blob: f1d03f752ac82f75a9c0f91060802a14c60a46d9 [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)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001328 SDValue Ops[] = {N1, N0};
1329 SDNode *CSENode;
1330 if (const BinaryWithFlagsSDNode *BinNode =
1331 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1332 CSENode = DAG.getNodeIfExists(
1333 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1334 BinNode->hasNoSignedWrap(), BinNode->isExact());
1335 } else {
1336 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1337 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001338 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001339 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001340 }
1341 }
1342
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001343 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001344}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001345
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001346/// getInputChainForNode - Given a node, return its input chain if it has one,
1347/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001348static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001349 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001350 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001351 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001352 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001353 return N->getOperand(NumOps-1);
1354 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001355 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001356 return N->getOperand(i);
1357 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001358 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001359}
1360
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001361SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001362 // If N has two operands, where one has an input chain equal to the other,
1363 // the 'other' chain is redundant.
1364 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001365 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001366 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001367 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001368 return N->getOperand(1);
1369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001370
Chris Lattner48fb92f2007-05-16 06:37:59 +00001371 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001372 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001373 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001374 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001375
Jim Laskey708d0db2006-10-04 16:53:27 +00001376 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001377 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001378
Jim Laskey0463e082006-10-07 23:37:56 +00001379 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001380 // encountered.
1381 for (unsigned i = 0; i < TFs.size(); ++i) {
1382 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001383
Jim Laskey708d0db2006-10-04 16:53:27 +00001384 // Check each of the operands.
1385 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001386 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001387
Jim Laskey708d0db2006-10-04 16:53:27 +00001388 switch (Op.getOpcode()) {
1389 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001390 // Entry tokens don't need to be added to the list. They are
1391 // rededundant.
1392 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001393 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001394
Jim Laskey708d0db2006-10-04 16:53:27 +00001395 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001396 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001397 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001398 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001399 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001400 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001401 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001402 Changed = true;
1403 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001404 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001405 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001406
Jim Laskey708d0db2006-10-04 16:53:27 +00001407 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001408 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001409 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001410 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001411 else
1412 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001413 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001414 }
1415 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001416 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001417
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001418 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001419
1420 // If we've change things around then replace token factor.
1421 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001422 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001423 // The entry token is the only possible outcome.
1424 Result = DAG.getEntryNode();
1425 } else {
1426 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001427 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001428 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001429
Jim Laskeydcf983c2006-10-13 23:32:28 +00001430 // Don't add users to work list.
1431 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001432 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001433
Jim Laskey708d0db2006-10-04 16:53:27 +00001434 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001435}
1436
Chris Lattneree322b42008-02-13 07:25:05 +00001437/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001438SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001439 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001440 // Replacing results may cause a different MERGE_VALUES to suddenly
1441 // be CSE'd with N, and carry its uses with it. Iterate until no
1442 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001443 // First add the users of this node to the work list so that they
1444 // can be tried again once they have new operands.
1445 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001446 do {
1447 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001448 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001449 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001450 removeFromWorkList(N);
1451 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001452 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001453}
1454
Evan Cheng92011002007-01-19 17:51:44 +00001455static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001456SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001457 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001458 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001459 SDValue N00 = N0.getOperand(0);
1460 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001461 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001462
Gabor Greiff304a7a2008-08-28 21:40:38 +00001463 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001464 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001465 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001466 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1467 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001468 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001469 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001470 N00.getOperand(1), N01));
1471 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001472 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001473
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001474 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001475}
1476
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001477SDValue DAGCombiner::visitADD(SDNode *N) {
1478 SDValue N0 = N->getOperand(0);
1479 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001480 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1481 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001482 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001483
1484 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001485 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001486 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001487 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001488
1489 // fold (add x, 0) -> x, vector edition
1490 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1491 return N0;
1492 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1493 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001494 }
Bill Wendling0864a752008-12-10 22:36:00 +00001495
Dan Gohman06563a82007-07-03 14:03:57 +00001496 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001497 if (N0.getOpcode() == ISD::UNDEF)
1498 return N0;
1499 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001500 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001501 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001502 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001503 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001504 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001505 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001506 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001507 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001508 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001509 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001510 // fold (add Sym, c) -> Sym+c
1511 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001512 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001513 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001514 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001515 GA->getOffset() +
1516 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001517 // fold ((c1-A)+c2) -> (c1+c2)-A
1518 if (N1C && N0.getOpcode() == ISD::SUB)
1519 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001520 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001521 DAG.getConstant(N1C->getAPIntValue()+
1522 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001523 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001524 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001525 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001526 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001527 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001528 // fold ((0-A) + B) -> B-A
1529 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1530 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001531 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001532 // fold (A + (0-B)) -> A-B
1533 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1534 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001535 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001536 // fold (A+(B-A)) -> B
1537 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001538 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001539 // fold ((B-A)+A) -> B
1540 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1541 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001542 // fold (A+(B-(A+C))) to (B-C)
1543 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001544 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001545 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001546 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001547 // fold (A+(B-(C+A))) to (B-C)
1548 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001549 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001550 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001551 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001552 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001553 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1554 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001555 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001556 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001557 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001558
Dale Johannesen8c766702008-12-02 01:30:54 +00001559 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1560 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1561 SDValue N00 = N0.getOperand(0);
1562 SDValue N01 = N0.getOperand(1);
1563 SDValue N10 = N1.getOperand(0);
1564 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001565
1566 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001567 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1568 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1569 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001570 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001571
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001572 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1573 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001574
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001575 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001576 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001577 APInt LHSZero, LHSOne;
1578 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001579 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001580
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001581 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001582 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001583
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001584 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1585 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001586 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1587 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1588 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1589 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001590 }
1591 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001592
Evan Cheng92011002007-01-19 17:51:44 +00001593 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001594 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001595 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001596 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001597 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001598 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001599 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001600 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001601 }
1602
Dan Gohman954f4902010-01-19 23:30:49 +00001603 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1604 if (N1.getOpcode() == ISD::SHL &&
1605 N1.getOperand(0).getOpcode() == ISD::SUB)
1606 if (ConstantSDNode *C =
1607 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1608 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001609 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1610 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001611 N1.getOperand(0).getOperand(1),
1612 N1.getOperand(1)));
1613 if (N0.getOpcode() == ISD::SHL &&
1614 N0.getOperand(0).getOpcode() == ISD::SUB)
1615 if (ConstantSDNode *C =
1616 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1617 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001618 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1619 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001620 N0.getOperand(0).getOperand(1),
1621 N0.getOperand(1)));
1622
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001623 if (N1.getOpcode() == ISD::AND) {
1624 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001625 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001626 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1627 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001628
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001629 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1630 // and similar xforms where the inner op is either ~0 or 0.
1631 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001632 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001633 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1634 }
1635 }
1636
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001637 // add (sext i1), X -> sub X, (zext i1)
1638 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1639 N0.getOperand(0).getValueType() == MVT::i1 &&
1640 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001641 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001642 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1643 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1644 }
1645
Evan Chengf1005572010-04-28 07:10:39 +00001646 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001647}
1648
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001649SDValue DAGCombiner::visitADDC(SDNode *N) {
1650 SDValue N0 = N->getOperand(0);
1651 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001652 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1653 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001654 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001655
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001656 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001657 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001658 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001659 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001660 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001661
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001662 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001663 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001664 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001665
Chris Lattner47206662007-03-04 20:40:38 +00001666 // fold (addc x, 0) -> x + no carry out
1667 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001668 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001669 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001670
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001671 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001672 APInt LHSZero, LHSOne;
1673 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001674 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001675
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001676 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001677 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001678
Chris Lattner47206662007-03-04 20:40:38 +00001679 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1680 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001681 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001682 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001683 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001684 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001685 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001686
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001687 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001688}
1689
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001690SDValue DAGCombiner::visitADDE(SDNode *N) {
1691 SDValue N0 = N->getOperand(0);
1692 SDValue N1 = N->getOperand(1);
1693 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001694 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1695 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001696
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001697 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001698 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001699 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001700 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001701
Chris Lattner47206662007-03-04 20:40:38 +00001702 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001703 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001704 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001705
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001706 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001707}
1708
Eric Christophere5ca1e02011-02-16 04:50:12 +00001709// Since it may not be valid to emit a fold to zero for vector initializers
1710// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001711static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001712 SelectionDAG &DAG,
1713 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001714 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001715 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001716 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1717 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001718 return SDValue();
1719}
1720
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001721SDValue DAGCombiner::visitSUB(SDNode *N) {
1722 SDValue N0 = N->getOperand(0);
1723 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001724 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1725 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001726 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001727 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001728 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001729
Dan Gohmana8665142007-06-25 16:23:39 +00001730 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001731 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001732 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001733 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001734
1735 // fold (sub x, 0) -> x, vector edition
1736 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1737 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001738 }
Bill Wendling0864a752008-12-10 22:36:00 +00001739
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001740 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001741 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001742 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001743 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001744 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001745 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001746 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001747 // fold (sub x, c) -> (add x, -c)
1748 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001749 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001750 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001751 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1752 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001753 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001754 // fold A-(A-B) -> B
1755 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1756 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001757 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001758 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001759 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001760 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001761 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001762 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001763 // fold C2-(A+C1) -> (C2-C1)-A
1764 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001765 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1766 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001767 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001768 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001769 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001770 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001771 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001772 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1773 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001774 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001775 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001776 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001777 // fold ((A+(C+B))-B) -> A+C
1778 if (N0.getOpcode() == ISD::ADD &&
1779 N0.getOperand(1).getOpcode() == ISD::ADD &&
1780 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001781 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001782 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001783 // fold ((A-(B-C))-C) -> A-B
1784 if (N0.getOpcode() == ISD::SUB &&
1785 N0.getOperand(1).getOpcode() == ISD::SUB &&
1786 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001787 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001788 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001789
Dan Gohman06563a82007-07-03 14:03:57 +00001790 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001791 if (N0.getOpcode() == ISD::UNDEF)
1792 return N0;
1793 if (N1.getOpcode() == ISD::UNDEF)
1794 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001795
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001796 // If the relocation model supports it, consider symbol offsets.
1797 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001798 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001799 // fold (sub Sym, c) -> Sym-c
1800 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001801 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001802 GA->getOffset() -
1803 (uint64_t)N1C->getSExtValue());
1804 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1805 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1806 if (GA->getGlobal() == GB->getGlobal())
1807 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1808 VT);
1809 }
1810
Evan Chengf1005572010-04-28 07:10:39 +00001811 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001812}
1813
Craig Topper43a1bd62012-01-07 09:06:39 +00001814SDValue DAGCombiner::visitSUBC(SDNode *N) {
1815 SDValue N0 = N->getOperand(0);
1816 SDValue N1 = N->getOperand(1);
1817 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1818 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1819 EVT VT = N0.getValueType();
1820
1821 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001822 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001823 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1824 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001825 MVT::Glue));
1826
1827 // fold (subc x, x) -> 0 + no borrow
1828 if (N0 == N1)
1829 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001830 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001831 MVT::Glue));
1832
1833 // fold (subc x, 0) -> x + no borrow
1834 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001835 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001836 MVT::Glue));
1837
1838 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1839 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001840 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1841 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001842 MVT::Glue));
1843
1844 return SDValue();
1845}
1846
1847SDValue DAGCombiner::visitSUBE(SDNode *N) {
1848 SDValue N0 = N->getOperand(0);
1849 SDValue N1 = N->getOperand(1);
1850 SDValue CarryIn = N->getOperand(2);
1851
1852 // fold (sube x, y, false) -> (subc x, y)
1853 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001854 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001855
1856 return SDValue();
1857}
1858
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001859SDValue DAGCombiner::visitMUL(SDNode *N) {
1860 SDValue N0 = N->getOperand(0);
1861 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001862 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001863
Dan Gohman06563a82007-07-03 14:03:57 +00001864 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001865 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001866 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001867
1868 bool N0IsConst = false;
1869 bool N1IsConst = false;
1870 APInt ConstValue0, ConstValue1;
1871 // fold vector ops
1872 if (VT.isVector()) {
1873 SDValue FoldedVOp = SimplifyVBinOp(N);
1874 if (FoldedVOp.getNode()) return FoldedVOp;
1875
1876 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1877 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1878 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001879 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001880 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1881 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001882 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001883 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1884 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001885 }
1886
Nate Begeman21158fc2005-09-01 00:19:25 +00001887 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001888 if (N0IsConst && N1IsConst)
1889 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1890
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001891 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001892 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001893 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001894 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001895 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001896 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001897 // We require a splat of the entire scalar bit width for non-contiguous
1898 // bit patterns.
1899 bool IsFullSplat =
1900 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001901 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001902 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001903 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001904 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001905 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001906 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001907 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001908 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001909 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001910 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001911 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001912 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001913 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001914 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001915 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001916 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001917 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001918 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001919 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001920 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001921 DAG.getConstant(Log2Val,
1922 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001923 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001924
1925 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001926 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001927 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001928 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1929 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001930 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001931 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001932 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001933 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001934 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001935 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001936
Chris Lattner324871e2006-03-01 03:44:24 +00001937 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1938 // use.
1939 {
Craig Topperc0196b12014-04-14 00:51:57 +00001940 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001941 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001942 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001943 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1944 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001945 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001946 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001947 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001948 isa<ConstantSDNode>(N1.getOperand(1)) &&
1949 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001950 Sh = N1; Y = N0;
1951 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001952
Gabor Greiff304a7a2008-08-28 21:40:38 +00001953 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001954 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001955 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001956 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001957 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001958 }
1959 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001960
Chris Lattnerf29f5202006-03-04 23:33:26 +00001961 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001962 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1963 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1964 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001965 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1966 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001967 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001968 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001969 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001970
Nate Begeman22e251a2006-02-03 06:46:56 +00001971 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001972 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001973 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001974 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001975
Evan Chengf1005572010-04-28 07:10:39 +00001976 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001977}
1978
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001979SDValue DAGCombiner::visitSDIV(SDNode *N) {
1980 SDValue N0 = N->getOperand(0);
1981 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00001982 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1983 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001984 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001985
Dan Gohmana8665142007-06-25 16:23:39 +00001986 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001987 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001988 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001989 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001990 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001991
Nate Begeman21158fc2005-09-01 00:19:25 +00001992 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001993 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001994 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001995 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001996 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001997 return N0;
1998 // fold (sdiv X, -1) -> 0-X
1999 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002000 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002001 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002002 // If we know the sign bits of both operands are zero, strength reduce to a
2003 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002004 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002005 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002006 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002007 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002008 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002009
Nate Begeman57b35672006-02-17 07:26:20 +00002010 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002011 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2012 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002013 // If dividing by powers of two is cheap, then don't perform the following
2014 // fold.
2015 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002016 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002017
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002018 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002019
Chris Lattner471627c2006-02-16 08:02:36 +00002020 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002021 SDValue SGN =
2022 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2023 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2024 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002025 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002026
Chris Lattner471627c2006-02-16 08:02:36 +00002027 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002028 SDValue SRL =
2029 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2030 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2031 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002032 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002033 AddToWorkList(SRL.getNode());
2034 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002035 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002036 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002037
Nate Begeman4dd38312005-10-21 00:02:42 +00002038 // If we're dividing by a positive value, we're done. Otherwise, we must
2039 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002040 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002041 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002042
Gabor Greiff304a7a2008-08-28 21:40:38 +00002043 AddToWorkList(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002044 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002045 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002046
Nate Begemanc6f067a2005-10-20 02:15:44 +00002047 // if integer divide is expensive and we satisfy the requirements, emit an
2048 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002049 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002050 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002051 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002052 }
Dan Gohmana8665142007-06-25 16:23:39 +00002053
Dan Gohman06563a82007-07-03 14:03:57 +00002054 // undef / X -> 0
2055 if (N0.getOpcode() == ISD::UNDEF)
2056 return DAG.getConstant(0, VT);
2057 // X / undef -> undef
2058 if (N1.getOpcode() == ISD::UNDEF)
2059 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002060
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002061 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002062}
2063
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002064SDValue DAGCombiner::visitUDIV(SDNode *N) {
2065 SDValue N0 = N->getOperand(0);
2066 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002067 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2068 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002069 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002070
Dan Gohmana8665142007-06-25 16:23:39 +00002071 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002072 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002073 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002074 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002075 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002076
Nate Begeman21158fc2005-09-01 00:19:25 +00002077 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002078 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002079 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002080 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002081 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002082 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002083 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002084 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002085 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002086 if (N1.getOpcode() == ISD::SHL) {
2087 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002088 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002089 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002090 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002091 N1.getOperand(1),
2092 DAG.getConstant(SHC->getAPIntValue()
2093 .logBase2(),
2094 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002095 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002096 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002097 }
2098 }
2099 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002100 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002101 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002102 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002103 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002104 }
Dan Gohmana8665142007-06-25 16:23:39 +00002105
Dan Gohman06563a82007-07-03 14:03:57 +00002106 // undef / X -> 0
2107 if (N0.getOpcode() == ISD::UNDEF)
2108 return DAG.getConstant(0, VT);
2109 // X / undef -> undef
2110 if (N1.getOpcode() == ISD::UNDEF)
2111 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002112
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002113 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002114}
2115
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002116SDValue DAGCombiner::visitSREM(SDNode *N) {
2117 SDValue N0 = N->getOperand(0);
2118 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002119 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2120 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002121 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002122
Nate Begeman21158fc2005-09-01 00:19:25 +00002123 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002124 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002125 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002126 // If we know the sign bits of both operands are zero, strength reduce to a
2127 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002128 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002129 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002130 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002131 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002132
Dan Gohman9a693412007-11-26 23:46:11 +00002133 // If X/C can be simplified by the division-by-constant logic, lower
2134 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002135 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002136 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002137 AddToWorkList(Div.getNode());
2138 SDValue OptimizedDiv = combine(Div.getNode());
2139 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002140 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002141 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002142 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002143 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002144 return Sub;
2145 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002146 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002147
Dan Gohman06563a82007-07-03 14:03:57 +00002148 // undef % X -> 0
2149 if (N0.getOpcode() == ISD::UNDEF)
2150 return DAG.getConstant(0, VT);
2151 // X % undef -> undef
2152 if (N1.getOpcode() == ISD::UNDEF)
2153 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002154
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002155 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002156}
2157
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002158SDValue DAGCombiner::visitUREM(SDNode *N) {
2159 SDValue N0 = N->getOperand(0);
2160 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002161 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2162 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002163 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002164
Nate Begeman21158fc2005-09-01 00:19:25 +00002165 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002166 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002167 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002168 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002169 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002170 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002171 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002172 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2173 if (N1.getOpcode() == ISD::SHL) {
2174 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002175 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002176 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002177 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002178 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002179 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002180 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002181 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002182 }
2183 }
2184 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002185
Dan Gohman9a693412007-11-26 23:46:11 +00002186 // If X/C can be simplified by the division-by-constant logic, lower
2187 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002188 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002189 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002190 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002191 SDValue OptimizedDiv = combine(Div.getNode());
2192 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002193 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002194 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002195 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002196 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002197 return Sub;
2198 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002199 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002200
Dan Gohman06563a82007-07-03 14:03:57 +00002201 // undef % X -> 0
2202 if (N0.getOpcode() == ISD::UNDEF)
2203 return DAG.getConstant(0, VT);
2204 // X % undef -> undef
2205 if (N1.getOpcode() == ISD::UNDEF)
2206 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002207
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002208 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002209}
2210
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002211SDValue DAGCombiner::visitMULHS(SDNode *N) {
2212 SDValue N0 = N->getOperand(0);
2213 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002214 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002215 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002216 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002217
Nate Begeman21158fc2005-09-01 00:19:25 +00002218 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002219 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002220 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002221 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002222 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002223 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002224 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002225 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002226 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002227 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002228 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002229
Chris Lattner10bd29f2010-12-13 08:39:01 +00002230 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2231 // plus a shift.
2232 if (VT.isSimple() && !VT.isVector()) {
2233 MVT Simple = VT.getSimpleVT();
2234 unsigned SimpleSize = Simple.getSizeInBits();
2235 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2236 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2237 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2238 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2239 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002240 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002241 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002242 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2243 }
2244 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002245
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002246 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002247}
2248
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002249SDValue DAGCombiner::visitMULHU(SDNode *N) {
2250 SDValue N0 = N->getOperand(0);
2251 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002252 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002253 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002254 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002255
Nate Begeman21158fc2005-09-01 00:19:25 +00002256 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002257 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002258 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002259 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002260 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002261 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002262 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002263 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002264 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002265
Chris Lattner10bd29f2010-12-13 08:39:01 +00002266 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2267 // plus a shift.
2268 if (VT.isSimple() && !VT.isVector()) {
2269 MVT Simple = VT.getSimpleVT();
2270 unsigned SimpleSize = Simple.getSizeInBits();
2271 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2272 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2273 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2274 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2275 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2276 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002277 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002278 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2279 }
2280 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002281
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002282 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002283}
2284
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002285/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2286/// compute two values. LoOp and HiOp give the opcodes for the two computations
2287/// that are being performed. Return true if a simplification was made.
2288///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002289SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002290 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002291 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002292 bool HiExists = N->hasAnyUseOfValue(1);
2293 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002294 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002295 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002296 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002297 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002298 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002299 }
2300
2301 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002302 bool LoExists = N->hasAnyUseOfValue(0);
2303 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002304 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002305 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002306 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002307 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002308 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002309 }
2310
Evan Chengece4c682007-11-08 09:25:29 +00002311 // If both halves are used, return as it is.
2312 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002313 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002314
2315 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002316 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002317 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002318 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002319 AddToWorkList(Lo.getNode());
2320 SDValue LoOpt = combine(Lo.getNode());
2321 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002322 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002323 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002324 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002325 }
2326
Evan Chengece4c682007-11-08 09:25:29 +00002327 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002328 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002329 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002330 AddToWorkList(Hi.getNode());
2331 SDValue HiOpt = combine(Hi.getNode());
2332 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002333 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002334 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002335 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002336 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002337
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002338 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002339}
2340
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002341SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2342 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002343 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002344
Chris Lattner15090e12010-12-15 06:04:19 +00002345 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002346 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002347
2348 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2349 // plus a shift.
2350 if (VT.isSimple() && !VT.isVector()) {
2351 MVT Simple = VT.getSimpleVT();
2352 unsigned SimpleSize = Simple.getSizeInBits();
2353 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2354 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2355 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2356 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2357 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2358 // Compute the high part as N1.
2359 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002360 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002361 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2362 // Compute the low part as N0.
2363 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2364 return CombineTo(N, Lo, Hi);
2365 }
2366 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002367
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002368 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002369}
2370
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002371SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2372 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002373 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002374
Chris Lattner15090e12010-12-15 06:04:19 +00002375 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002376 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002377
Chris Lattner15090e12010-12-15 06:04:19 +00002378 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2379 // plus a shift.
2380 if (VT.isSimple() && !VT.isVector()) {
2381 MVT Simple = VT.getSimpleVT();
2382 unsigned SimpleSize = Simple.getSizeInBits();
2383 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2384 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2385 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2386 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2387 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2388 // Compute the high part as N1.
2389 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002390 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002391 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2392 // Compute the low part as N0.
2393 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2394 return CombineTo(N, Lo, Hi);
2395 }
2396 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002397
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002398 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002399}
2400
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002401SDValue DAGCombiner::visitSMULO(SDNode *N) {
2402 // (smulo x, 2) -> (saddo x, x)
2403 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2404 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002405 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002406 N->getOperand(0), N->getOperand(0));
2407
2408 return SDValue();
2409}
2410
2411SDValue DAGCombiner::visitUMULO(SDNode *N) {
2412 // (umulo x, 2) -> (uaddo x, x)
2413 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2414 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002415 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002416 N->getOperand(0), N->getOperand(0));
2417
2418 return SDValue();
2419}
2420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002421SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2422 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
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
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002428SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2429 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002430 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002431
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002432 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002433}
2434
Chris Lattner8d6fc202006-05-05 05:51:50 +00002435/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2436/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002437SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2438 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002439 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002440 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002441
Dan Gohmandd5286d2010-01-14 03:08:49 +00002442 // Bail early if none of these transforms apply.
2443 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2444
Chris Lattner002ee912006-05-05 06:31:05 +00002445 // For each of OP in AND/OR/XOR:
2446 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2447 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2448 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002449 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002450 //
2451 // do not sink logical op inside of a vector extend, since it may combine
2452 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002453 EVT Op0VT = N0.getOperand(0).getValueType();
2454 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002455 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002456 // Avoid infinite looping with PromoteIntBinOp.
2457 (N0.getOpcode() == ISD::ANY_EXTEND &&
2458 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002459 (N0.getOpcode() == ISD::TRUNCATE &&
2460 (!TLI.isZExtFree(VT, Op0VT) ||
2461 !TLI.isTruncateFree(Op0VT, VT)) &&
2462 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002463 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002464 Op0VT == N1.getOperand(0).getValueType() &&
2465 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002466 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002467 N0.getOperand(0).getValueType(),
2468 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002469 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002470 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002471 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002472
Chris Lattner5ac42932006-05-05 06:10:43 +00002473 // For each of OP in SHL/SRL/SRA/AND...
2474 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2475 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2476 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002477 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002478 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002479 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002480 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002481 N0.getOperand(0).getValueType(),
2482 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002483 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002484 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002485 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002486 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002487
Nadav Rotemb0783502012-04-01 19:31:22 +00002488 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2489 // Only perform this optimization after type legalization and before
2490 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2491 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2492 // we don't want to undo this promotion.
2493 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2494 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002495 if ((N0.getOpcode() == ISD::BITCAST ||
2496 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2497 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002498 SDValue In0 = N0.getOperand(0);
2499 SDValue In1 = N1.getOperand(0);
2500 EVT In0Ty = In0.getValueType();
2501 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002502 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002503 // If both incoming values are integers, and the original types are the
2504 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002505 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002506 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2507 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002508 AddToWorkList(Op.getNode());
2509 return BC;
2510 }
2511 }
2512
2513 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2514 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2515 // If both shuffles use the same mask, and both shuffle within a single
2516 // vector, then it is worthwhile to move the swizzle after the operation.
2517 // The type-legalizer generates this pattern when loading illegal
2518 // vector types from memory. In many cases this allows additional shuffle
2519 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002520 // There are other cases where moving the shuffle after the xor/and/or
2521 // is profitable even if shuffles don't perform a swizzle.
2522 // If both shuffles use the same mask, and both shuffles have the same first
2523 // or second operand, then it might still be profitable to move the shuffle
2524 // after the xor/and/or operation.
2525 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002526 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2527 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002528
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002529 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002530 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002531
Nadav Rotemb0783502012-04-01 19:31:22 +00002532 // Check that both shuffles use the same mask. The masks are known to be of
2533 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002534 // Check also that shuffles have only one use to avoid introducing extra
2535 // instructions.
2536 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2537 SVN0->getMask().equals(SVN1->getMask())) {
2538 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002539
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002540 // Don't try to fold this node if it requires introducing a
2541 // build vector of all zeros that might be illegal at this stage.
2542 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2543 if (!LegalTypes)
2544 ShOp = DAG.getConstant(0, VT);
2545 else
2546 ShOp = SDValue();
2547 }
2548
2549 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2550 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2551 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2552 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2553 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2554 N0->getOperand(0), N1->getOperand(0));
2555 AddToWorkList(NewNode.getNode());
2556 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2557 &SVN0->getMask()[0]);
2558 }
2559
2560 // Don't try to fold this node if it requires introducing a
2561 // build vector of all zeros that might be illegal at this stage.
2562 ShOp = N0->getOperand(0);
2563 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2564 if (!LegalTypes)
2565 ShOp = DAG.getConstant(0, VT);
2566 else
2567 ShOp = SDValue();
2568 }
2569
2570 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2571 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2572 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2573 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2574 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2575 N0->getOperand(1), N1->getOperand(1));
2576 AddToWorkList(NewNode.getNode());
2577 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2578 &SVN0->getMask()[0]);
2579 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002580 }
2581 }
Craig Topper9c3da312012-04-09 07:19:09 +00002582
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002583 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002584}
2585
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002586SDValue DAGCombiner::visitAND(SDNode *N) {
2587 SDValue N0 = N->getOperand(0);
2588 SDValue N1 = N->getOperand(1);
2589 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002590 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2591 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002592 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002593 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002594
Dan Gohmana8665142007-06-25 16:23:39 +00002595 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002596 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002597 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002598 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002599
2600 // fold (and x, 0) -> 0, vector edition
2601 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2602 return N0;
2603 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2604 return N1;
2605
2606 // fold (and x, -1) -> x, vector edition
2607 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2608 return N1;
2609 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2610 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002611 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002612
Dan Gohman06563a82007-07-03 14:03:57 +00002613 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002614 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002615 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002616 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002617 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002618 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002619 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002620 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002621 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002622 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002623 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002624 return N0;
2625 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002626 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002627 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002628 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002629 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002630 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002631 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002632 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002633 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002634 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002635 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002636 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002637 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002638 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2639 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002640 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002641 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002642 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002643 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002644 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002645 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002646
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002647 // Replace uses of the AND with uses of the Zero extend node.
2648 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002649
Chris Lattner49beaf42006-02-02 07:17:31 +00002650 // We actually want to replace all uses of the any_extend with the
2651 // zero_extend, to avoid duplicating things. This will later cause this
2652 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002653 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002654 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002655 }
2656 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002657 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002658 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2659 // already be zero by virtue of the width of the base type of the load.
2660 //
2661 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2662 // more cases.
2663 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2664 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2665 N0.getOpcode() == ISD::LOAD) {
2666 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2667 N0 : N0.getOperand(0) );
2668
2669 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2670 // This can be a pure constant or a vector splat, in which case we treat the
2671 // vector as a scalar and use the splat value.
2672 APInt Constant = APInt::getNullValue(1);
2673 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2674 Constant = C->getAPIntValue();
2675 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2676 APInt SplatValue, SplatUndef;
2677 unsigned SplatBitSize;
2678 bool HasAnyUndefs;
2679 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2680 SplatBitSize, HasAnyUndefs);
2681 if (IsSplat) {
2682 // Undef bits can contribute to a possible optimisation if set, so
2683 // set them.
2684 SplatValue |= SplatUndef;
2685
2686 // The splat value may be something like "0x00FFFFFF", which means 0 for
2687 // the first vector value and FF for the rest, repeating. We need a mask
2688 // that will apply equally to all members of the vector, so AND all the
2689 // lanes of the constant together.
2690 EVT VT = Vector->getValueType(0);
2691 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002692
2693 // If the splat value has been compressed to a bitlength lower
2694 // than the size of the vector lane, we need to re-expand it to
2695 // the lane size.
2696 if (BitWidth > SplatBitSize)
2697 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2698 SplatBitSize < BitWidth;
2699 SplatBitSize = SplatBitSize * 2)
2700 SplatValue |= SplatValue.shl(SplatBitSize);
2701
James Molloy862fe492012-02-20 12:02:38 +00002702 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002703 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002704 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2705 }
2706 }
2707
2708 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2709 // actually legal and isn't going to get expanded, else this is a false
2710 // optimisation.
2711 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2712 Load->getMemoryVT());
2713
2714 // Resize the constant to the same size as the original memory access before
2715 // extension. If it is still the AllOnesValue then this AND is completely
2716 // unneeded.
2717 Constant =
2718 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2719
2720 bool B;
2721 switch (Load->getExtensionType()) {
2722 default: B = false; break;
2723 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2724 case ISD::ZEXTLOAD:
2725 case ISD::NON_EXTLOAD: B = true; break;
2726 }
2727
2728 if (B && Constant.isAllOnesValue()) {
2729 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2730 // preserve semantics once we get rid of the AND.
2731 SDValue NewLoad(Load, 0);
2732 if (Load->getExtensionType() == ISD::EXTLOAD) {
2733 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002734 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002735 Load->getChain(), Load->getBasePtr(),
2736 Load->getOffset(), Load->getMemoryVT(),
2737 Load->getMemOperand());
2738 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002739 if (Load->getNumValues() == 3) {
2740 // PRE/POST_INC loads have 3 values.
2741 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2742 NewLoad.getValue(2) };
2743 CombineTo(Load, To, 3, true);
2744 } else {
2745 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2746 }
James Molloy862fe492012-02-20 12:02:38 +00002747 }
2748
2749 // Fold the AND away, taking care not to fold to the old load node if we
2750 // replaced it.
2751 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2752
2753 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2754 }
2755 }
Nate Begeman049b7482005-09-09 19:49:52 +00002756 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2757 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2758 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2759 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002760
Tom Stellardb9a02332014-06-10 16:01:25 +00002761 if (LR == RR && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002762 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002763 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellardb9a02332014-06-10 16:01:25 +00002764 if (TLI.isConstFalseVal(LR.getNode()) && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002765 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002766 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002767 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002768 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002769 }
Bill Wendling86171912009-01-30 20:43:18 +00002770 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellardb9a02332014-06-10 16:01:25 +00002771 if (TLI.isConstTrueVal(LR.getNode()) && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002772 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002773 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002774 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002775 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002776 }
Bill Wendling86171912009-01-30 20:43:18 +00002777 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellardb9a02332014-06-10 16:01:25 +00002778 if (TLI.isConstTrueVal(LR.getNode()) && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002779 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002780 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002781 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002782 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002783 }
2784 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002785 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2786 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2787 Op0 == Op1 && LL.getValueType().isInteger() &&
2788 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2789 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2790 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2791 cast<ConstantSDNode>(RR)->isNullValue()))) {
2792 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2793 LL, DAG.getConstant(1, LL.getValueType()));
2794 AddToWorkList(ADDNode.getNode());
2795 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2796 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2797 }
Nate Begeman049b7482005-09-09 19:49:52 +00002798 // canonicalize equivalent to ll == rl
2799 if (LL == RR && LR == RL) {
2800 Op1 = ISD::getSetCCSwappedOperands(Op1);
2801 std::swap(RL, RR);
2802 }
2803 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002804 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002805 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002806 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002807 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002808 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2809 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002810 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002811 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002812 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002813 }
2814 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002815
Bill Wendling86171912009-01-30 20:43:18 +00002816 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002817 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002818 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002819 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002820 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002821
Nate Begemandc7bba92006-02-03 22:24:05 +00002822 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2823 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002824 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002825 SimplifyDemandedBits(SDValue(N, 0)))
2826 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002827
Nate Begeman02b23c62005-10-13 03:11:28 +00002828 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002829 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002830 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002831 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002832 // If we zero all the possible extended bits, then we can turn this into
2833 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002834 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002835 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002836 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002837 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002838 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002839 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002840 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002841 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002842 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002843 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002844 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002845 }
2846 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002847 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002848 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002849 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002850 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002851 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002852 // If we zero all the possible extended bits, then we can turn this into
2853 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002854 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002855 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002856 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002857 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002858 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002859 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002860 LN0->getChain(), LN0->getBasePtr(),
2861 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002862 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002863 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002864 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002865 }
2866 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002867
Chris Lattnerf0032b32006-02-28 06:49:37 +00002868 // fold (and (load x), 255) -> (zextload x, i8)
2869 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002870 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2871 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2872 (N0.getOpcode() == ISD::ANY_EXTEND &&
2873 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2874 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2875 LoadSDNode *LN0 = HasAnyExt
2876 ? cast<LoadSDNode>(N0.getOperand(0))
2877 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002878 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002879 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002880 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002881 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2882 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2883 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002884
Evan Cheng166a4e62010-01-06 19:38:29 +00002885 if (ExtVT == LoadedVT &&
2886 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002887 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002888
2889 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002890 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002891 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2892 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002893 AddToWorkList(N);
2894 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2895 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2896 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002897
Chris Lattner88de3842010-01-07 21:53:27 +00002898 // Do not change the width of a volatile load.
2899 // Do not generate loads of non-round integer types since these can
2900 // be expensive (and would be wrong if the type is not byte sized).
2901 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2902 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2903 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002904
Chris Lattner88de3842010-01-07 21:53:27 +00002905 unsigned Alignment = LN0->getAlignment();
2906 SDValue NewPtr = LN0->getBasePtr();
2907
2908 // For big endian targets, we need to add an offset to the pointer
2909 // to load the correct bytes. For little endian systems, we merely
2910 // need to read fewer bytes from the same pointer.
2911 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002912 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2913 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2914 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002915 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002916 NewPtr, DAG.getConstant(PtrOff, PtrType));
2917 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002918 }
Chris Lattner88de3842010-01-07 21:53:27 +00002919
2920 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002921
Chris Lattner88de3842010-01-07 21:53:27 +00002922 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2923 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002924 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002925 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002926 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002927 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002928 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002929 AddToWorkList(N);
2930 CombineTo(LN0, Load, Load.getValue(1));
2931 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002932 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002933 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002934 }
2935 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002936
Evan Chenge6a3b032012-07-17 18:54:11 +00002937 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2938 VT.getSizeInBits() <= 64) {
2939 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2940 APInt ADDC = ADDI->getAPIntValue();
2941 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2942 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2943 // immediate for an add, but it is legal if its top c2 bits are set,
2944 // transform the ADD so the immediate doesn't need to be materialized
2945 // in a register.
2946 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2947 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2948 SRLI->getZExtValue());
2949 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2950 ADDC |= Mask;
2951 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2952 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002953 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002954 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2955 CombineTo(N0.getNode(), NewAdd);
2956 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2957 }
2958 }
2959 }
2960 }
2961 }
2962 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002963
Tim Northover819bfb52013-08-27 13:46:45 +00002964 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2965 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2966 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2967 N0.getOperand(1), false);
2968 if (BSwap.getNode())
2969 return BSwap;
2970 }
2971
Evan Chengf1005572010-04-28 07:10:39 +00002972 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002973}
2974
Evan Cheng4c0bd962011-06-21 06:01:08 +00002975/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2976///
2977SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2978 bool DemandHighBits) {
2979 if (!LegalOperations)
2980 return SDValue();
2981
2982 EVT VT = N->getValueType(0);
2983 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2984 return SDValue();
2985 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2986 return SDValue();
2987
2988 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2989 bool LookPassAnd0 = false;
2990 bool LookPassAnd1 = false;
2991 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2992 std::swap(N0, N1);
2993 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2994 std::swap(N0, N1);
2995 if (N0.getOpcode() == ISD::AND) {
2996 if (!N0.getNode()->hasOneUse())
2997 return SDValue();
2998 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2999 if (!N01C || N01C->getZExtValue() != 0xFF00)
3000 return SDValue();
3001 N0 = N0.getOperand(0);
3002 LookPassAnd0 = true;
3003 }
3004
3005 if (N1.getOpcode() == ISD::AND) {
3006 if (!N1.getNode()->hasOneUse())
3007 return SDValue();
3008 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3009 if (!N11C || N11C->getZExtValue() != 0xFF)
3010 return SDValue();
3011 N1 = N1.getOperand(0);
3012 LookPassAnd1 = true;
3013 }
3014
3015 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3016 std::swap(N0, N1);
3017 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3018 return SDValue();
3019 if (!N0.getNode()->hasOneUse() ||
3020 !N1.getNode()->hasOneUse())
3021 return SDValue();
3022
3023 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3024 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3025 if (!N01C || !N11C)
3026 return SDValue();
3027 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3028 return SDValue();
3029
3030 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3031 SDValue N00 = N0->getOperand(0);
3032 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3033 if (!N00.getNode()->hasOneUse())
3034 return SDValue();
3035 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3036 if (!N001C || N001C->getZExtValue() != 0xFF)
3037 return SDValue();
3038 N00 = N00.getOperand(0);
3039 LookPassAnd0 = true;
3040 }
3041
3042 SDValue N10 = N1->getOperand(0);
3043 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3044 if (!N10.getNode()->hasOneUse())
3045 return SDValue();
3046 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3047 if (!N101C || N101C->getZExtValue() != 0xFF00)
3048 return SDValue();
3049 N10 = N10.getOperand(0);
3050 LookPassAnd1 = true;
3051 }
3052
3053 if (N00 != N10)
3054 return SDValue();
3055
Tim Northover819bfb52013-08-27 13:46:45 +00003056 // Make sure everything beyond the low halfword gets set to zero since the SRL
3057 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003058 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003059 if (DemandHighBits && OpSizeInBits > 16) {
3060 // If the left-shift isn't masked out then the only way this is a bswap is
3061 // if all bits beyond the low 8 are 0. In that case the entire pattern
3062 // reduces to a left shift anyway: leave it for other parts of the combiner.
3063 if (!LookPassAnd0)
3064 return SDValue();
3065
3066 // However, if the right shift isn't masked out then it might be because
3067 // it's not needed. See if we can spot that too.
3068 if (!LookPassAnd1 &&
3069 !DAG.MaskedValueIsZero(
3070 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3071 return SDValue();
3072 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003073
Andrew Trickef9de2a2013-05-25 02:42:55 +00003074 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003075 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003076 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003077 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3078 return Res;
3079}
3080
3081/// isBSwapHWordElement - Return true if the specified node is an element
3082/// that makes up a 32-bit packed halfword byteswap. i.e.
3083/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003084static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003085 if (!N.getNode()->hasOneUse())
3086 return false;
3087
3088 unsigned Opc = N.getOpcode();
3089 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3090 return false;
3091
3092 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3093 if (!N1C)
3094 return false;
3095
3096 unsigned Num;
3097 switch (N1C->getZExtValue()) {
3098 default:
3099 return false;
3100 case 0xFF: Num = 0; break;
3101 case 0xFF00: Num = 1; break;
3102 case 0xFF0000: Num = 2; break;
3103 case 0xFF000000: Num = 3; break;
3104 }
3105
3106 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3107 SDValue N0 = N.getOperand(0);
3108 if (Opc == ISD::AND) {
3109 if (Num == 0 || Num == 2) {
3110 // (x >> 8) & 0xff
3111 // (x >> 8) & 0xff0000
3112 if (N0.getOpcode() != ISD::SRL)
3113 return false;
3114 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3115 if (!C || C->getZExtValue() != 8)
3116 return false;
3117 } else {
3118 // (x << 8) & 0xff00
3119 // (x << 8) & 0xff000000
3120 if (N0.getOpcode() != ISD::SHL)
3121 return false;
3122 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3123 if (!C || C->getZExtValue() != 8)
3124 return false;
3125 }
3126 } else if (Opc == ISD::SHL) {
3127 // (x & 0xff) << 8
3128 // (x & 0xff0000) << 8
3129 if (Num != 0 && Num != 2)
3130 return false;
3131 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3132 if (!C || C->getZExtValue() != 8)
3133 return false;
3134 } else { // Opc == ISD::SRL
3135 // (x & 0xff00) >> 8
3136 // (x & 0xff000000) >> 8
3137 if (Num != 1 && Num != 3)
3138 return false;
3139 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3140 if (!C || C->getZExtValue() != 8)
3141 return false;
3142 }
3143
3144 if (Parts[Num])
3145 return false;
3146
3147 Parts[Num] = N0.getOperand(0).getNode();
3148 return true;
3149}
3150
3151/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3152/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3153/// => (rotl (bswap x), 16)
3154SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3155 if (!LegalOperations)
3156 return SDValue();
3157
3158 EVT VT = N->getValueType(0);
3159 if (VT != MVT::i32)
3160 return SDValue();
3161 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3162 return SDValue();
3163
Craig Topperc0196b12014-04-14 00:51:57 +00003164 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003165 // Look for either
3166 // (or (or (and), (and)), (or (and), (and)))
3167 // (or (or (or (and), (and)), (and)), (and))
3168 if (N0.getOpcode() != ISD::OR)
3169 return SDValue();
3170 SDValue N00 = N0.getOperand(0);
3171 SDValue N01 = N0.getOperand(1);
3172
Evan Chengbf0baa92012-12-13 01:34:32 +00003173 if (N1.getOpcode() == ISD::OR &&
3174 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003175 // (or (or (and), (and)), (or (and), (and)))
3176 SDValue N000 = N00.getOperand(0);
3177 if (!isBSwapHWordElement(N000, Parts))
3178 return SDValue();
3179
3180 SDValue N001 = N00.getOperand(1);
3181 if (!isBSwapHWordElement(N001, Parts))
3182 return SDValue();
3183 SDValue N010 = N01.getOperand(0);
3184 if (!isBSwapHWordElement(N010, Parts))
3185 return SDValue();
3186 SDValue N011 = N01.getOperand(1);
3187 if (!isBSwapHWordElement(N011, Parts))
3188 return SDValue();
3189 } else {
3190 // (or (or (or (and), (and)), (and)), (and))
3191 if (!isBSwapHWordElement(N1, Parts))
3192 return SDValue();
3193 if (!isBSwapHWordElement(N01, Parts))
3194 return SDValue();
3195 if (N00.getOpcode() != ISD::OR)
3196 return SDValue();
3197 SDValue N000 = N00.getOperand(0);
3198 if (!isBSwapHWordElement(N000, Parts))
3199 return SDValue();
3200 SDValue N001 = N00.getOperand(1);
3201 if (!isBSwapHWordElement(N001, Parts))
3202 return SDValue();
3203 }
3204
3205 // Make sure the parts are all coming from the same node.
3206 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3207 return SDValue();
3208
Andrew Trickef9de2a2013-05-25 02:42:55 +00003209 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003210 SDValue(Parts[0],0));
3211
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003212 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003213 // do (x << 16) | (x >> 16).
3214 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3215 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003216 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003217 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003218 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3219 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3220 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3221 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003222}
3223
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003224SDValue DAGCombiner::visitOR(SDNode *N) {
3225 SDValue N0 = N->getOperand(0);
3226 SDValue N1 = N->getOperand(1);
3227 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003228 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3229 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003230 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003231
Dan Gohmana8665142007-06-25 16:23:39 +00003232 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003233 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003234 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003235 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003236
3237 // fold (or x, 0) -> x, vector edition
3238 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3239 return N1;
3240 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3241 return N0;
3242
3243 // fold (or x, -1) -> -1, vector edition
3244 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3245 return N0;
3246 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3247 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003248
3249 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3250 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3251 // Do this only if the resulting shuffle is legal.
3252 if (isa<ShuffleVectorSDNode>(N0) &&
3253 isa<ShuffleVectorSDNode>(N1) &&
3254 N0->getOperand(1) == N1->getOperand(1) &&
3255 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3256 bool CanFold = true;
3257 unsigned NumElts = VT.getVectorNumElements();
3258 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3259 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3260 // We construct two shuffle masks:
3261 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3262 // and N1 as the second operand.
3263 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3264 // and N0 as the second operand.
3265 // We do this because OR is commutable and therefore there might be
3266 // two ways to fold this node into a shuffle.
3267 SmallVector<int,4> Mask1;
3268 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003269
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003270 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3271 int M0 = SV0->getMaskElt(i);
3272 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003273
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003274 // Both shuffle indexes are undef. Propagate Undef.
3275 if (M0 < 0 && M1 < 0) {
3276 Mask1.push_back(M0);
3277 Mask2.push_back(M0);
3278 continue;
3279 }
3280
3281 if (M0 < 0 || M1 < 0 ||
3282 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3283 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3284 CanFold = false;
3285 break;
3286 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003287
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003288 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3289 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3290 }
3291
3292 if (CanFold) {
3293 // Fold this sequence only if the resulting shuffle is 'legal'.
3294 if (TLI.isShuffleMaskLegal(Mask1, VT))
3295 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3296 N1->getOperand(0), &Mask1[0]);
3297 if (TLI.isShuffleMaskLegal(Mask2, VT))
3298 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3299 N0->getOperand(0), &Mask2[0]);
3300 }
3301 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003302 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003303
Dan Gohman06563a82007-07-03 14:03:57 +00003304 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003305 if (!LegalOperations &&
3306 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003307 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3308 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3309 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003310 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003311 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003312 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003313 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003314 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003315 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003316 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003317 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003318 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003319 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003320 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003321 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003322 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003323 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003324 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003325
3326 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3327 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003328 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003329 return BSwap;
3330 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003331 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003332 return BSwap;
3333
Nate Begeman22e251a2006-02-03 06:46:56 +00003334 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003335 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003336 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003337 return ROR;
3338 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003339 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003340 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003341 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003342 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003343 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3344 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3345 if (!COR.getNode())
3346 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003347 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3348 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003349 N0.getOperand(0), N1), COR);
3350 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003351 }
Nate Begeman049b7482005-09-09 19:49:52 +00003352 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3353 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3354 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3355 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003356
Nate Begeman049b7482005-09-09 19:49:52 +00003357 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003358 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003359 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3360 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003361 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003362 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003363 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003364 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003365 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003366 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003367 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003368 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3369 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003370 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003371 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003372 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003373 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003374 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003375 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003376 }
3377 }
3378 // canonicalize equivalent to ll == rl
3379 if (LL == RR && LR == RL) {
3380 Op1 = ISD::getSetCCSwappedOperands(Op1);
3381 std::swap(RL, RR);
3382 }
3383 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003384 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003385 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003386 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003387 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003388 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3389 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003390 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003391 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003392 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003393 }
3394 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003395
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003396 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003397 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003398 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003399 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003400 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003401
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003402 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003403 if (N0.getOpcode() == ISD::AND &&
3404 N1.getOpcode() == ISD::AND &&
3405 N0.getOperand(1).getOpcode() == ISD::Constant &&
3406 N1.getOperand(1).getOpcode() == ISD::Constant &&
3407 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003408 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003409 // We can only do this xform if we know that bits from X that are set in C2
3410 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003411 const APInt &LHSMask =
3412 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3413 const APInt &RHSMask =
3414 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003415
Dan Gohman309d3d52007-06-22 14:59:07 +00003416 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3417 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003418 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003419 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003420 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003421 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003422 }
3423 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003424
Chris Lattner97614c82006-09-14 20:50:57 +00003425 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003426 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003427 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003428
Dan Gohman600f62b2010-06-24 14:30:44 +00003429 // Simplify the operands using demanded-bits information.
3430 if (!VT.isVector() &&
3431 SimplifyDemandedBits(SDValue(N, 0)))
3432 return SDValue(N, 0);
3433
Evan Chengf1005572010-04-28 07:10:39 +00003434 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003435}
3436
Chris Lattner97614c82006-09-14 20:50:57 +00003437/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003438static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003439 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003440 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003441 Mask = Op.getOperand(1);
3442 Op = Op.getOperand(0);
3443 } else {
3444 return false;
3445 }
3446 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003447
Chris Lattner97614c82006-09-14 20:50:57 +00003448 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3449 Shift = Op;
3450 return true;
3451 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003452
Scott Michelcf0da6c2009-02-17 22:15:04 +00003453 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003454}
3455
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003456// Return true if we can prove that, whenever Neg and Pos are both in the
3457// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003458// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3459//
3460// (or (shift1 X, Neg), (shift2 X, Pos))
3461//
Adam Nemetc6553a82014-03-07 23:56:24 +00003462// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3463// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3464// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003465static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003466 // If OpSize is a power of 2 then:
3467 //
3468 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3469 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3470 //
3471 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3472 // for the stronger condition:
3473 //
3474 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3475 //
3476 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3477 // we can just replace Neg with Neg' for the rest of the function.
3478 //
3479 // In other cases we check for the even stronger condition:
3480 //
3481 // Neg == OpSize - Pos [B]
3482 //
3483 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3484 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003485 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003486 // We could actually use [A] whenever OpSize is a power of 2, but the
3487 // only extra cases that it would match are those uninteresting ones
3488 // where Neg and Pos are never in range at the same time. E.g. for
3489 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3490 // as well as (sub 32, Pos), but:
3491 //
3492 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3493 //
3494 // always invokes undefined behavior for 32-bit X.
3495 //
3496 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003497 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003498 if (Neg.getOpcode() == ISD::AND &&
3499 isPowerOf2_64(OpSize) &&
3500 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3501 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3502 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003503 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003504 }
3505
Richard Sandiford0f264db2014-01-09 10:49:40 +00003506 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3507 if (Neg.getOpcode() != ISD::SUB)
3508 return 0;
3509 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3510 if (!NegC)
3511 return 0;
3512 SDValue NegOp1 = Neg.getOperand(1);
3513
Adam Nemet5117f5d2014-03-07 23:56:28 +00003514 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3515 // Pos'. The truncation is redundant for the purpose of the equality.
3516 if (MaskLoBits &&
3517 Pos.getOpcode() == ISD::AND &&
3518 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3519 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3520 Pos = Pos.getOperand(0);
3521
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003522 // The condition we need is now:
3523 //
3524 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3525 //
3526 // If NegOp1 == Pos then we need:
3527 //
3528 // OpSize & Mask == NegC & Mask
3529 //
3530 // (because "x & Mask" is a truncation and distributes through subtraction).
3531 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003532 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003533 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003534 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3535 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003536 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003537 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3538 //
3539 // which, again because "x & Mask" is a truncation, becomes:
3540 //
3541 // NegC & Mask == (OpSize - PosC) & Mask
3542 // OpSize & Mask == (NegC + PosC) & Mask
3543 else if (Pos.getOpcode() == ISD::ADD &&
3544 Pos.getOperand(0) == NegOp1 &&
3545 Pos.getOperand(1).getOpcode() == ISD::Constant)
3546 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3547 NegC->getAPIntValue());
3548 else
3549 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003550
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003551 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003552 if (MaskLoBits)
3553 // Opsize & Mask is 0 since Mask is Opsize - 1.
3554 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003555 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003556}
3557
Richard Sandiford95c864d2014-01-08 15:40:47 +00003558// A subroutine of MatchRotate used once we have found an OR of two opposite
3559// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3560// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3561// former being preferred if supported. InnerPos and InnerNeg are Pos and
3562// Neg with outer conversions stripped away.
3563SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3564 SDValue Neg, SDValue InnerPos,
3565 SDValue InnerNeg, unsigned PosOpcode,
3566 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003567 // fold (or (shl x, (*ext y)),
3568 // (srl x, (*ext (sub 32, y)))) ->
3569 // (rotl x, y) or (rotr x, (sub 32, y))
3570 //
3571 // fold (or (shl x, (*ext (sub 32, y))),
3572 // (srl x, (*ext y))) ->
3573 // (rotr x, y) or (rotl x, (sub 32, y))
3574 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003575 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003576 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3577 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3578 HasPos ? Pos : Neg).getNode();
3579 }
3580
Craig Topperc0196b12014-04-14 00:51:57 +00003581 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003582}
3583
Chris Lattner97614c82006-09-14 20:50:57 +00003584// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3585// idioms for rotate, and if the target supports rotation instructions, generate
3586// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003587SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003588 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003589 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003590 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003591
3592 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003593 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3594 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003595 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003596
Chris Lattner97614c82006-09-14 20:50:57 +00003597 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003598 SDValue LHSShift; // The shift.
3599 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003600 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003601 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003602
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003603 SDValue RHSShift; // The shift.
3604 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003605 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003606 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003607
Chris Lattner97614c82006-09-14 20:50:57 +00003608 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003609 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003610
3611 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003612 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003613
Chris Lattner97614c82006-09-14 20:50:57 +00003614 // Canonicalize shl to left side in a shl/srl pair.
3615 if (RHSShift.getOpcode() == ISD::SHL) {
3616 std::swap(LHS, RHS);
3617 std::swap(LHSShift, RHSShift);
3618 std::swap(LHSMask , RHSMask );
3619 }
3620
Duncan Sands13237ac2008-06-06 12:08:01 +00003621 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003622 SDValue LHSShiftArg = LHSShift.getOperand(0);
3623 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003624 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003625 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003626
3627 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3628 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003629 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3630 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003631 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3632 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003633 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003634 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003635
Craig Topper65161fa2012-09-29 06:54:22 +00003636 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3637 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003638
Chris Lattner97614c82006-09-14 20:50:57 +00003639 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003640 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003641 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003642
Gabor Greiff304a7a2008-08-28 21:40:38 +00003643 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003644 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3645 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003646 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003647 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003648 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3649 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003650 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003651
Bill Wendling35972a92009-01-30 21:14:50 +00003652 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003653 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003654
Gabor Greiff304a7a2008-08-28 21:40:38 +00003655 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003656 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003657
Chris Lattner97614c82006-09-14 20:50:57 +00003658 // If there is a mask here, and we have a variable shift, we can't be sure
3659 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003660 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003661 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003662
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003663 // If the shift amount is sign/zext/any-extended just peel it off.
3664 SDValue LExtOp0 = LHSShiftAmt;
3665 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003666 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3667 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3668 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3669 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3670 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3671 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3672 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3673 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003674 LExtOp0 = LHSShiftAmt.getOperand(0);
3675 RExtOp0 = RHSShiftAmt.getOperand(0);
3676 }
3677
Richard Sandiford95c864d2014-01-08 15:40:47 +00003678 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3679 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3680 if (TryL)
3681 return TryL;
3682
3683 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3684 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3685 if (TryR)
3686 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003687
Craig Topperc0196b12014-04-14 00:51:57 +00003688 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003689}
3690
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003691SDValue DAGCombiner::visitXOR(SDNode *N) {
3692 SDValue N0 = N->getOperand(0);
3693 SDValue N1 = N->getOperand(1);
3694 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003697 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003698
Dan Gohmana8665142007-06-25 16:23:39 +00003699 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003700 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003701 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003702 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003703
3704 // fold (xor x, 0) -> x, vector edition
3705 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3706 return N1;
3707 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3708 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003709 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003710
Evan Chengdf1690d2008-03-25 20:08:07 +00003711 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3712 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3713 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003714 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003715 if (N0.getOpcode() == ISD::UNDEF)
3716 return N0;
3717 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003718 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003719 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003720 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003721 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003722 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003723 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003724 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003725 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003726 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003727 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003728 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003729 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003730 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003731 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003732
Nate Begeman21158fc2005-09-01 00:19:25 +00003733 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003734 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003735 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003736 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3737 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003738
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003739 if (!LegalOperations ||
3740 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003741 switch (N0.getOpcode()) {
3742 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003743 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003744 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003745 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003746 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003747 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003748 N0.getOperand(3), NotCC);
3749 }
3750 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003751 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003752
Chris Lattner58c227b2007-09-10 21:39:07 +00003753 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003754 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003755 N0.getNode()->hasOneUse() &&
3756 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003757 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003758 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003759 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003760 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003761 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003762 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003763
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003764 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003765 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003766 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003767 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003768 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3769 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003770 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3771 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003772 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003773 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003774 }
3775 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003776 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003777 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003778 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003779 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003780 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3781 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003782 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3783 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003784 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003785 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003786 }
3787 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003788 // fold (xor (and x, y), y) -> (and (not x), y)
3789 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003790 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003791 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003792 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003793 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003794 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003795 }
Bill Wendling35972a92009-01-30 21:14:50 +00003796 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003797 if (N1C && N0.getOpcode() == ISD::XOR) {
3798 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3799 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3800 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003801 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003802 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003803 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003804 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003805 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003806 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003807 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003808 }
3809 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003810 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003811 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003812
Chris Lattner8d6fc202006-05-05 05:51:50 +00003813 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3814 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003815 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003816 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003817 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003818
Chris Lattner098c01e2006-04-08 04:15:24 +00003819 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003820 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003821 SimplifyDemandedBits(SDValue(N, 0)))
3822 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003823
Evan Chengf1005572010-04-28 07:10:39 +00003824 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003825}
3826
Chris Lattner7c709a52007-12-06 07:33:36 +00003827/// visitShiftByConstant - Handle transforms common to the three shifts, when
3828/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003829SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003830 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003831 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003832 return SDValue();
3833
Gabor Greiff304a7a2008-08-28 21:40:38 +00003834 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003835 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003836
Chris Lattner7c709a52007-12-06 07:33:36 +00003837 // We want to pull some binops through shifts, so that we have (and (shift))
3838 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3839 // thing happens with address calculations, so it's important to canonicalize
3840 // it.
3841 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003842
Chris Lattner7c709a52007-12-06 07:33:36 +00003843 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003844 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003845 case ISD::OR:
3846 case ISD::XOR:
3847 HighBitSet = false; // We can only transform sra if the high bit is clear.
3848 break;
3849 case ISD::AND:
3850 HighBitSet = true; // We can only transform sra if the high bit is set.
3851 break;
3852 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003853 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003854 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003855 HighBitSet = false; // We can only transform sra if the high bit is clear.
3856 break;
3857 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003858
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003859 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003860 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003861 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003862
3863 // FIXME: disable this unless the input to the binop is a shift by a constant.
3864 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003865 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003866 // void foo(int *X, int i) { X[i & 1235] = 1; }
3867 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003868 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003869 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003870 BinOpLHSVal->getOpcode() != ISD::SRA &&
3871 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3872 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003873 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003874
Owen Anderson53aa7a92009-08-10 22:56:29 +00003875 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003876
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003877 // If this is a signed shift right, and the high bit is modified by the
3878 // logical operation, do not perform the transformation. The highBitSet
3879 // boolean indicates the value of the high bit of the constant which would
3880 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003881 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003882 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3883 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003884 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003885 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003886
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003887 if (!TLI.isDesirableToCommuteWithShift(LHS))
3888 return SDValue();
3889
Chris Lattner7c709a52007-12-06 07:33:36 +00003890 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003891 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003892 N->getValueType(0),
3893 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003894 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003895
3896 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003897 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003898 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003899 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003900
3901 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003902 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003903}
3904
Adam Nemet67483892014-03-04 23:28:31 +00003905SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3906 assert(N->getOpcode() == ISD::TRUNCATE);
3907 assert(N->getOperand(0).getOpcode() == ISD::AND);
3908
3909 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3910 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3911 SDValue N01 = N->getOperand(0).getOperand(1);
3912
Matt Arsenault985b9de2014-03-17 18:58:01 +00003913 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003914 EVT TruncVT = N->getValueType(0);
3915 SDValue N00 = N->getOperand(0).getOperand(0);
3916 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003917 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003918
3919 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3920 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3921 DAG.getConstant(TruncC, TruncVT));
3922 }
3923 }
3924
3925 return SDValue();
3926}
Adam Nemet7f928f12014-03-07 23:56:30 +00003927
3928SDValue DAGCombiner::visitRotate(SDNode *N) {
3929 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3930 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3931 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3932 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3933 if (NewOp1.getNode())
3934 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3935 N->getOperand(0), NewOp1);
3936 }
3937 return SDValue();
3938}
3939
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003940SDValue DAGCombiner::visitSHL(SDNode *N) {
3941 SDValue N0 = N->getOperand(0);
3942 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003943 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3944 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003945 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003946 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003947
Daniel Sandersa1840d22013-11-11 17:23:41 +00003948 // fold vector ops
3949 if (VT.isVector()) {
3950 SDValue FoldedVOp = SimplifyVBinOp(N);
3951 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003952
3953 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3954 // If setcc produces all-one true value then:
3955 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003956 if (N1CV && N1CV->isConstant()) {
3957 if (N0.getOpcode() == ISD::AND &&
3958 TLI.getBooleanContents(true) ==
3959 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3960 SDValue N00 = N0->getOperand(0);
3961 SDValue N01 = N0->getOperand(1);
3962 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003963
Matt Arsenault985b9de2014-03-17 18:58:01 +00003964 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3965 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3966 if (C.getNode())
3967 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3968 }
3969 } else {
3970 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003971 }
3972 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003973 }
3974
Nate Begeman21158fc2005-09-01 00:19:25 +00003975 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003976 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003977 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003978 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003979 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003980 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003981 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003982 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003983 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003984 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003985 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003986 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003987 // fold (shl undef, x) -> 0
3988 if (N0.getOpcode() == ISD::UNDEF)
3989 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003990 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003991 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003992 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003993 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003994 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003995 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00003996 N1.getOperand(0).getOpcode() == ISD::AND) {
3997 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3998 if (NewOp1.getNode())
3999 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004000 }
4001
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004002 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4003 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004004
4005 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004006 if (N1C && N0.getOpcode() == ISD::SHL) {
4007 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4008 uint64_t c1 = N0C1->getZExtValue();
4009 uint64_t c2 = N1C->getZExtValue();
4010 if (c1 + c2 >= OpSizeInBits)
4011 return DAG.getConstant(0, VT);
4012 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4013 DAG.getConstant(c1 + c2, N1.getValueType()));
4014 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004015 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004016
4017 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4018 // For this to be valid, the second form must not preserve any of the bits
4019 // that are shifted out by the inner shift in the first form. This means
4020 // the outer shift size must be >= the number of bits added by the ext.
4021 // As a corollary, we don't care what kind of ext it is.
4022 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4023 N0.getOpcode() == ISD::ANY_EXTEND ||
4024 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004025 N0.getOperand(0).getOpcode() == ISD::SHL) {
4026 SDValue N0Op0 = N0.getOperand(0);
4027 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4028 uint64_t c1 = N0Op0C1->getZExtValue();
4029 uint64_t c2 = N1C->getZExtValue();
4030 EVT InnerShiftVT = N0Op0.getValueType();
4031 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4032 if (c2 >= OpSizeInBits - InnerShiftSize) {
4033 if (c1 + c2 >= OpSizeInBits)
4034 return DAG.getConstant(0, VT);
4035 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4036 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4037 N0Op0->getOperand(0)),
4038 DAG.getConstant(c1 + c2, N1.getValueType()));
4039 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004040 }
4041 }
4042
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004043 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4044 // Only fold this if the inner zext has no other uses to avoid increasing
4045 // the total number of instructions.
4046 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004047 N0.getOperand(0).getOpcode() == ISD::SRL) {
4048 SDValue N0Op0 = N0.getOperand(0);
4049 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4050 uint64_t c1 = N0Op0C1->getZExtValue();
4051 if (c1 < VT.getScalarSizeInBits()) {
4052 uint64_t c2 = N1C->getZExtValue();
4053 if (c1 == c2) {
4054 SDValue NewOp0 = N0.getOperand(0);
4055 EVT CountVT = NewOp0.getOperand(1).getValueType();
4056 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4057 NewOp0, DAG.getConstant(c2, CountVT));
4058 AddToWorkList(NewSHL.getNode());
4059 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4060 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004061 }
4062 }
4063 }
4064
Eli Friedman1877ac92011-06-09 22:14:44 +00004065 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4066 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004067 // Only fold this if the inner shift has no other uses -- if it does, folding
4068 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004069 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4070 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4071 uint64_t c1 = N0C1->getZExtValue();
4072 if (c1 < OpSizeInBits) {
4073 uint64_t c2 = N1C->getZExtValue();
4074 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4075 SDValue Shift;
4076 if (c2 > c1) {
4077 Mask = Mask.shl(c2 - c1);
4078 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4079 DAG.getConstant(c2 - c1, N1.getValueType()));
4080 } else {
4081 Mask = Mask.lshr(c1 - c2);
4082 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4083 DAG.getConstant(c1 - c2, N1.getValueType()));
4084 }
4085 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4086 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004087 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004088 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004089 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004090 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004091 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004092 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004093 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004094 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4095 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004096 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004097 HiBitsMask);
4098 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004099
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004100 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004101 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004102 if (NewSHL.getNode())
4103 return NewSHL;
4104 }
4105
Evan Chengf1005572010-04-28 07:10:39 +00004106 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004107}
4108
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004109SDValue DAGCombiner::visitSRA(SDNode *N) {
4110 SDValue N0 = N->getOperand(0);
4111 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004112 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004114 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004115 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004116
Daniel Sandersa1840d22013-11-11 17:23:41 +00004117 // fold vector ops
4118 if (VT.isVector()) {
4119 SDValue FoldedVOp = SimplifyVBinOp(N);
4120 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004121
4122 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004123 }
4124
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004125 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004126 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004127 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004128 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004129 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004130 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004131 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004132 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004133 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004134 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004135 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004136 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004137 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004138 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004139 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004140 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4141 // sext_inreg.
4142 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004143 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004144 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4145 if (VT.isVector())
4146 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4147 ExtVT, VT.getVectorNumElements());
4148 if ((!LegalOperations ||
4149 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004150 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004151 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004152 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004153
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004154 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004155 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004156 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004157 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004158 if (Sum >= OpSizeInBits)
4159 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004160 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004161 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004162 }
4163 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004164
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004165 // fold (sra (shl X, m), (sub result_size, n))
4166 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004167 // result_size - n != m.
4168 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004169 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004170 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004171 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004172 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4173 if (N01C) {
4174 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004175 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004176 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4177
4178 if (VT.isVector())
4179 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4180
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004181 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004182 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004183
Scott Michelcf0da6c2009-02-17 22:15:04 +00004184 // If the shift is not a no-op (in which case this should be just a sign
4185 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004186 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004187 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004188 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004189 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4190 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004191 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004192
Owen Andersonb2c80da2011-02-25 21:41:48 +00004193 SDValue Amt = DAG.getConstant(ShiftAmt,
4194 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004195 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004196 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004197 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004198 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004199 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004200 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004201 }
4202 }
4203 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004204
Duncan Sands3ed76882009-02-01 18:06:53 +00004205 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004206 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004207 N1.getOperand(0).getOpcode() == ISD::AND) {
4208 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4209 if (NewOp1.getNode())
4210 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004211 }
4212
Matt Arsenault985b9de2014-03-17 18:58:01 +00004213 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004214 // if c1 is equal to the number of bits the trunc removes
4215 if (N0.getOpcode() == ISD::TRUNCATE &&
4216 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4217 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4218 N0.getOperand(0).hasOneUse() &&
4219 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004220 N1C) {
4221 SDValue N0Op0 = N0.getOperand(0);
4222 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4223 unsigned LargeShiftVal = LargeShift->getZExtValue();
4224 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004225
Matt Arsenault985b9de2014-03-17 18:58:01 +00004226 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4227 SDValue Amt =
4228 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4229 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4230 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4231 N0Op0.getOperand(0), Amt);
4232 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4233 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004234 }
4235 }
4236
Scott Michelcf0da6c2009-02-17 22:15:04 +00004237 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004238 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4239 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004240
4241
Nate Begeman21158fc2005-09-01 00:19:25 +00004242 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004243 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004244 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004245
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004246 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004247 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004248 if (NewSRA.getNode())
4249 return NewSRA;
4250 }
4251
Evan Chengf1005572010-04-28 07:10:39 +00004252 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004253}
4254
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004255SDValue DAGCombiner::visitSRL(SDNode *N) {
4256 SDValue N0 = N->getOperand(0);
4257 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004258 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4259 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004260 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004261 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004262
Daniel Sandersa1840d22013-11-11 17:23:41 +00004263 // fold vector ops
4264 if (VT.isVector()) {
4265 SDValue FoldedVOp = SimplifyVBinOp(N);
4266 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004267
4268 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004269 }
4270
Nate Begeman21158fc2005-09-01 00:19:25 +00004271 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004272 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004273 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004274 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004275 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004276 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004277 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004278 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004279 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004280 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004281 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004282 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004283 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004284 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004285 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004286 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004287
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004288 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004289 if (N1C && N0.getOpcode() == ISD::SRL) {
4290 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4291 uint64_t c1 = N01C->getZExtValue();
4292 uint64_t c2 = N1C->getZExtValue();
4293 if (c1 + c2 >= OpSizeInBits)
4294 return DAG.getConstant(0, VT);
4295 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4296 DAG.getConstant(c1 + c2, N1.getValueType()));
4297 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004298 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004299
Dale Johannesencd538af2010-12-17 21:45:49 +00004300 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004301 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4302 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004303 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004304 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004305 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4306 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004307 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4308 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004309 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004310 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004311 if (c1 + OpSizeInBits == InnerShiftSize) {
4312 if (c1 + c2 >= InnerShiftSize)
4313 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004314 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4315 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004316 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004317 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004318 }
4319 }
4320
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004321 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004322 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4323 unsigned BitSize = N0.getScalarValueSizeInBits();
4324 if (BitSize <= 64) {
4325 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4326 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4327 DAG.getConstant(~0ULL >> ShAmt, VT));
4328 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004329 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004330
Michael Liao62ebfd82013-06-21 18:45:27 +00004331 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004332 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4333 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004334 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004335 unsigned BitSize = SmallVT.getScalarSizeInBits();
4336 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004337 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004338
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004339 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004340 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004341 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004342 N0.getOperand(0),
4343 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004344 AddToWorkList(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004345 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004346 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4347 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4348 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004349 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004350 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004351
Chris Lattner2e33fb42006-10-12 20:23:19 +00004352 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4353 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004354 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004355 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004356 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004357 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004358
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004359 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004360 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004361 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004362 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004363 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004364
Chris Lattner49932492006-04-02 06:11:11 +00004365 // If any of the input bits are KnownOne, then the input couldn't be all
4366 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004367 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004368
Chris Lattner49932492006-04-02 06:11:11 +00004369 // If all of the bits input the to ctlz node are known to be zero, then
4370 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004371 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004372 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004373
Chris Lattner49932492006-04-02 06:11:11 +00004374 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004375 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004376 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004377 // could be set on input to the CTLZ node. If this bit is set, the SRL
4378 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4379 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004380 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004381 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004382
Chris Lattner49932492006-04-02 06:11:11 +00004383 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004384 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004385 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004386 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004387 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004388
Andrew Trickef9de2a2013-05-25 02:42:55 +00004389 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004390 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004391 }
4392 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004393
Duncan Sands3ed76882009-02-01 18:06:53 +00004394 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004395 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004396 N1.getOperand(0).getOpcode() == ISD::AND) {
4397 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4398 if (NewOp1.getNode())
4399 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004400 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004401
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004402 // fold operands of srl based on knowledge that the low bits are not
4403 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004404 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4405 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004406
Evan Chengb175de62009-12-18 21:31:31 +00004407 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004408 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004409 if (NewSRL.getNode())
4410 return NewSRL;
4411 }
4412
Dan Gohman600f62b2010-06-24 14:30:44 +00004413 // Attempt to convert a srl of a load into a narrower zero-extending load.
4414 SDValue NarrowLoad = ReduceLoadWidth(N);
4415 if (NarrowLoad.getNode())
4416 return NarrowLoad;
4417
Evan Chengb175de62009-12-18 21:31:31 +00004418 // Here is a common situation. We want to optimize:
4419 //
4420 // %a = ...
4421 // %b = and i32 %a, 2
4422 // %c = srl i32 %b, 1
4423 // brcond i32 %c ...
4424 //
4425 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004426 //
Evan Chengb175de62009-12-18 21:31:31 +00004427 // %a = ...
4428 // %b = and %a, 2
4429 // %c = setcc eq %b, 0
4430 // brcond %c ...
4431 //
4432 // However when after the source operand of SRL is optimized into AND, the SRL
4433 // itself may not be optimized further. Look for it and add the BRCOND into
4434 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004435 if (N->hasOneUse()) {
4436 SDNode *Use = *N->use_begin();
4437 if (Use->getOpcode() == ISD::BRCOND)
4438 AddToWorkList(Use);
4439 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4440 // Also look pass the truncate.
4441 Use = *Use->use_begin();
4442 if (Use->getOpcode() == ISD::BRCOND)
4443 AddToWorkList(Use);
4444 }
4445 }
Evan Chengb175de62009-12-18 21:31:31 +00004446
Evan Chengf1005572010-04-28 07:10:39 +00004447 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004448}
4449
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004450SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4451 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004452 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004453
4454 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004455 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004456 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004457 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004458}
4459
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004460SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4461 SDValue N0 = N->getOperand(0);
4462 EVT VT = N->getValueType(0);
4463
4464 // fold (ctlz_zero_undef c1) -> c2
4465 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004466 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004467 return SDValue();
4468}
4469
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004470SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4471 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004472 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004473
Nate Begeman21158fc2005-09-01 00:19:25 +00004474 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004475 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004476 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004477 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004478}
4479
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004480SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4481 SDValue N0 = N->getOperand(0);
4482 EVT VT = N->getValueType(0);
4483
4484 // fold (cttz_zero_undef c1) -> c2
4485 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004486 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004487 return SDValue();
4488}
4489
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004490SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4491 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004492 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004493
Nate Begeman21158fc2005-09-01 00:19:25 +00004494 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004495 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004496 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004497 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004498}
4499
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004500SDValue DAGCombiner::visitSELECT(SDNode *N) {
4501 SDValue N0 = N->getOperand(0);
4502 SDValue N1 = N->getOperand(1);
4503 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004504 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4506 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004507 EVT VT = N->getValueType(0);
4508 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004509
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004510 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004511 if (N1 == N2)
4512 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004513 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004514 if (N0C && !N0C->isNullValue())
4515 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004516 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004517 if (N0C && N0C->isNullValue())
4518 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004519 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004520 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004521 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004522 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004523 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004524 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004525 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004526 TLI.getBooleanContents(false) ==
4527 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004528 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004529 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004530 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004531 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004532 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004533 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004534 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004535 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004536 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004537 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4538 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004539 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004540 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004541 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004542 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004543 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004544 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004545 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004546 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004547 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004548 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004549 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004550 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004551 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004552 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004553 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004554 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004555 // fold (select X, X, Y) -> (or X, Y)
4556 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004557 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004558 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004559 // fold (select X, Y, X) -> (and X, Y)
4560 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004561 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004562 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004563
Chris Lattner6c14c352005-10-18 06:04:22 +00004564 // If we can fold this based on the true/false value, do so.
4565 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004566 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004567
Nate Begemanc760f802005-09-19 22:34:01 +00004568 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004569 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004570 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004571 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004572 // having to say they don't support SELECT_CC on every type the DAG knows
4573 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004574 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004575 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004576 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004577 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004578 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004579 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004580 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004581
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004582 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004583}
4584
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004585static
4586std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4587 SDLoc DL(N);
4588 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004589 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004590
4591 // Split the inputs.
4592 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004593 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4594 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004595
4596 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4597 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4598
4599 return std::make_pair(Lo, Hi);
4600}
4601
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004602// This function assumes all the vselect's arguments are CONCAT_VECTOR
4603// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4604static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4605 SDLoc dl(N);
4606 SDValue Cond = N->getOperand(0);
4607 SDValue LHS = N->getOperand(1);
4608 SDValue RHS = N->getOperand(2);
4609 MVT VT = N->getSimpleValueType(0);
4610 int NumElems = VT.getVectorNumElements();
4611 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4612 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4613 Cond.getOpcode() == ISD::BUILD_VECTOR);
4614
4615 // We're sure we have an even number of elements due to the
4616 // concat_vectors we have as arguments to vselect.
4617 // Skip BV elements until we find one that's not an UNDEF
4618 // After we find an UNDEF element, keep looping until we get to half the
4619 // length of the BV and see if all the non-undef nodes are the same.
4620 ConstantSDNode *BottomHalf = nullptr;
4621 for (int i = 0; i < NumElems / 2; ++i) {
4622 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4623 continue;
4624
4625 if (BottomHalf == nullptr)
4626 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4627 else if (Cond->getOperand(i).getNode() != BottomHalf)
4628 return SDValue();
4629 }
4630
4631 // Do the same for the second half of the BuildVector
4632 ConstantSDNode *TopHalf = nullptr;
4633 for (int i = NumElems / 2; i < NumElems; ++i) {
4634 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4635 continue;
4636
4637 if (TopHalf == nullptr)
4638 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4639 else if (Cond->getOperand(i).getNode() != TopHalf)
4640 return SDValue();
4641 }
4642
4643 assert(TopHalf && BottomHalf &&
4644 "One half of the selector was all UNDEFs and the other was all the "
4645 "same value. This should have been addressed before this function.");
4646 return DAG.getNode(
4647 ISD::CONCAT_VECTORS, dl, VT,
4648 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4649 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4650}
4651
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004652SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4653 SDValue N0 = N->getOperand(0);
4654 SDValue N1 = N->getOperand(1);
4655 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004656 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004657
4658 // Canonicalize integer abs.
4659 // vselect (setg[te] X, 0), X, -X ->
4660 // vselect (setgt X, -1), X, -X ->
4661 // vselect (setl[te] X, 0), -X, X ->
4662 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4663 if (N0.getOpcode() == ISD::SETCC) {
4664 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4665 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4666 bool isAbs = false;
4667 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4668
4669 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4670 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4671 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4672 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4673 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4674 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4675 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4676
4677 if (isAbs) {
4678 EVT VT = LHS.getValueType();
4679 SDValue Shift = DAG.getNode(
4680 ISD::SRA, DL, VT, LHS,
4681 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4682 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4683 AddToWorkList(Shift.getNode());
4684 AddToWorkList(Add.getNode());
4685 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4686 }
4687 }
4688
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004689 // If the VSELECT result requires splitting and the mask is provided by a
4690 // SETCC, then split both nodes and its operands before legalization. This
4691 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4692 // and enables future optimizations (e.g. min/max pattern matching on X86).
4693 if (N0.getOpcode() == ISD::SETCC) {
4694 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004695
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004696 // Check if any splitting is required.
4697 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4698 TargetLowering::TypeSplitVector)
4699 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004700
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004701 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004702 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4703 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4704 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004705
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004706 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4707 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004708
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004709 // Add the new VSELECT nodes to the work list in case they need to be split
4710 // again.
4711 AddToWorkList(Lo.getNode());
4712 AddToWorkList(Hi.getNode());
4713
4714 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004715 }
4716
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004717 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4718 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4719 return N1;
4720 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4721 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4722 return N2;
4723
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004724 // The ConvertSelectToConcatVector function is assuming both the above
4725 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4726 // and addressed.
4727 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4728 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4729 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4730 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4731 if (CV.getNode())
4732 return CV;
4733 }
4734
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004735 return SDValue();
4736}
4737
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004738SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4739 SDValue N0 = N->getOperand(0);
4740 SDValue N1 = N->getOperand(1);
4741 SDValue N2 = N->getOperand(2);
4742 SDValue N3 = N->getOperand(3);
4743 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004744 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004745
Nate Begemanc760f802005-09-19 22:34:01 +00004746 // fold select_cc lhs, rhs, x, x, cc -> x
4747 if (N2 == N3)
4748 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004749
Chris Lattner8b68dec2006-09-20 06:19:26 +00004750 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004751 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004752 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004753 if (SCC.getNode()) {
4754 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004755
Stephen Lin605207f2013-06-15 04:03:33 +00004756 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4757 if (!SCCC->isNullValue())
4758 return N2; // cond always true -> true val
4759 else
4760 return N3; // cond always false -> false val
4761 }
4762
4763 // Fold to a simpler select_cc
4764 if (SCC.getOpcode() == ISD::SETCC)
4765 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4766 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4767 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004768 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004769
Chris Lattner6c14c352005-10-18 06:04:22 +00004770 // If we can fold this based on the true/false value, do so.
4771 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004772 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004773
Nate Begemanc760f802005-09-19 22:34:01 +00004774 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004775 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004776}
4777
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004778SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004779 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004780 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004781 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004782}
4783
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004784// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4785// dag node into a ConstantSDNode or a build_vector of constants.
4786// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004787// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004788// Vector extends are not folded if operations are legal; this is to
4789// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004790static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4791 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004792 bool LegalOperations) {
4793 unsigned Opcode = N->getOpcode();
4794 SDValue N0 = N->getOperand(0);
4795 EVT VT = N->getValueType(0);
4796
4797 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4798 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4799
4800 // fold (sext c1) -> c1
4801 // fold (zext c1) -> c1
4802 // fold (aext c1) -> c1
4803 if (isa<ConstantSDNode>(N0))
4804 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4805
4806 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4807 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4808 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004809 EVT SVT = VT.getScalarType();
4810 if (!(VT.isVector() &&
4811 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004812 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004813 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004814
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004815 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004816 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004817 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4818 unsigned ShAmt = VTBits - EVTBits;
4819 SmallVector<SDValue, 8> Elts;
4820 unsigned NumElts = N0->getNumOperands();
4821 SDLoc DL(N);
4822
4823 for (unsigned i=0; i != NumElts; ++i) {
4824 SDValue Op = N0->getOperand(i);
4825 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004826 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004827 continue;
4828 }
4829
4830 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4831 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4832 if (Opcode == ISD::SIGN_EXTEND)
4833 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004834 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004835 else
4836 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004837 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004838 }
4839
Craig Topper48d114b2014-04-26 18:35:24 +00004840 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004841}
4842
Evan Chenge106e2f2007-10-29 19:58:20 +00004843// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004844// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004845// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004846// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004847static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004848 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004849 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004850 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004851 bool HasCopyToRegUses = false;
4852 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004853 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4854 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004855 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004856 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004857 if (User == N)
4858 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004859 if (UI.getUse().getResNo() != N0.getResNo())
4860 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004861 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004862 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004863 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4864 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4865 // Sign bits will be lost after a zext.
4866 return false;
4867 bool Add = false;
4868 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004869 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004870 if (UseOp == N0)
4871 continue;
4872 if (!isa<ConstantSDNode>(UseOp))
4873 return false;
4874 Add = true;
4875 }
4876 if (Add)
4877 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004878 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004879 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004880 // If truncates aren't free and there are users we can't
4881 // extend, it isn't worthwhile.
4882 if (!isTruncFree)
4883 return false;
4884 // Remember if this value is live-out.
4885 if (User->getOpcode() == ISD::CopyToReg)
4886 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004887 }
4888
4889 if (HasCopyToRegUses) {
4890 bool BothLiveOut = false;
4891 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4892 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004893 SDUse &Use = UI.getUse();
4894 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4895 BothLiveOut = true;
4896 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004897 }
4898 }
4899 if (BothLiveOut)
4900 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004901 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004902 return ExtendNodes.size();
4903 }
4904 return true;
4905}
4906
Craig Toppere0b71182013-07-13 07:43:40 +00004907void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004908 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004909 ISD::NodeType ExtType) {
4910 // Extend SetCC uses if necessary.
4911 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4912 SDNode *SetCC = SetCCs[i];
4913 SmallVector<SDValue, 4> Ops;
4914
4915 for (unsigned j = 0; j != 2; ++j) {
4916 SDValue SOp = SetCC->getOperand(j);
4917 if (SOp == Trunc)
4918 Ops.push_back(ExtLoad);
4919 else
4920 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4921 }
4922
4923 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00004924 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004925 }
4926}
4927
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004928SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4929 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004930 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004931
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004932 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4933 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004934 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004935
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004936 // fold (sext (sext x)) -> (sext x)
4937 // fold (sext (aext x)) -> (sext x)
4938 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004939 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004940 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004941
Chris Lattnerfce448f2007-02-26 03:13:59 +00004942 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004943 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4944 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004945 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4946 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004947 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4948 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004949 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004950 // CombineTo deleted the truncate, if needed, but not what's under it.
4951 AddToWorkList(oye);
4952 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004953 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004954 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004955
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004956 // See if the value being truncated is already sign extended. If so, just
4957 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004958 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004959 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4960 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4961 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004962 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004963
Chris Lattnerfce448f2007-02-26 03:13:59 +00004964 if (OpBits == DestBits) {
4965 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4966 // bits, it is already ready.
4967 if (NumSignBits > DestBits-MidBits)
4968 return Op;
4969 } else if (OpBits < DestBits) {
4970 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4971 // bits, just sext from i32.
4972 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004973 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004974 } else {
4975 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4976 // bits, just truncate to i32.
4977 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004978 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004979 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004980
Chris Lattnerfce448f2007-02-26 03:13:59 +00004981 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004982 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4983 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004984 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004985 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004986 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004987 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4988 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004989 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004990 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004991 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004992
Evan Chengbce7c472005-12-14 02:19:23 +00004993 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004994 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004995 // on vectors in one instruction. We only perform this transformation on
4996 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004997 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004998 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004999 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005000 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005001 bool DoXform = true;
5002 SmallVector<SDNode*, 4> SetCCs;
5003 if (!N0.hasOneUse())
5004 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5005 if (DoXform) {
5006 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005007 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005008 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005009 LN0->getBasePtr(), N0.getValueType(),
5010 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005011 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005012 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005013 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005014 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005015 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005016 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005017 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005018 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005019 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005020
5021 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5022 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005023 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5024 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005025 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005026 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005027 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005028 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005029 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005030 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005031 LN0->getBasePtr(), MemVT,
5032 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005033 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005034 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005035 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005036 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005037 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005038 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005039 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005040 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005041
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005042 // fold (sext (and/or/xor (load x), cst)) ->
5043 // (and/or/xor (sextload x), (sext cst))
5044 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5045 N0.getOpcode() == ISD::XOR) &&
5046 isa<LoadSDNode>(N0.getOperand(0)) &&
5047 N0.getOperand(1).getOpcode() == ISD::Constant &&
5048 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5049 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5050 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005051 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005052 bool DoXform = true;
5053 SmallVector<SDNode*, 4> SetCCs;
5054 if (!N0.hasOneUse())
5055 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5056 SetCCs, TLI);
5057 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005058 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005059 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005060 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005061 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005062 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5063 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005064 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005065 ExtLoad, DAG.getConstant(Mask, VT));
5066 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005067 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005068 N0.getOperand(0).getValueType(), ExtLoad);
5069 CombineTo(N, And);
5070 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005071 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005072 ISD::SIGN_EXTEND);
5073 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5074 }
5075 }
5076 }
5077
Chris Lattner65786b02007-04-11 05:32:27 +00005078 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00005079 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005080 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005081 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00005082 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00005083 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00005084 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00005085 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5086 // of the same size as the compared operands. Only optimize sext(setcc())
5087 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005088 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005089
5090 // We know that the # elements of the results is the same as the
5091 // # elements of the compare (and the # elements of the compare result
5092 // for that matter). Check to see that they are the same size. If so,
5093 // we know that the element size of the sext'd result matches the
5094 // element size of the compare operands.
5095 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005096 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005097 N0.getOperand(1),
5098 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005099
Dan Gohmane82c25e2010-04-30 17:19:19 +00005100 // If the desired elements are smaller or larger than the source
5101 // elements we can use a matching integer vector type and then
5102 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005103 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005104 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005105 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005106 N0.getOperand(0), N0.getOperand(1),
5107 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005108 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005109 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005110 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005111
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005112 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005113 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005114 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005115 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005116 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005117 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005118 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005119 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005120 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005121
5122 if (!VT.isVector()) {
5123 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5124 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5125 SDLoc DL(N);
5126 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5127 SDValue SetCC = DAG.getSetCC(DL,
5128 SetCCVT,
5129 N0.getOperand(0), N0.getOperand(1), CC);
5130 EVT SelectVT = getSetCCResultType(VT);
5131 return DAG.getSelect(DL, VT,
5132 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5133 NegOne, DAG.getConstant(0, VT));
5134
5135 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005136 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005137 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005138
Dan Gohman3eb10f72008-04-28 16:58:24 +00005139 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005140 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005141 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005142 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005143
Evan Chengf1005572010-04-28 07:10:39 +00005144 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005145}
5146
Rafael Espindola8f62b322012-04-09 16:06:03 +00005147// isTruncateOf - If N is a truncate of some other value, return true, record
5148// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5149// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005150// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005151static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5152 APInt &KnownZero) {
5153 APInt KnownOne;
5154 if (N->getOpcode() == ISD::TRUNCATE) {
5155 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005156 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005157 return true;
5158 }
5159
5160 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5161 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5162 return false;
5163
5164 SDValue Op0 = N->getOperand(0);
5165 SDValue Op1 = N->getOperand(1);
5166 assert(Op0.getValueType() == Op1.getValueType());
5167
5168 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5169 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005170 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005171 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005172 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005173 Op = Op0;
5174 else
5175 return false;
5176
Jay Foada0653a32014-05-14 21:14:37 +00005177 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005178
5179 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5180 return false;
5181
5182 return true;
5183}
5184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005185SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5186 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005187 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005188
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005189 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5190 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005191 return SDValue(Res, 0);
5192
Nate Begeman21158fc2005-09-01 00:19:25 +00005193 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005194 // fold (zext (aext x)) -> (zext x)
5195 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005196 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005197 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005198
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005199 // fold (zext (truncate x)) -> (zext x) or
5200 // (zext (truncate x)) -> (truncate x)
5201 // This is valid when the truncated bits of x are already zero.
5202 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005203 SDValue Op;
5204 APInt KnownZero;
5205 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5206 APInt TruncatedBits =
5207 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5208 APInt(Op.getValueSizeInBits(), 0) :
5209 APInt::getBitsSet(Op.getValueSizeInBits(),
5210 N0.getValueSizeInBits(),
5211 std::min(Op.getValueSizeInBits(),
5212 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005213 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005214 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005215 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005216 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005217 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005218
5219 return Op;
5220 }
5221 }
5222
Evan Cheng464dc9b2007-03-22 01:54:19 +00005223 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5224 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005225 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005226 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5227 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005228 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5229 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005230 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005231 // CombineTo deleted the truncate, if needed, but not what's under it.
5232 AddToWorkList(oye);
5233 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005234 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005235 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005236 }
5237
Chris Lattnera31f0a62006-09-21 06:00:20 +00005238 // fold (zext (truncate x)) -> (and x, mask)
5239 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005240 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005241
5242 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5243 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5244 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5245 if (NarrowLoad.getNode()) {
5246 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5247 if (NarrowLoad.getNode() != N0.getNode()) {
5248 CombineTo(N0.getNode(), NarrowLoad);
5249 // CombineTo deleted the truncate, if needed, but not what's under it.
5250 AddToWorkList(oye);
5251 }
5252 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5253 }
5254
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005255 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005256 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005257 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005258 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005259 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005260 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005261 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005262 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005263 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005264 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005265 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005266
Dan Gohmanad3e5492009-04-08 00:15:30 +00005267 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5268 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005269 if (N0.getOpcode() == ISD::AND &&
5270 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005271 N0.getOperand(1).getOpcode() == ISD::Constant &&
5272 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5273 N0.getValueType()) ||
5274 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005275 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005276 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005277 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005278 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005279 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005280 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005281 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005282 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005283 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005284 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005285 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005286
Evan Chengbce7c472005-12-14 02:19:23 +00005287 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005288 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005289 // on vectors in one instruction. We only perform this transformation on
5290 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005291 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005292 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005293 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005294 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005295 bool DoXform = true;
5296 SmallVector<SDNode*, 4> SetCCs;
5297 if (!N0.hasOneUse())
5298 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5299 if (DoXform) {
5300 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005301 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005302 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005303 LN0->getBasePtr(), N0.getValueType(),
5304 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005305 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005306 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005307 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005308 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005309
Andrew Trickef9de2a2013-05-25 02:42:55 +00005310 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005311 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005312 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005313 }
Evan Chengbce7c472005-12-14 02:19:23 +00005314 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005315
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005316 // fold (zext (and/or/xor (load x), cst)) ->
5317 // (and/or/xor (zextload x), (zext cst))
5318 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5319 N0.getOpcode() == ISD::XOR) &&
5320 isa<LoadSDNode>(N0.getOperand(0)) &&
5321 N0.getOperand(1).getOpcode() == ISD::Constant &&
5322 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5323 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5324 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005325 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005326 bool DoXform = true;
5327 SmallVector<SDNode*, 4> SetCCs;
5328 if (!N0.hasOneUse())
5329 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5330 SetCCs, TLI);
5331 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005332 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005333 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005334 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005335 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005336 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5337 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005338 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005339 ExtLoad, DAG.getConstant(Mask, VT));
5340 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005341 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005342 N0.getOperand(0).getValueType(), ExtLoad);
5343 CombineTo(N, And);
5344 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005345 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005346 ISD::ZERO_EXTEND);
5347 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5348 }
5349 }
5350 }
5351
Chris Lattner7dac1082005-12-14 19:05:06 +00005352 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5353 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005354 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5355 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005356 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005357 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005358 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005359 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005360 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005361 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005362 LN0->getBasePtr(), MemVT,
5363 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005364 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005365 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005366 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005367 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005368 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005369 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005370 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005371 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005372
Chris Lattner65786b02007-04-11 05:32:27 +00005373 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005374 if (!LegalOperations && VT.isVector() &&
5375 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005376 EVT N0VT = N0.getOperand(0).getValueType();
5377 if (getSetCCResultType(N0VT) == N0.getValueType())
5378 return SDValue();
5379
Evan Chengabd0ad52010-05-19 01:08:17 +00005380 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5381 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005382 EVT EltVT = VT.getVectorElementType();
5383 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5384 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005385 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005386 // We know that the # elements of the results is the same as the
5387 // # elements of the compare (and the # elements of the compare result
5388 // for that matter). Check to see that they are the same size. If so,
5389 // we know that the element size of the sext'd result matches the
5390 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005391 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5392 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005393 N0.getOperand(1),
5394 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005395 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005396 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005397
5398 // If the desired elements are smaller or larger than the source
5399 // elements we can use a matching integer vector type and then
5400 // truncate/sign extend
5401 EVT MatchingElementType =
5402 EVT::getIntegerVT(*DAG.getContext(),
5403 N0VT.getScalarType().getSizeInBits());
5404 EVT MatchingVectorType =
5405 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5406 N0VT.getVectorNumElements());
5407 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005408 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005409 N0.getOperand(1),
5410 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005411 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5412 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005413 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005414 }
5415
5416 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005417 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005418 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005419 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005420 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005421 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005422 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005423
Evan Cheng852c4862009-12-15 03:00:32 +00005424 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005425 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005426 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005427 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5428 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005429 SDValue ShAmt = N0.getOperand(1);
5430 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005431 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005432 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005433 // If the original shl may be shifting out bits, do not perform this
5434 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005435 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5436 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5437 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005438 return SDValue();
5439 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005440
Andrew Trickef9de2a2013-05-25 02:42:55 +00005441 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005442
5443 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005444 if (VT.getSizeInBits() >= 256)
5445 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005446
Chris Lattnere95d1952011-02-13 19:09:16 +00005447 return DAG.getNode(N0.getOpcode(), DL, VT,
5448 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5449 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005450 }
5451
Evan Chengf1005572010-04-28 07:10:39 +00005452 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005453}
5454
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005455SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5456 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005457 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005458
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005459 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5460 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005461 return SDValue(Res, 0);
5462
Chris Lattner812646a2006-05-05 05:58:59 +00005463 // fold (aext (aext x)) -> (aext x)
5464 // fold (aext (zext x)) -> (zext x)
5465 // fold (aext (sext x)) -> (sext x)
5466 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5467 N0.getOpcode() == ISD::ZERO_EXTEND ||
5468 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005469 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005470
Evan Cheng464dc9b2007-03-22 01:54:19 +00005471 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5472 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5473 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005474 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5475 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005476 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5477 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005478 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005479 // CombineTo deleted the truncate, if needed, but not what's under it.
5480 AddToWorkList(oye);
5481 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005482 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005483 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005484 }
5485
Chris Lattner8746e2c2006-09-20 06:29:17 +00005486 // fold (aext (truncate x))
5487 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005488 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005489 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005490 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005491 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005492 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5493 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005494 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005495
Dan Gohmanad3e5492009-04-08 00:15:30 +00005496 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5497 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005498 if (N0.getOpcode() == ISD::AND &&
5499 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005500 N0.getOperand(1).getOpcode() == ISD::Constant &&
5501 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5502 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005503 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005504 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005505 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005506 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005507 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005508 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005509 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005510 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005511 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005512 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005513 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005514
Chris Lattner812646a2006-05-05 05:58:59 +00005515 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005516 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005517 // on vectors in one instruction. We only perform this transformation on
5518 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005519 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005520 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005521 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005522 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005523 bool DoXform = true;
5524 SmallVector<SDNode*, 4> SetCCs;
5525 if (!N0.hasOneUse())
5526 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5527 if (DoXform) {
5528 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005529 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005530 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005531 LN0->getBasePtr(), N0.getValueType(),
5532 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005533 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005534 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005535 N0.getValueType(), ExtLoad);
5536 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005537 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005538 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005539 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5540 }
Chris Lattner812646a2006-05-05 05:58:59 +00005541 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005542
Chris Lattner812646a2006-05-05 05:58:59 +00005543 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5544 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5545 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005546 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005547 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005548 N0.hasOneUse()) {
5549 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005550 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005551 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005552 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5553 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5554 VT, LN0->getChain(), LN0->getBasePtr(),
5555 MemVT, LN0->getMemOperand());
5556 CombineTo(N, ExtLoad);
5557 CombineTo(N0.getNode(),
5558 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5559 N0.getValueType(), ExtLoad),
5560 ExtLoad.getValue(1));
5561 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5562 }
Chris Lattner812646a2006-05-05 05:58:59 +00005563 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005564
Chris Lattner65786b02007-04-11 05:32:27 +00005565 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005566 // For vectors:
5567 // aext(setcc) -> vsetcc
5568 // aext(setcc) -> truncate(vsetcc)
5569 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005570 // Only do this before legalize for now.
5571 if (VT.isVector() && !LegalOperations) {
5572 EVT N0VT = N0.getOperand(0).getValueType();
5573 // We know that the # elements of the results is the same as the
5574 // # elements of the compare (and the # elements of the compare result
5575 // for that matter). Check to see that they are the same size. If so,
5576 // we know that the element size of the sext'd result matches the
5577 // element size of the compare operands.
5578 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005579 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005580 N0.getOperand(1),
5581 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005582 // If the desired elements are smaller or larger than the source
5583 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005584 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005585 else {
Hao Liuc636d152014-04-22 09:57:06 +00005586 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005587 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005588 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005589 N0.getOperand(1),
5590 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005591 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005592 }
5593 }
5594
5595 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005596 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005597 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005598 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005599 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005600 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005601 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005602 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005603
Evan Chengf1005572010-04-28 07:10:39 +00005604 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005605}
5606
Chris Lattner5e6fe052007-10-13 06:35:54 +00005607/// GetDemandedBits - See if the specified operand can be simplified with the
5608/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005609/// simpler operand, otherwise return a null SDValue.
5610SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005611 switch (V.getOpcode()) {
5612 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005613 case ISD::Constant: {
5614 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005615 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005616 const APInt &CVal = CV->getAPIntValue();
5617 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005618 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005619 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005620 break;
5621 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005622 case ISD::OR:
5623 case ISD::XOR:
5624 // If the LHS or RHS don't contribute bits to the or, drop them.
5625 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5626 return V.getOperand(1);
5627 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5628 return V.getOperand(0);
5629 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005630 case ISD::SRL:
5631 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005632 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005633 break;
5634 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5635 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005636 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005637
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005638 // Watch out for shift count overflow though.
5639 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005640 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005641 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005642 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005643 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005644 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005645 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005646 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005647 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005648}
5649
Evan Cheng464dc9b2007-03-22 01:54:19 +00005650/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5651/// bits and then truncated to a narrower type and where N is a multiple
5652/// of number of bits of the narrower type, transform it to a narrower load
5653/// from address + N / num of bits of new type. If the result is to be
5654/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005655SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005656 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005657
Evan Cheng464dc9b2007-03-22 01:54:19 +00005658 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005659 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005660 EVT VT = N->getValueType(0);
5661 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005662
Dan Gohman550c9af2008-08-14 20:04:46 +00005663 // This transformation isn't valid for vector loads.
5664 if (VT.isVector())
5665 return SDValue();
5666
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005667 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005668 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005669 if (Opc == ISD::SIGN_EXTEND_INREG) {
5670 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005671 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005672 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005673 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005674 ExtType = ISD::ZEXTLOAD;
5675 N0 = SDValue(N, 0);
5676 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5677 if (!N01) return SDValue();
5678 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5679 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005680 }
Richard Osborne272e0842011-01-31 17:41:44 +00005681 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5682 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005683
Owen Anderson53aa7a92009-08-10 22:56:29 +00005684 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005685
Chris Lattner9a499e92010-12-22 08:01:44 +00005686 // Do not generate loads of non-round integer types since these can
5687 // be expensive (and would be wrong if the type is not byte sized).
5688 if (!ExtVT.isRound())
5689 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005690
Evan Cheng464dc9b2007-03-22 01:54:19 +00005691 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005692 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005693 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005694 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005695 // Is the shift amount a multiple of size of VT?
5696 if ((ShAmt & (EVTBits-1)) == 0) {
5697 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005698 // Is the load width a multiple of size of VT?
5699 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005700 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005701 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005702
Chris Lattnercafc1e62010-12-22 08:02:57 +00005703 // At this point, we must have a load or else we can't do the transform.
5704 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005705
Chandler Carruthb27041c2012-12-11 00:36:57 +00005706 // Because a SRL must be assumed to *need* to zero-extend the high bits
5707 // (as opposed to anyext the high bits), we can't combine the zextload
5708 // lowering of SRL and an sextload.
5709 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5710 return SDValue();
5711
Chris Lattnera2050552010-10-01 05:36:09 +00005712 // If the shift amount is larger than the input type then we're not
5713 // accessing any of the loaded bytes. If the load was a zextload/extload
5714 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005715 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005716 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005717 }
5718 }
5719
Dan Gohman68fb0042010-11-03 01:47:46 +00005720 // If the load is shifted left (and the result isn't shifted back right),
5721 // we can fold the truncate through the shift.
5722 unsigned ShLeftAmt = 0;
5723 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005724 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005725 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5726 ShLeftAmt = N01->getZExtValue();
5727 N0 = N0.getOperand(0);
5728 }
5729 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005730
Chris Lattner222374d2010-12-22 07:36:50 +00005731 // If we haven't found a load, we can't narrow it. Don't transform one with
5732 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005733 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5734 return SDValue();
5735
5736 // Don't change the width of a volatile load.
5737 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5738 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005739 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005740
Chris Lattner9a499e92010-12-22 08:01:44 +00005741 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005742 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005743 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005744
Bill Schmidtd006c692013-01-14 22:04:38 +00005745 // For the transform to be legal, the load must produce only two values
5746 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005747 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005748 // transformation is not equivalent, and the downstream logic to replace
5749 // uses gets things wrong.
5750 if (LN0->getNumValues() > 2)
5751 return SDValue();
5752
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005753 // If the load that we're shrinking is an extload and we're not just
5754 // discarding the extension we can't simply shrink the load. Bail.
5755 // TODO: It would be possible to merge the extensions in some cases.
5756 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5757 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5758 return SDValue();
5759
Chris Lattner222374d2010-12-22 07:36:50 +00005760 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005761
Evan Cheng4c6f9172012-06-26 01:19:33 +00005762 if (PtrType == MVT::Untyped || PtrType.isExtended())
5763 // It's not possible to generate a constant of extended or untyped type.
5764 return SDValue();
5765
Chris Lattner222374d2010-12-22 07:36:50 +00005766 // For big endian targets, we need to adjust the offset to the pointer to
5767 // load the correct bytes.
5768 if (TLI.isBigEndian()) {
5769 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5770 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5771 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005772 }
5773
Chris Lattner222374d2010-12-22 07:36:50 +00005774 uint64_t PtrOff = ShAmt / 8;
5775 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005776 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005777 PtrType, LN0->getBasePtr(),
5778 DAG.getConstant(PtrOff, PtrType));
5779 AddToWorkList(NewPtr.getNode());
5780
Chris Lattner9a499e92010-12-22 08:01:44 +00005781 SDValue Load;
5782 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005783 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005784 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005785 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005786 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005787 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005788 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005789 LN0->getPointerInfo().getWithOffset(PtrOff),
5790 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005791 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005792
5793 // Replace the old load's chain with the new load's chain.
5794 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005795 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005796
5797 // Shift the result left, if we've swallowed a left shift.
5798 SDValue Result = Load;
5799 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005800 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005801 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5802 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005803 // If the shift amount is as large as the result size (but, presumably,
5804 // no larger than the source) then the useful bits of the result are
5805 // zero; we can't simply return the shortened shift, because the result
5806 // of that operation is undefined.
5807 if (ShLeftAmt >= VT.getSizeInBits())
5808 Result = DAG.getConstant(0, VT);
5809 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005810 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005811 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005812 }
5813
5814 // Return the new loaded value.
5815 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005816}
5817
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005818SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5819 SDValue N0 = N->getOperand(0);
5820 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005821 EVT VT = N->getValueType(0);
5822 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005823 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005824 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005825
Nate Begeman21158fc2005-09-01 00:19:25 +00005826 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005827 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005828 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005829
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005830 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005831 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005832 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005833
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005834 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5835 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005836 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005837 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005838 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005839
Dan Gohman345d63c2008-07-31 00:50:31 +00005840 // fold (sext_in_reg (sext x)) -> (sext x)
5841 // fold (sext_in_reg (aext x)) -> (sext x)
5842 // if x is small enough.
5843 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5844 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005845 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5846 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005847 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005848 }
5849
Chris Lattner9ad59152007-04-17 19:03:21 +00005850 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005851 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005852 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005853
Chris Lattner9ad59152007-04-17 19:03:21 +00005854 // fold operands of sext_in_reg based on knowledge that the top bits are not
5855 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005856 if (SimplifyDemandedBits(SDValue(N, 0)))
5857 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005858
Evan Cheng464dc9b2007-03-22 01:54:19 +00005859 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5860 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005861 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005862 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005863 return NarrowLoad;
5864
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005865 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005866 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005867 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5868 if (N0.getOpcode() == ISD::SRL) {
5869 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005870 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005871 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005872 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005873 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005874 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005875 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005876 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005877 }
5878 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005879
Nate Begeman02b23c62005-10-13 03:11:28 +00005880 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005881 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005882 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005883 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005884 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005885 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005886 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005887 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005888 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005889 LN0->getBasePtr(), EVT,
5890 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005891 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005892 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005893 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005895 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005896 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005897 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005898 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005899 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005900 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005901 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005902 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005903 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005904 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005905 LN0->getBasePtr(), EVT,
5906 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005907 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005908 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005910 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005911
5912 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5913 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5914 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5915 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005916 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005917 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005918 BSwap, N1);
5919 }
5920
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005921 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5922 // into a build_vector.
5923 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5924 SmallVector<SDValue, 8> Elts;
5925 unsigned NumElts = N0->getNumOperands();
5926 unsigned ShAmt = VTBits - EVTBits;
5927
5928 for (unsigned i = 0; i != NumElts; ++i) {
5929 SDValue Op = N0->getOperand(i);
5930 if (Op->getOpcode() == ISD::UNDEF) {
5931 Elts.push_back(Op);
5932 continue;
5933 }
5934
5935 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005936 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5937 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005938 Op.getValueType()));
5939 }
5940
Craig Topper48d114b2014-04-26 18:35:24 +00005941 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005942 }
5943
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005944 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005945}
5946
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005947SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5948 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005949 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005950 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005951
5952 // noop truncate
5953 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005954 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005955 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005956 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005957 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005958 // fold (truncate (truncate x)) -> (truncate x)
5959 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005960 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005961 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005962 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5963 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005964 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005965 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005966 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005967 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005968 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005969 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005970 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005971 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005972 // if the source and dest are the same type, we can drop both the extend
5973 // and the truncate.
5974 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005975 }
Evan Chengd63baea2007-03-21 20:14:05 +00005976
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005977 // Fold extract-and-trunc into a narrow extract. For example:
5978 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5979 // i32 y = TRUNCATE(i64 x)
5980 // -- becomes --
5981 // v16i8 b = BITCAST (v2i64 val)
5982 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5983 //
5984 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005985 // creates this pattern) and before operation legalization after which
5986 // we need to be more careful about the vector instructions that we generate.
5987 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005988 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005989
5990 EVT VecTy = N0.getOperand(0).getValueType();
5991 EVT ExTy = N0.getValueType();
5992 EVT TrTy = N->getValueType(0);
5993
5994 unsigned NumElem = VecTy.getVectorNumElements();
5995 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5996
5997 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5998 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5999
6000 SDValue EltNo = N0->getOperand(1);
6001 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6002 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006003 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006004 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6005
Andrew Trickef9de2a2013-05-25 02:42:55 +00006006 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006007 NVT, N0.getOperand(0));
6008
6009 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006010 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006011 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006012 }
6013 }
6014
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006015 // Fold a series of buildvector, bitcast, and truncate if possible.
6016 // For example fold
6017 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6018 // (2xi32 (buildvector x, y)).
6019 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6020 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6021 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6022 N0.getOperand(0).hasOneUse()) {
6023
6024 SDValue BuildVect = N0.getOperand(0);
6025 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6026 EVT TruncVecEltTy = VT.getVectorElementType();
6027
6028 // Check that the element types match.
6029 if (BuildVectEltTy == TruncVecEltTy) {
6030 // Now we only need to compute the offset of the truncated elements.
6031 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6032 unsigned TruncVecNumElts = VT.getVectorNumElements();
6033 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6034
6035 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6036 "Invalid number of elements");
6037
6038 SmallVector<SDValue, 8> Opnds;
6039 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6040 Opnds.push_back(BuildVect.getOperand(i));
6041
Craig Topper48d114b2014-04-26 18:35:24 +00006042 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006043 }
6044 }
6045
Chris Lattner5e6fe052007-10-13 06:35:54 +00006046 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006047 // only the low bits are being used.
6048 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006049 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006050 // may have different active low bits.
6051 if (!VT.isVector()) {
6052 SDValue Shorter =
6053 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6054 VT.getSizeInBits()));
6055 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006056 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006057 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006058 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006059 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006060 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6061 SDValue Reduced = ReduceLoadWidth(N);
6062 if (Reduced.getNode())
6063 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006064 // Handle the case where the load remains an extending load even
6065 // after truncation.
6066 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6067 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6068 if (!LN0->isVolatile() &&
6069 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6070 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6071 VT, LN0->getChain(), LN0->getBasePtr(),
6072 LN0->getMemoryVT(),
6073 LN0->getMemOperand());
6074 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6075 return NewLoad;
6076 }
6077 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006078 }
Michael Liao3ac82012012-10-17 23:45:54 +00006079 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6080 // where ... are all 'undef'.
6081 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6082 SmallVector<EVT, 8> VTs;
6083 SDValue V;
6084 unsigned Idx = 0;
6085 unsigned NumDefs = 0;
6086
6087 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6088 SDValue X = N0.getOperand(i);
6089 if (X.getOpcode() != ISD::UNDEF) {
6090 V = X;
6091 Idx = i;
6092 NumDefs++;
6093 }
6094 // Stop if more than one members are non-undef.
6095 if (NumDefs > 1)
6096 break;
6097 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6098 VT.getVectorElementType(),
6099 X.getValueType().getVectorNumElements()));
6100 }
6101
6102 if (NumDefs == 0)
6103 return DAG.getUNDEF(VT);
6104
6105 if (NumDefs == 1) {
6106 assert(V.getNode() && "The single defined operand is empty!");
6107 SmallVector<SDValue, 8> Opnds;
6108 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6109 if (i != Idx) {
6110 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6111 continue;
6112 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006113 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00006114 AddToWorkList(NV.getNode());
6115 Opnds.push_back(NV);
6116 }
Craig Topper48d114b2014-04-26 18:35:24 +00006117 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006118 }
6119 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006120
6121 // Simplify the operands using demanded-bits information.
6122 if (!VT.isVector() &&
6123 SimplifyDemandedBits(SDValue(N, 0)))
6124 return SDValue(N, 0);
6125
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006126 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006127}
6128
Evan Chengb980f6f2008-05-12 23:04:07 +00006129static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006130 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006131 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006132 return Elt.getNode();
6133 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006134}
6135
6136/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006137/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006138SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006139 assert(N->getOpcode() == ISD::BUILD_PAIR);
6140
Nate Begeman624690c2009-06-05 21:37:30 +00006141 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6142 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006143 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006144 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006145 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006146 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006147
Evan Chengb980f6f2008-05-12 23:04:07 +00006148 if (ISD::isNON_EXTLoad(LD2) &&
6149 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006150 // If both are volatile this would reduce the number of volatile loads.
6151 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006152 !LD1->isVolatile() &&
6153 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006154 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006155 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006156 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006157 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006158
Duncan Sands8651e9c2008-06-13 19:07:40 +00006159 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006160 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006161 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006162 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006163 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006164 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006166 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006167}
6168
Wesley Peck527da1b2010-11-23 03:31:01 +00006169SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006170 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006171 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006172
Dan Gohmana8665142007-06-25 16:23:39 +00006173 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6174 // Only do this before legalize, since afterward the target may be depending
6175 // on the bitconvert.
6176 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006177 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006178 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006179 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006180 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006181
Owen Anderson53aa7a92009-08-10 22:56:29 +00006182 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006183 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006184 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006185 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006186 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006187 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006188
Dan Gohman921ddd62008-09-05 01:58:21 +00006189 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006190 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006191 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006192 if (Res.getNode() != N) {
6193 if (!LegalOperations ||
6194 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6195 return Res;
6196
6197 // Folding it resulted in an illegal node, and it's too late to
6198 // do that. Clean up the old node and forego the transformation.
6199 // Ideally this won't happen very often, because instcombine
6200 // and the earlier dagcombine runs (where illegal nodes are
6201 // permitted) should have folded most of them already.
6202 DAG.DeleteNode(Res.getNode());
6203 }
Chris Lattnera1874602005-12-23 05:30:37 +00006204 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006205
Bill Wendling4e0a6152009-01-30 22:44:24 +00006206 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006207 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006208 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006209 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006210
Chris Lattner54560f62005-12-23 05:44:41 +00006211 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006212 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006213 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006214 // Do not change the width of a volatile load.
6215 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006216 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6217 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006218 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006219 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006220 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006221 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006222
Evan Chenga4cf58a2007-05-07 21:27:48 +00006223 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006224 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006225 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006226 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006227 LN0->isInvariant(), OrigAlign,
6228 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006229 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006230 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006231 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006232 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006233 Load.getValue(1));
6234 return Load;
6235 }
Chris Lattner54560f62005-12-23 05:44:41 +00006236 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006237
Bill Wendling4e0a6152009-01-30 22:44:24 +00006238 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6239 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006240 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006241 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6242 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006243 N0.getNode()->hasOneUse() && VT.isInteger() &&
6244 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006245 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006246 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006247 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006248
Duncan Sands13237ac2008-06-06 12:08:01 +00006249 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006250 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006251 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006252 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006253 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006254 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006255 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006256 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006257
Bill Wendling4e0a6152009-01-30 22:44:24 +00006258 // fold (bitconvert (fcopysign cst, x)) ->
6259 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6260 // Note that we don't handle (copysign x, cst) because this can always be
6261 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006262 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006263 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006264 VT.isInteger() && !VT.isVector()) {
6265 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006266 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006267 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006268 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006269 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006270 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006271
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006272 // If X has a different width than the result/lhs, sext it or truncate it.
6273 unsigned VTWidth = VT.getSizeInBits();
6274 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006275 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006276 AddToWorkList(X.getNode());
6277 } else if (OrigXWidth > VTWidth) {
6278 // To get the sign bit in the right place, we have to shift it right
6279 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006280 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006281 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006282 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6283 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006284 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006285 AddToWorkList(X.getNode());
6286 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006287
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006288 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006289 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006290 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006291 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006292
Andrew Trickef9de2a2013-05-25 02:42:55 +00006293 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006294 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006295 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006296 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006297 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006298
Andrew Trickef9de2a2013-05-25 02:42:55 +00006299 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006300 }
Chris Lattner888560d2008-01-27 17:42:27 +00006301 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006302
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006303 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006304 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006305 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6306 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006307 return CombineLD;
6308 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006309
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006310 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006311}
6312
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006313SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006314 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006315 return CombineConsecutiveLoads(N, VT);
6316}
6317
Wesley Peck527da1b2010-11-23 03:31:01 +00006318/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006319/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006320/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006321SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006322ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006323 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006324
Chris Lattnere4e64b62006-04-02 02:53:43 +00006325 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006326 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006327
Duncan Sands13237ac2008-06-06 12:08:01 +00006328 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6329 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006330
Chris Lattnere4e64b62006-04-02 02:53:43 +00006331 // If this is a conversion of N elements of one type to N elements of another
6332 // type, convert each element. This handles FP<->INT cases.
6333 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006334 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6335 BV->getValueType(0).getVectorNumElements());
6336
6337 // Due to the FP element handling below calling this routine recursively,
6338 // we can end up with a scalar-to-vector node here.
6339 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006340 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6341 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006342 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006343
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006344 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006345 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006346 SDValue Op = BV->getOperand(i);
6347 // If the vector element type is not legal, the BUILD_VECTOR operands
6348 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006349 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006350 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6351 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006352 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006353 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006354 }
Craig Topper48d114b2014-04-26 18:35:24 +00006355 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006356 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006357
Chris Lattnere4e64b62006-04-02 02:53:43 +00006358 // Otherwise, we're growing or shrinking the elements. To avoid having to
6359 // handle annoying details of growing/shrinking FP values, we convert them to
6360 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006361 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006362 // Convert the input float vector to a int vector where the elements are the
6363 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006364 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006365 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006366 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006367 SrcEltVT = IntVT;
6368 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006369
Chris Lattnere4e64b62006-04-02 02:53:43 +00006370 // Now we know the input is an integer vector. If the output is a FP type,
6371 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006372 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006373 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006374 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006375 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006376
Chris Lattnere4e64b62006-04-02 02:53:43 +00006377 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006378 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006379 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006380
Chris Lattnere4e64b62006-04-02 02:53:43 +00006381 // Okay, we know the src/dst types are both integers of differing types.
6382 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006383 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006384 if (SrcBitSize < DstBitSize) {
6385 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006386
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006387 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006388 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006389 i += NumInputsPerOutput) {
6390 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006391 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006392 bool EltIsUndef = true;
6393 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6394 // Shift the previously computed bits over.
6395 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006396 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006397 if (Op.getOpcode() == ISD::UNDEF) continue;
6398 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006399
Jay Foad583abbc2010-12-07 08:25:19 +00006400 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006401 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006402 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006403
Chris Lattnere4e64b62006-04-02 02:53:43 +00006404 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006405 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006406 else
6407 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6408 }
6409
Owen Anderson117c9e82009-08-12 00:36:31 +00006410 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006411 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006412 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006413
Chris Lattnere4e64b62006-04-02 02:53:43 +00006414 // Finally, this must be the case where we are shrinking elements: each input
6415 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006416 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006417 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006418 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6419 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006420 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006421
Dan Gohmana8665142007-06-25 16:23:39 +00006422 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006423 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6424 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006425 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006426 continue;
6427 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006428
Jay Foad583abbc2010-12-07 08:25:19 +00006429 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6430 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006431
Chris Lattnere4e64b62006-04-02 02:53:43 +00006432 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006433 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006434 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006435 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006436 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006437 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006438 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006439 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006440 }
6441
6442 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006443 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006444 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6445 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006446
Craig Topper48d114b2014-04-26 18:35:24 +00006447 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006448}
6449
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006450SDValue DAGCombiner::visitFADD(SDNode *N) {
6451 SDValue N0 = N->getOperand(0);
6452 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006453 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6454 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006455 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006456
Dan Gohmana8665142007-06-25 16:23:39 +00006457 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006458 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006459 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006460 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006461 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006462
Lang Hamesa33db652012-06-14 20:37:15 +00006463 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006464 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006465 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006466 // canonicalize constant to RHS
6467 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006468 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006469 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006470 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6471 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006472 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006473 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006474 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006475 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006476 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006477 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006478 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006479 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006480 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006481 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006482 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006483
Chris Lattner0199fd62007-01-08 23:04:05 +00006484 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006485 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6486 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6487 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006488 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6489 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006490 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006491
Shuxin Yang93b1f122013-03-25 22:52:29 +00006492 // No FP constant should be created after legalization as Instruction
6493 // Selection pass has hard time in dealing with FP constant.
6494 //
6495 // We don't need test this condition for transformation like following, as
6496 // the DAG being transformed implies it is legal to take FP constant as
6497 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006498 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006499 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006500 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006501 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6502
Owen Andersonb351c8d2012-11-01 02:00:53 +00006503 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006504 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006505 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006506 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006507
6508 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006509 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006510 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006511 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006512
Owen Andersoncc61f872012-08-30 23:35:16 +00006513 // In unsafe math mode, we can fold chains of FADD's of the same value
6514 // into multiplications. This transform is not safe in general because
6515 // we are reducing the number of rounding steps.
6516 if (DAG.getTarget().Options.UnsafeFPMath &&
6517 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6518 !N0CFP && !N1CFP) {
6519 if (N0.getOpcode() == ISD::FMUL) {
6520 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6521 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6522
Stephen Line31f2d22013-06-14 18:17:35 +00006523 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006524 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006525 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006526 SDValue(CFP00, 0),
6527 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006528 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006529 N1, NewCFP);
6530 }
6531
Stephen Line31f2d22013-06-14 18:17:35 +00006532 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006533 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
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(CFP01, 0),
6536 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006538 N1, NewCFP);
6539 }
6540
Stephen Line31f2d22013-06-14 18:17:35 +00006541 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006542 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6543 N1.getOperand(0) == N1.getOperand(1) &&
6544 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006545 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006546 SDValue(CFP00, 0),
6547 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006548 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006549 N0.getOperand(1), NewCFP);
6550 }
6551
Stephen Line31f2d22013-06-14 18:17:35 +00006552 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006553 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6554 N1.getOperand(0) == N1.getOperand(1) &&
6555 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006556 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006557 SDValue(CFP01, 0),
6558 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006559 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006560 N0.getOperand(0), NewCFP);
6561 }
6562 }
6563
6564 if (N1.getOpcode() == ISD::FMUL) {
6565 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6566 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6567
Stephen Line31f2d22013-06-14 18:17:35 +00006568 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006569 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006570 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006571 SDValue(CFP10, 0),
6572 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006573 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006574 N0, NewCFP);
6575 }
6576
Stephen Line31f2d22013-06-14 18:17:35 +00006577 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006578 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006579 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006580 SDValue(CFP11, 0),
6581 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006582 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006583 N0, NewCFP);
6584 }
6585
Owen Andersoncc61f872012-08-30 23:35:16 +00006586
Stephen Line31f2d22013-06-14 18:17:35 +00006587 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6588 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6589 N0.getOperand(0) == N0.getOperand(1) &&
6590 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006591 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006592 SDValue(CFP10, 0),
6593 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006594 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006595 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006596 }
6597
Stephen Line31f2d22013-06-14 18:17:35 +00006598 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6599 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6600 N0.getOperand(0) == N0.getOperand(1) &&
6601 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006602 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006603 SDValue(CFP11, 0),
6604 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006605 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006606 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006607 }
6608 }
6609
Shuxin Yang93b1f122013-03-25 22:52:29 +00006610 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006611 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006612 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006613 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006614 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006615 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006616 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006617 }
6618
Shuxin Yang93b1f122013-03-25 22:52:29 +00006619 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006620 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006621 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006622 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006623 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006624 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006625 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006626 }
6627
Stephen Lin4e69d012013-06-14 21:33:58 +00006628 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006629 if (AllowNewFpConst &&
6630 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006631 N0.getOperand(0) == N0.getOperand(1) &&
6632 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006633 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006634 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006635 N0.getOperand(0),
6636 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006637 }
6638
Lang Hames39fb1d02012-06-19 22:51:23 +00006639 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006640 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006641 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006642 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6643 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006644
6645 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006646 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006647 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006648 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006649
Michael Liaoec3850122012-09-01 04:09:16 +00006650 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006651 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006652 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006653 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006654 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006655 }
6656
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006657 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006658}
6659
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006660SDValue DAGCombiner::visitFSUB(SDNode *N) {
6661 SDValue N0 = N->getOperand(0);
6662 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006663 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6664 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006665 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006666 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006667
Dan Gohmana8665142007-06-25 16:23:39 +00006668 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006669 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006670 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006671 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006672 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006673
Nate Begeman418c6e42005-10-18 00:28:13 +00006674 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006675 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006676 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006677 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006678 if (DAG.getTarget().Options.UnsafeFPMath &&
6679 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006680 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006681 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006682 if (DAG.getTarget().Options.UnsafeFPMath &&
6683 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006684 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006685 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006686 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006687 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006688 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006689 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006690 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006691 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006692 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006693
Bill Wendlingdf170db2012-03-15 05:12:00 +00006694 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006695 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006696 // (fsub x, (fadd x, y)) -> (fneg y) &
6697 // (fsub x, (fadd y, x)) -> (fneg y)
6698 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006699 if (N0 == N1)
6700 return DAG.getConstantFP(0.0f, VT);
6701
Bill Wendlingdf170db2012-03-15 05:12:00 +00006702 if (N1.getOpcode() == ISD::FADD) {
6703 SDValue N10 = N1->getOperand(0);
6704 SDValue N11 = N1->getOperand(1);
6705
6706 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6707 &DAG.getTarget().Options))
6708 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006709
Stephen Lin8e8424e2013-07-09 00:44:49 +00006710 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6711 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006712 return GetNegatedExpression(N10, DAG, LegalOperations);
6713 }
6714 }
6715
Lang Hames39fb1d02012-06-19 22:51:23 +00006716 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006717 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006718 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006719 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6720 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006721
6722 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006723 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006724 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006725 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006726 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006727
6728 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6729 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006730 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006731 return DAG.getNode(ISD::FMA, dl, VT,
6732 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006733 N1.getOperand(0)),
6734 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006735
Stephen Lin8e8424e2013-07-09 00:44:49 +00006736 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006737 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006738 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6739 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6740 SDValue N00 = N0.getOperand(0).getOperand(0);
6741 SDValue N01 = N0.getOperand(0).getOperand(1);
6742 return DAG.getNode(ISD::FMA, dl, VT,
6743 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6744 DAG.getNode(ISD::FNEG, dl, VT, N1));
6745 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006746 }
6747
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006748 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006749}
6750
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006751SDValue DAGCombiner::visitFMUL(SDNode *N) {
6752 SDValue N0 = N->getOperand(0);
6753 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006754 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6755 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006756 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006758
Dan Gohmana8665142007-06-25 16:23:39 +00006759 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006760 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006761 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006762 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006763 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006764
Nate Begemanec48a1b2005-10-17 20:40:11 +00006765 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006766 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006767 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006768 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006769 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006770 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006771 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006772 if (DAG.getTarget().Options.UnsafeFPMath &&
6773 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006774 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006775 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006776 if (DAG.getTarget().Options.UnsafeFPMath &&
6777 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006778 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006779 // fold (fmul A, 1.0) -> A
6780 if (N1CFP && N1CFP->isExactlyValue(1.0))
6781 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006782 // fold (fmul X, 2.0) -> (fadd X, X)
6783 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006784 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006785 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006786 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006787 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006788 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006789
Bill Wendling3dc5d242009-01-30 22:57:07 +00006790 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006791 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006792 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006793 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006794 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006795 // Both can be negated for free, check to see if at least one is cheaper
6796 // negated.
6797 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006798 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006799 GetNegatedExpression(N0, DAG, LegalOperations),
6800 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006801 }
6802 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006803
Chris Lattner0199fd62007-01-08 23:04:05 +00006804 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006805 if (DAG.getTarget().Options.UnsafeFPMath &&
6806 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006807 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006808 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6809 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006810 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006811
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006812 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006813}
6814
Owen Anderson41b06652012-05-02 22:17:40 +00006815SDValue DAGCombiner::visitFMA(SDNode *N) {
6816 SDValue N0 = N->getOperand(0);
6817 SDValue N1 = N->getOperand(1);
6818 SDValue N2 = N->getOperand(2);
6819 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6820 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6821 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006822 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006823
Owen Andersonb351c8d2012-11-01 02:00:53 +00006824 if (DAG.getTarget().Options.UnsafeFPMath) {
6825 if (N0CFP && N0CFP->isZero())
6826 return N2;
6827 if (N1CFP && N1CFP->isZero())
6828 return N2;
6829 }
Owen Anderson41b06652012-05-02 22:17:40 +00006830 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006831 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006832 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006833 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006834
Owen Andersonc7aaf522012-05-30 18:50:39 +00006835 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006836 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006837 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006838
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006839 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6840 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6841 N2.getOpcode() == ISD::FMUL &&
6842 N0 == N2.getOperand(0) &&
6843 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6844 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6845 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6846 }
6847
6848
6849 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6850 if (DAG.getTarget().Options.UnsafeFPMath &&
6851 N0.getOpcode() == ISD::FMUL && N1CFP &&
6852 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6853 return DAG.getNode(ISD::FMA, dl, VT,
6854 N0.getOperand(0),
6855 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6856 N2);
6857 }
6858
6859 // (fma x, 1, y) -> (fadd x, y)
6860 // (fma x, -1, y) -> (fadd (fneg x), y)
6861 if (N1CFP) {
6862 if (N1CFP->isExactlyValue(1.0))
6863 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6864
6865 if (N1CFP->isExactlyValue(-1.0) &&
6866 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6867 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6868 AddToWorkList(RHSNeg.getNode());
6869 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6870 }
6871 }
6872
6873 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006874 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6875 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006876 DAG.getNode(ISD::FADD, dl, VT,
6877 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006878
6879 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6880 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006881 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6882 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006883 DAG.getNode(ISD::FADD, dl, VT,
6884 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006885
6886
Owen Anderson41b06652012-05-02 22:17:40 +00006887 return SDValue();
6888}
6889
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006890SDValue DAGCombiner::visitFDIV(SDNode *N) {
6891 SDValue N0 = N->getOperand(0);
6892 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +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);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006897
Dan Gohmana8665142007-06-25 16:23:39 +00006898 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006899 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006900 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006901 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006902 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006903
Nate Begeman569c4392006-01-18 22:35:16 +00006904 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006905 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006906 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006907
Duncan Sands2f1dc382012-04-08 18:08:12 +00006908 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006909 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006910 // Compute the reciprocal 1.0 / c2.
6911 APFloat N1APF = N1CFP->getValueAPF();
6912 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6913 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006914 // Only do the transform if the reciprocal is a legal fp immediate that
6915 // isn't too nasty (eg NaN, denormal, ...).
6916 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006917 (!LegalOperations ||
6918 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6919 // backend)... we should handle this gracefully after Legalize.
6920 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6921 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6922 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006923 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006924 DAG.getConstantFP(Recip, VT));
6925 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006926
Bill Wendling3dc5d242009-01-30 22:57:07 +00006927 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006928 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006929 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006930 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006931 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006932 // Both can be negated for free, check to see if at least one is cheaper
6933 // negated.
6934 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006935 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006936 GetNegatedExpression(N0, DAG, LegalOperations),
6937 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006938 }
6939 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006940
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006941 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006942}
6943
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006944SDValue DAGCombiner::visitFREM(SDNode *N) {
6945 SDValue N0 = N->getOperand(0);
6946 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006947 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6948 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006949 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006950
Nate Begeman569c4392006-01-18 22:35:16 +00006951 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006952 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006953 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006954
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006955 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006956}
6957
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006958SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6959 SDValue N0 = N->getOperand(0);
6960 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006961 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6962 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006963 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006964
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006965 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006966 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006967
Chris Lattner3bc40502006-03-05 05:30:57 +00006968 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006969 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006970 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6971 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006972 if (!V.isNegative()) {
6973 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006974 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006975 } else {
6976 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006977 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6978 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006979 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006980 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006981
Chris Lattner3bc40502006-03-05 05:30:57 +00006982 // copysign(fabs(x), y) -> copysign(x, y)
6983 // copysign(fneg(x), y) -> copysign(x, y)
6984 // copysign(copysign(x,z), y) -> copysign(x, y)
6985 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6986 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006987 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006988 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006989
6990 // copysign(x, abs(y)) -> abs(x)
6991 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006992 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006993
Chris Lattner3bc40502006-03-05 05:30:57 +00006994 // copysign(x, copysign(y,z)) -> copysign(x, z)
6995 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006996 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006997 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006998
Chris Lattner3bc40502006-03-05 05:30:57 +00006999 // copysign(x, fp_extend(y)) -> copysign(x, y)
7000 // copysign(x, fp_round(y)) -> copysign(x, y)
7001 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007002 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007003 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007004
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007005 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007006}
7007
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007008SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7009 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007010 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007011 EVT VT = N->getValueType(0);
7012 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007013
Nate Begeman21158fc2005-09-01 00:19:25 +00007014 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007015 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007016 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007017 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007018 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007019 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007020
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007021 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7022 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007023 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7024 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007025 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007026 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007027 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007028 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007029
Alp Tokercb402912014-01-24 17:20:08 +00007030 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00007031 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7032 // having to say they don't support SELECT_CC on every type the DAG knows
7033 // about, since there is no way to mark an opcode illegal at all value types
7034 // (See also visitSELECT)
7035 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7036 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7037 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7038 !VT.isVector() &&
7039 (!LegalOperations ||
7040 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7041 SDValue Ops[] =
7042 { N0.getOperand(0), N0.getOperand(1),
7043 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7044 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007045 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007046 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007047
Nadav Rotem90560762012-07-23 07:59:50 +00007048 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7049 // (select_cc x, y, 1.0, 0.0,, cc)
7050 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7051 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7052 (!LegalOperations ||
7053 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7054 SDValue Ops[] =
7055 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7056 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7057 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007058 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007059 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007060 }
7061
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::visitUINT_TO_FP(SDNode *N) {
7066 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007067 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007068 EVT VT = N->getValueType(0);
7069 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007070
Nate Begeman21158fc2005-09-01 00:19:25 +00007071 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007072 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007073 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007074 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007075 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007076 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007077
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007078 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7079 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007080 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7081 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007082 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007083 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007084 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007085 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007086
Alp Tokercb402912014-01-24 17:20:08 +00007087 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00007088 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7089 // having to say they don't support SELECT_CC on every type the DAG knows
7090 // about, since there is no way to mark an opcode illegal at all value types
7091 // (See also visitSELECT)
7092 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7093 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007094
Nadav Rotem90560762012-07-23 07:59:50 +00007095 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7096 (!LegalOperations ||
7097 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7098 SDValue Ops[] =
7099 { N0.getOperand(0), N0.getOperand(1),
7100 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7101 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007102 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007103 }
7104 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007105
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007106 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007107}
7108
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007109SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7110 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007111 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007112 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007113
Nate Begeman21158fc2005-09-01 00:19:25 +00007114 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007115 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007116 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007117
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007118 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007119}
7120
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007121SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7122 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007123 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007124 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007125
Nate Begeman21158fc2005-09-01 00:19:25 +00007126 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007127 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007128 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007129
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007130 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007131}
7132
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007133SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7134 SDValue N0 = N->getOperand(0);
7135 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007136 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007137 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007138
Nate Begeman21158fc2005-09-01 00:19:25 +00007139 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007140 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007141 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007142
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007143 // fold (fp_round (fp_extend x)) -> x
7144 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7145 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007146
Chris Lattner0feb1b02008-01-24 06:45:35 +00007147 // fold (fp_round (fp_round x)) -> (fp_round x)
7148 if (N0.getOpcode() == ISD::FP_ROUND) {
7149 // This is a value preserving truncation if both round's are.
7150 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007151 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007152 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007153 DAG.getIntPtrConstant(IsTrunc));
7154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007155
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007156 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007157 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007158 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007159 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007160 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007161 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007162 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007163 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007164
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007165 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007166}
7167
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007168SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7169 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007170 EVT VT = N->getValueType(0);
7171 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007172 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007173
Nate Begeman21158fc2005-09-01 00:19:25 +00007174 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007175 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007176 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007177 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007178 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007179
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007180 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007181}
7182
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007183SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7184 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007185 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007186 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007187
Chris Lattner5919b482007-12-29 06:55:23 +00007188 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007189 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007190 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007191 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007192
Nate Begeman21158fc2005-09-01 00:19:25 +00007193 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007194 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007195 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007196
7197 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7198 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007199 if (N0.getOpcode() == ISD::FP_ROUND
7200 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007201 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007202 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007203 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007204 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007205 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007206 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007207 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007208
Chris Lattner72733e52008-01-17 07:00:52 +00007209 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007210 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007211 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007212 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007213 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007214 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007215 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007216 LN0->getBasePtr(), N0.getValueType(),
7217 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007218 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007219 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007220 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007221 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007222 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007223 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007224 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007225
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007226 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007227}
7228
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007229SDValue DAGCombiner::visitFNEG(SDNode *N) {
7230 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007231 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007232
Craig Topper82384612012-09-11 01:45:21 +00007233 if (VT.isVector()) {
7234 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7235 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007236 }
7237
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007238 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7239 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007240 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007241
Chris Lattner888560d2008-01-27 17:42:27 +00007242 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7243 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007244 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007245 !VT.isVector() &&
7246 N0.getNode()->hasOneUse() &&
7247 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007248 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007249 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007250 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007251 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007252 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007253 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007254 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007255 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007256 }
7257 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007258
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007259 // (fneg (fmul c, x)) -> (fmul -c, x)
7260 if (N0.getOpcode() == ISD::FMUL) {
7261 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007262 if (CFP1) {
7263 APFloat CVal = CFP1->getValueAPF();
7264 CVal.changeSign();
7265 if (Level >= AfterLegalizeDAG &&
7266 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7267 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7268 return DAG.getNode(
7269 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7270 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7271 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007272 }
7273
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007274 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007275}
7276
Owen Andersona40319b2012-08-13 23:32:49 +00007277SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7278 SDValue N0 = N->getOperand(0);
7279 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7280 EVT VT = N->getValueType(0);
7281
7282 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007283 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007284 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007285
7286 return SDValue();
7287}
7288
7289SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7290 SDValue N0 = N->getOperand(0);
7291 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7292 EVT VT = N->getValueType(0);
7293
7294 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007295 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007296 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007297
7298 return SDValue();
7299}
7300
7301SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7302 SDValue N0 = N->getOperand(0);
7303 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7304 EVT VT = N->getValueType(0);
7305
7306 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007307 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007308 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007309
7310 return SDValue();
7311}
7312
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007313SDValue DAGCombiner::visitFABS(SDNode *N) {
7314 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007315 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007316 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007317
Craig Topper82384612012-09-11 01:45:21 +00007318 if (VT.isVector()) {
7319 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7320 if (FoldedVOp.getNode()) return FoldedVOp;
7321 }
7322
Nate Begeman21158fc2005-09-01 00:19:25 +00007323 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007324 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007325 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007326 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007327 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007328 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007329 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007330 // fold (fabs (fcopysign x, y)) -> (fabs x)
7331 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007332 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007333
Chris Lattner888560d2008-01-27 17:42:27 +00007334 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7335 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007336 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007337 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007338 N0.getOperand(0).getValueType().isInteger() &&
7339 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007340 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007341 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007342 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007343 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007344 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007345 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007346 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007347 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007348 }
7349 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007350
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007351 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007352}
7353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007354SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7355 SDValue Chain = N->getOperand(0);
7356 SDValue N1 = N->getOperand(1);
7357 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007358
Dan Gohman82e80012009-11-17 00:47:23 +00007359 // If N is a constant we could fold this into a fallthrough or unconditional
7360 // branch. However that doesn't happen very often in normal code, because
7361 // Instcombine/SimplifyCFG should have handled the available opportunities.
7362 // If we did this folding here, it would be necessary to update the
7363 // MachineBasicBlock CFG, which is awkward.
7364
Nate Begeman7e7f4392006-02-01 07:19:44 +00007365 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7366 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007367 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007368 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7369 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007370 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007371 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007372 N1.getOperand(0), N1.getOperand(1), N2);
7373 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007374
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007375 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7376 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7377 (N1.getOperand(0).hasOneUse() &&
7378 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007379 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007380 if (N1.getOpcode() == ISD::TRUNCATE) {
7381 // Look pass the truncate.
7382 Trunc = N1.getNode();
7383 N1 = N1.getOperand(0);
7384 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007385
Bill Wendlingaa28be62009-03-26 06:14:09 +00007386 // Match this pattern so that we can generate simpler code:
7387 //
7388 // %a = ...
7389 // %b = and i32 %a, 2
7390 // %c = srl i32 %b, 1
7391 // brcond i32 %c ...
7392 //
7393 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007394 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007395 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007396 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007397 // %c = setcc eq %b, 0
7398 // brcond %c ...
7399 //
7400 // This applies only when the AND constant value has one bit set and the
7401 // SRL constant is equal to the log2 of the AND constant. The back-end is
7402 // smart enough to convert the result into a TEST/JMP sequence.
7403 SDValue Op0 = N1.getOperand(0);
7404 SDValue Op1 = N1.getOperand(1);
7405
7406 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007407 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007408 SDValue AndOp1 = Op0.getOperand(1);
7409
7410 if (AndOp1.getOpcode() == ISD::Constant) {
7411 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7412
7413 if (AndConst.isPowerOf2() &&
7414 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7415 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007416 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007417 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007418 Op0, DAG.getConstant(0, Op0.getValueType()),
7419 ISD::SETNE);
7420
Andrew Trickef9de2a2013-05-25 02:42:55 +00007421 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007422 MVT::Other, Chain, SetCC, N2);
7423 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7424 // will convert it back to (X & C1) >> C2.
7425 CombineTo(N, NewBRCond, false);
7426 // Truncate is dead.
7427 if (Trunc) {
7428 removeFromWorkList(Trunc);
7429 DAG.DeleteNode(Trunc);
7430 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007431 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007432 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007433 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007434 removeFromWorkList(N1.getNode());
7435 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007436 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007437 }
7438 }
7439 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007440
7441 if (Trunc)
7442 // Restore N1 if the above transformation doesn't match.
7443 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007444 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007445
Evan Cheng228c31f2010-02-27 07:36:59 +00007446 // Transform br(xor(x, y)) -> br(x != y)
7447 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7448 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7449 SDNode *TheXor = N1.getNode();
7450 SDValue Op0 = TheXor->getOperand(0);
7451 SDValue Op1 = TheXor->getOperand(1);
7452 if (Op0.getOpcode() == Op1.getOpcode()) {
7453 // Avoid missing important xor optimizations.
7454 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007455 if (Tmp.getNode()) {
7456 if (Tmp.getNode() != TheXor) {
7457 DEBUG(dbgs() << "\nReplacing.8 ";
7458 TheXor->dump(&DAG);
7459 dbgs() << "\nWith: ";
7460 Tmp.getNode()->dump(&DAG);
7461 dbgs() << '\n');
7462 WorkListRemover DeadNodes(*this);
7463 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7464 removeFromWorkList(TheXor);
7465 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007466 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007467 MVT::Other, Chain, Tmp, N2);
7468 }
7469
Benjamin Kramer93354432013-03-30 21:28:18 +00007470 // visitXOR has changed XOR's operands or replaced the XOR completely,
7471 // bail out.
7472 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007473 }
7474 }
7475
7476 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7477 bool Equal = false;
7478 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7479 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7480 Op0.getOpcode() == ISD::XOR) {
7481 TheXor = Op0.getNode();
7482 Equal = true;
7483 }
7484
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007485 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007486 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007487 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007488 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007489 SetCCVT,
7490 Op0, Op1,
7491 Equal ? ISD::SETEQ : ISD::SETNE);
7492 // Replace the uses of XOR with SETCC
7493 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007494 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007495 removeFromWorkList(N1.getNode());
7496 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007497 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007498 MVT::Other, Chain, SetCC, N2);
7499 }
7500 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007501
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007502 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007503}
7504
Chris Lattnera49e16f2005-10-05 06:47:48 +00007505// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7506//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007507SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007508 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007509 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007510
Dan Gohman82e80012009-11-17 00:47:23 +00007511 // If N is a constant we could fold this into a fallthrough or unconditional
7512 // branch. However that doesn't happen very often in normal code, because
7513 // Instcombine/SimplifyCFG should have handled the available opportunities.
7514 // If we did this folding here, it would be necessary to update the
7515 // MachineBasicBlock CFG, which is awkward.
7516
Duncan Sands93b66092008-06-09 11:32:28 +00007517 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007518 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007519 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007520 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007521 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007522
Nate Begemanbd7df032005-10-05 21:43:42 +00007523 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007524 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007525 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007526 N->getOperand(0), Simp.getOperand(2),
7527 Simp.getOperand(0), Simp.getOperand(1),
7528 N->getOperand(4));
7529
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007530 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007531}
7532
Evan Chengfa832632012-01-13 01:37:24 +00007533/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7534/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007535/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007536static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7537 SelectionDAG &DAG,
7538 const TargetLowering &TLI) {
7539 EVT VT;
7540 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7541 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7542 return false;
7543 VT = Use->getValueType(0);
7544 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7545 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7546 return false;
7547 VT = ST->getValue().getValueType();
7548 } else
7549 return false;
7550
Chandler Carruth95f83e02013-01-07 15:14:13 +00007551 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007552 if (N->getOpcode() == ISD::ADD) {
7553 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7554 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007555 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007556 AM.BaseOffs = Offset->getSExtValue();
7557 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007558 // [reg +/- reg]
7559 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007560 } else if (N->getOpcode() == ISD::SUB) {
7561 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7562 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007563 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007564 AM.BaseOffs = -Offset->getSExtValue();
7565 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007566 // [reg +/- reg]
7567 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007568 } else
7569 return false;
7570
7571 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7572}
7573
Duncan Sands075293f2008-06-15 20:12:31 +00007574/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7575/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007576/// and it has other uses besides the load / store. After the
7577/// transformation, the new indexed load / store has effectively folded
7578/// the add / subtract in and all of its other uses are redirected to the
7579/// new load / store.
7580bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007581 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007582 return false;
7583
7584 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007585 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007586 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007587 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007588 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007589 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007590 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007591 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007592 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7593 return false;
7594 Ptr = LD->getBasePtr();
7595 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007596 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007597 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007598 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007599 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7600 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7601 return false;
7602 Ptr = ST->getBasePtr();
7603 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007604 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007605 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007606 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007607
Chris Lattnereabc15c2006-11-11 00:56:29 +00007608 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7609 // out. There is no reason to make this a preinc/predec.
7610 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007611 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007612 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007613
Chris Lattnereabc15c2006-11-11 00:56:29 +00007614 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007615 SDValue BasePtr;
7616 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007617 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7618 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7619 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007620
7621 // Backends without true r+i pre-indexed forms may need to pass a
7622 // constant base with a variable offset so that constant coercion
7623 // will work with the patterns in canonical form.
7624 bool Swapped = false;
7625 if (isa<ConstantSDNode>(BasePtr)) {
7626 std::swap(BasePtr, Offset);
7627 Swapped = true;
7628 }
7629
Evan Cheng044a0a82007-05-03 23:52:19 +00007630 // Don't create a indexed load / store with zero offset.
7631 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007632 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007633 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007634
Chris Lattnera0a80032006-11-11 01:00:15 +00007635 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007636 // 1) The new base ptr is a frame index.
7637 // 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 +00007638 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007639 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007640 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007641 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007642
Chris Lattnera0a80032006-11-11 01:00:15 +00007643 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7644 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007645 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007646 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007647
Chris Lattnera0a80032006-11-11 01:00:15 +00007648 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007649 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007650 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007651 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007652 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007653 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007654
Hal Finkel25819052013-02-08 21:35:47 +00007655 // If the offset is a constant, there may be other adds of constants that
7656 // can be folded with this one. We should do this to avoid having to keep
7657 // a copy of the original base pointer.
7658 SmallVector<SDNode *, 16> OtherUses;
7659 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007660 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007661 if (Use == Ptr.getNode())
7662 continue;
7663
7664 if (Use->isPredecessorOf(N))
7665 continue;
7666
7667 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7668 OtherUses.clear();
7669 break;
7670 }
7671
7672 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7673 if (Op1.getNode() == BasePtr.getNode())
7674 std::swap(Op0, Op1);
7675 assert(Op0.getNode() == BasePtr.getNode() &&
7676 "Use of ADD/SUB but not an operand");
7677
7678 if (!isa<ConstantSDNode>(Op1)) {
7679 OtherUses.clear();
7680 break;
7681 }
7682
7683 // FIXME: In some cases, we can be smarter about this.
7684 if (Op1.getValueType() != Offset.getValueType()) {
7685 OtherUses.clear();
7686 break;
7687 }
7688
7689 OtherUses.push_back(Use);
7690 }
7691
7692 if (Swapped)
7693 std::swap(BasePtr, Offset);
7694
Evan Chenga4d187b2007-05-24 02:35:39 +00007695 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007696 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007697
7698 // Caches for hasPredecessorHelper
7699 SmallPtrSet<const SDNode *, 32> Visited;
7700 SmallVector<const SDNode *, 16> Worklist;
7701
Jim Grosbache8160032014-04-11 01:13:13 +00007702 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007703 if (Use == N)
7704 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007705 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007706 return false;
7707
Evan Chengfa832632012-01-13 01:37:24 +00007708 // If Ptr may be folded in addressing mode of other use, then it's
7709 // not profitable to do this transformation.
7710 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007711 RealUse = true;
7712 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007713
Chris Lattnereabc15c2006-11-11 00:56:29 +00007714 if (!RealUse)
7715 return false;
7716
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007717 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007718 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007719 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007720 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007721 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007722 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007723 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007724 ++PreIndexedNodes;
7725 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007726 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007727 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007728 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007729 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007730 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007731 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007732 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007733 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7734 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007735 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007736 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007737 }
7738
Chris Lattnereabc15c2006-11-11 00:56:29 +00007739 // Finally, since the node is now dead, remove it from the graph.
7740 DAG.DeleteNode(N);
7741
Hal Finkel25819052013-02-08 21:35:47 +00007742 if (Swapped)
7743 std::swap(BasePtr, Offset);
7744
7745 // Replace other uses of BasePtr that can be updated to use Ptr
7746 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7747 unsigned OffsetIdx = 1;
7748 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7749 OffsetIdx = 0;
7750 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7751 BasePtr.getNode() && "Expected BasePtr operand");
7752
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007753 // We need to replace ptr0 in the following expression:
7754 // x0 * offset0 + y0 * ptr0 = t0
7755 // knowing that
7756 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007757 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007758 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7759 // indexed load/store and the expresion that needs to be re-written.
7760 //
7761 // Therefore, we have:
7762 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007763
7764 ConstantSDNode *CN =
7765 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007766 int X0, X1, Y0, Y1;
7767 APInt Offset0 = CN->getAPIntValue();
7768 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007769
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007770 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7771 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7772 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7773 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007774
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007775 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7776
7777 APInt CNV = Offset0;
7778 if (X0 < 0) CNV = -CNV;
7779 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7780 else CNV = CNV - Offset1;
7781
7782 // We can now generate the new expression.
7783 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7784 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7785
7786 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007787 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007788 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7789 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7790 removeFromWorkList(OtherUses[i]);
7791 DAG.DeleteNode(OtherUses[i]);
7792 }
7793
Chris Lattnereabc15c2006-11-11 00:56:29 +00007794 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007795 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007796 removeFromWorkList(Ptr.getNode());
7797 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007798
7799 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007800}
7801
Duncan Sands075293f2008-06-15 20:12:31 +00007802/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007803/// add / sub of the base pointer node into a post-indexed load / store.
7804/// The transformation folded the add / subtract into the new indexed
7805/// load / store effectively and all of its uses are redirected to the
7806/// new load / store.
7807bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007808 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007809 return false;
7810
7811 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007812 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007813 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007814 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007815 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007816 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007817 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007818 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7819 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7820 return false;
7821 Ptr = LD->getBasePtr();
7822 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007823 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007824 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007825 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007826 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7827 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7828 return false;
7829 Ptr = ST->getBasePtr();
7830 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007831 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007832 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007833 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007834
Gabor Greiff304a7a2008-08-28 21:40:38 +00007835 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007836 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007837
Jim Grosbache8160032014-04-11 01:13:13 +00007838 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007839 if (Op == N ||
7840 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7841 continue;
7842
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007843 SDValue BasePtr;
7844 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007845 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7846 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007847 // Don't create a indexed load / store with zero offset.
7848 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007849 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007850 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007851
Chris Lattnereabc15c2006-11-11 00:56:29 +00007852 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007853 // 1) All uses are load / store ops that use it as base ptr (and
7854 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007855 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7856 // nor a successor of N. Otherwise, if Op is folded that would
7857 // create a cycle.
7858
Evan Chengcfc05132009-05-06 18:25:01 +00007859 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7860 continue;
7861
Chris Lattnereabc15c2006-11-11 00:56:29 +00007862 // Check for #1.
7863 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007864 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007865 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007866 continue;
7867
Chris Lattnereabc15c2006-11-11 00:56:29 +00007868 // If all the uses are load / store addresses, then don't do the
7869 // transformation.
7870 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7871 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007872 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007873 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007874 RealUse = true;
7875 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007876
Chris Lattnereabc15c2006-11-11 00:56:29 +00007877 if (!RealUse) {
7878 TryNext = true;
7879 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007880 }
7881 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007882 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007883
Chris Lattnereabc15c2006-11-11 00:56:29 +00007884 if (TryNext)
7885 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007886
Chris Lattnereabc15c2006-11-11 00:56:29 +00007887 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007888 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007889 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007890 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007891 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007892 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007893 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007894 ++PostIndexedNodes;
7895 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007896 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007897 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007898 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007899 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007900 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007901 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007902 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007903 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7904 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007905 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007906 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007907 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007908
Chris Lattnereabc15c2006-11-11 00:56:29 +00007909 // Finally, since the node is now dead, remove it from the graph.
7910 DAG.DeleteNode(N);
7911
7912 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007913 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007914 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007915 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007916 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007917 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007918 }
7919 }
7920 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007921
Chris Lattnerffad2162006-11-11 00:39:41 +00007922 return false;
7923}
7924
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007925SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007926 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007927 SDValue Chain = LD->getChain();
7928 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007929
Evan Chenga684cd22007-05-01 00:38:21 +00007930 // If load is not volatile and there are no uses of the loaded value (and
7931 // the updated indexed value in case of indexed loads), change uses of the
7932 // chain value into uses of the chain input (i.e. delete the dead load).
7933 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007934 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007935 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007936 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007937 // It's not safe to use the two value CombineTo variant here. e.g.
7938 // v1, chain2 = load chain1, loc
7939 // v2, chain3 = load chain2, loc
7940 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007941 // Now we replace use of chain2 with chain1. This makes the second load
7942 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007943 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007944 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007945 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007946 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007947 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007948 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007949 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007950
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007951 if (N->use_empty()) {
7952 removeFromWorkList(N);
7953 DAG.DeleteNode(N);
7954 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007955
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007956 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007957 }
Evan Chengb68343c2007-05-01 08:53:39 +00007958 } else {
7959 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007960 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel2c77fe52014-05-28 15:33:19 +00007961 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007962 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007963 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007964 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007965 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007966 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007967 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007968 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007969 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel2c77fe52014-05-28 15:33:19 +00007970 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7971 DAG.getUNDEF(N->getValueType(1)));
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007972 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007973 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007974 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007976 }
Evan Chenga684cd22007-05-01 00:38:21 +00007977 }
7978 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007979
Chris Lattnere260ed82005-10-10 22:04:48 +00007980 // If this load is directly stored, replace the load value with the stored
7981 // value.
7982 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007983 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007984 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007985 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007986 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7987 if (PrevST->getBasePtr() == Ptr &&
7988 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007989 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007990 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007991 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007992
Evan Cheng43cd9e32010-04-01 06:04:33 +00007993 // Try to infer better alignment information than the load already has.
7994 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007995 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007996 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7997 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007998 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007999 LD->getValueType(0),
8000 Chain, Ptr, LD->getPointerInfo(),
8001 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008002 LD->isVolatile(), LD->isNonTemporal(), Align,
8003 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008004 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8005 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008006 }
8007 }
8008
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008009 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8010 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008011#ifndef NDEBUG
8012 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8013 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8014 UseAA = false;
8015#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008016 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008017 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008018 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008019
Jim Laskey708d0db2006-10-04 16:53:27 +00008020 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008021 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008022 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008023
Jim Laskeyd07be232006-09-25 16:29:54 +00008024 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008025 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008026 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008027 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008028 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008029 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008030 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008031 BetterChain, Ptr, LD->getMemoryVT(),
8032 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008033 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008034
Jim Laskey708d0db2006-10-04 16:53:27 +00008035 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008036 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008037 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008038
Nate Begeman879d8f12009-09-15 00:18:30 +00008039 // Make sure the new and old chains are cleaned up.
8040 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008041
Jim Laskeydcf983c2006-10-13 23:32:28 +00008042 // Replace uses with load result and token factor. Don't add users
8043 // to work list.
8044 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008045 }
8046 }
8047
Evan Cheng357017f2006-11-03 03:06:21 +00008048 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008049 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008050 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008051
Quentin Colombetde0e0622013-10-11 18:29:42 +00008052 // Try to slice up N to more direct loads if the slices are mapped to
8053 // different register banks or pairing can take place.
8054 if (SliceUpLoad(N))
8055 return SDValue(N, 0);
8056
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008057 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008058}
8059
Quentin Colombetde0e0622013-10-11 18:29:42 +00008060namespace {
8061/// \brief Helper structure used to slice a load in smaller loads.
8062/// Basically a slice is obtained from the following sequence:
8063/// Origin = load Ty1, Base
8064/// Shift = srl Ty1 Origin, CstTy Amount
8065/// Inst = trunc Shift to Ty2
8066///
8067/// Then, it will be rewriten into:
8068/// Slice = load SliceTy, Base + SliceOffset
8069/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8070///
8071/// SliceTy is deduced from the number of bits that are actually used to
8072/// build Inst.
8073struct LoadedSlice {
8074 /// \brief Helper structure used to compute the cost of a slice.
8075 struct Cost {
8076 /// Are we optimizing for code size.
8077 bool ForCodeSize;
8078 /// Various cost.
8079 unsigned Loads;
8080 unsigned Truncates;
8081 unsigned CrossRegisterBanksCopies;
8082 unsigned ZExts;
8083 unsigned Shift;
8084
8085 Cost(bool ForCodeSize = false)
8086 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8087 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8088
8089 /// \brief Get the cost of one isolated slice.
8090 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8091 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8092 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8093 EVT TruncType = LS.Inst->getValueType(0);
8094 EVT LoadedType = LS.getLoadedType();
8095 if (TruncType != LoadedType &&
8096 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8097 ZExts = 1;
8098 }
8099
8100 /// \brief Account for slicing gain in the current cost.
8101 /// Slicing provide a few gains like removing a shift or a
8102 /// truncate. This method allows to grow the cost of the original
8103 /// load with the gain from this slice.
8104 void addSliceGain(const LoadedSlice &LS) {
8105 // Each slice saves a truncate.
8106 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8107 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8108 LS.Inst->getOperand(0).getValueType()))
8109 ++Truncates;
8110 // If there is a shift amount, this slice gets rid of it.
8111 if (LS.Shift)
8112 ++Shift;
8113 // If this slice can merge a cross register bank copy, account for it.
8114 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8115 ++CrossRegisterBanksCopies;
8116 }
8117
8118 Cost &operator+=(const Cost &RHS) {
8119 Loads += RHS.Loads;
8120 Truncates += RHS.Truncates;
8121 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8122 ZExts += RHS.ZExts;
8123 Shift += RHS.Shift;
8124 return *this;
8125 }
8126
8127 bool operator==(const Cost &RHS) const {
8128 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8129 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8130 ZExts == RHS.ZExts && Shift == RHS.Shift;
8131 }
8132
8133 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8134
8135 bool operator<(const Cost &RHS) const {
8136 // Assume cross register banks copies are as expensive as loads.
8137 // FIXME: Do we want some more target hooks?
8138 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8139 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8140 // Unless we are optimizing for code size, consider the
8141 // expensive operation first.
8142 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8143 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8144 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8145 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8146 }
8147
8148 bool operator>(const Cost &RHS) const { return RHS < *this; }
8149
8150 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8151
8152 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8153 };
8154 // The last instruction that represent the slice. This should be a
8155 // truncate instruction.
8156 SDNode *Inst;
8157 // The original load instruction.
8158 LoadSDNode *Origin;
8159 // The right shift amount in bits from the original load.
8160 unsigned Shift;
8161 // The DAG from which Origin came from.
8162 // This is used to get some contextual information about legal types, etc.
8163 SelectionDAG *DAG;
8164
Craig Topperc0196b12014-04-14 00:51:57 +00008165 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8166 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008167 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8168
8169 LoadedSlice(const LoadedSlice &LS)
8170 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8171
8172 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8173 /// \return Result is \p BitWidth and has used bits set to 1 and
8174 /// not used bits set to 0.
8175 APInt getUsedBits() const {
8176 // Reproduce the trunc(lshr) sequence:
8177 // - Start from the truncated value.
8178 // - Zero extend to the desired bit width.
8179 // - Shift left.
8180 assert(Origin && "No original load to compare against.");
8181 unsigned BitWidth = Origin->getValueSizeInBits(0);
8182 assert(Inst && "This slice is not bound to an instruction");
8183 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8184 "Extracted slice is bigger than the whole type!");
8185 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8186 UsedBits.setAllBits();
8187 UsedBits = UsedBits.zext(BitWidth);
8188 UsedBits <<= Shift;
8189 return UsedBits;
8190 }
8191
8192 /// \brief Get the size of the slice to be loaded in bytes.
8193 unsigned getLoadedSize() const {
8194 unsigned SliceSize = getUsedBits().countPopulation();
8195 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8196 return SliceSize / 8;
8197 }
8198
8199 /// \brief Get the type that will be loaded for this slice.
8200 /// Note: This may not be the final type for the slice.
8201 EVT getLoadedType() const {
8202 assert(DAG && "Missing context");
8203 LLVMContext &Ctxt = *DAG->getContext();
8204 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8205 }
8206
8207 /// \brief Get the alignment of the load used for this slice.
8208 unsigned getAlignment() const {
8209 unsigned Alignment = Origin->getAlignment();
8210 unsigned Offset = getOffsetFromBase();
8211 if (Offset != 0)
8212 Alignment = MinAlign(Alignment, Alignment + Offset);
8213 return Alignment;
8214 }
8215
8216 /// \brief Check if this slice can be rewritten with legal operations.
8217 bool isLegal() const {
8218 // An invalid slice is not legal.
8219 if (!Origin || !Inst || !DAG)
8220 return false;
8221
8222 // Offsets are for indexed load only, we do not handle that.
8223 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8224 return false;
8225
8226 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8227
8228 // Check that the type is legal.
8229 EVT SliceType = getLoadedType();
8230 if (!TLI.isTypeLegal(SliceType))
8231 return false;
8232
8233 // Check that the load is legal for this type.
8234 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8235 return false;
8236
8237 // Check that the offset can be computed.
8238 // 1. Check its type.
8239 EVT PtrType = Origin->getBasePtr().getValueType();
8240 if (PtrType == MVT::Untyped || PtrType.isExtended())
8241 return false;
8242
8243 // 2. Check that it fits in the immediate.
8244 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8245 return false;
8246
8247 // 3. Check that the computation is legal.
8248 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8249 return false;
8250
8251 // Check that the zext is legal if it needs one.
8252 EVT TruncateType = Inst->getValueType(0);
8253 if (TruncateType != SliceType &&
8254 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8255 return false;
8256
8257 return true;
8258 }
8259
8260 /// \brief Get the offset in bytes of this slice in the original chunk of
8261 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008262 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008263 uint64_t getOffsetFromBase() const {
8264 assert(DAG && "Missing context.");
8265 bool IsBigEndian =
8266 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8267 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8268 uint64_t Offset = Shift / 8;
8269 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8270 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8271 "The size of the original loaded type is not a multiple of a"
8272 " byte.");
8273 // If Offset is bigger than TySizeInBytes, it means we are loading all
8274 // zeros. This should have been optimized before in the process.
8275 assert(TySizeInBytes > Offset &&
8276 "Invalid shift amount for given loaded size");
8277 if (IsBigEndian)
8278 Offset = TySizeInBytes - Offset - getLoadedSize();
8279 return Offset;
8280 }
8281
8282 /// \brief Generate the sequence of instructions to load the slice
8283 /// represented by this object and redirect the uses of this slice to
8284 /// this new sequence of instructions.
8285 /// \pre this->Inst && this->Origin are valid Instructions and this
8286 /// object passed the legal check: LoadedSlice::isLegal returned true.
8287 /// \return The last instruction of the sequence used to load the slice.
8288 SDValue loadSlice() const {
8289 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8290 const SDValue &OldBaseAddr = Origin->getBasePtr();
8291 SDValue BaseAddr = OldBaseAddr;
8292 // Get the offset in that chunk of bytes w.r.t. the endianess.
8293 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8294 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8295 if (Offset) {
8296 // BaseAddr = BaseAddr + Offset.
8297 EVT ArithType = BaseAddr.getValueType();
8298 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8299 DAG->getConstant(Offset, ArithType));
8300 }
8301
8302 // Create the type of the loaded slice according to its size.
8303 EVT SliceType = getLoadedType();
8304
8305 // Create the load for the slice.
8306 SDValue LastInst = DAG->getLoad(
8307 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8308 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8309 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8310 // If the final type is not the same as the loaded type, this means that
8311 // we have to pad with zero. Create a zero extend for that.
8312 EVT FinalType = Inst->getValueType(0);
8313 if (SliceType != FinalType)
8314 LastInst =
8315 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8316 return LastInst;
8317 }
8318
8319 /// \brief Check if this slice can be merged with an expensive cross register
8320 /// bank copy. E.g.,
8321 /// i = load i32
8322 /// f = bitcast i32 i to float
8323 bool canMergeExpensiveCrossRegisterBankCopy() const {
8324 if (!Inst || !Inst->hasOneUse())
8325 return false;
8326 SDNode *Use = *Inst->use_begin();
8327 if (Use->getOpcode() != ISD::BITCAST)
8328 return false;
8329 assert(DAG && "Missing context");
8330 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8331 EVT ResVT = Use->getValueType(0);
8332 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8333 const TargetRegisterClass *ArgRC =
8334 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8335 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8336 return false;
8337
8338 // At this point, we know that we perform a cross-register-bank copy.
8339 // Check if it is expensive.
8340 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8341 // Assume bitcasts are cheap, unless both register classes do not
8342 // explicitly share a common sub class.
8343 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8344 return false;
8345
8346 // Check if it will be merged with the load.
8347 // 1. Check the alignment constraint.
8348 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8349 ResVT.getTypeForEVT(*DAG->getContext()));
8350
8351 if (RequiredAlignment > getAlignment())
8352 return false;
8353
8354 // 2. Check that the load is a legal operation for that type.
8355 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8356 return false;
8357
8358 // 3. Check that we do not have a zext in the way.
8359 if (Inst->getValueType(0) != getLoadedType())
8360 return false;
8361
8362 return true;
8363 }
8364};
8365}
8366
Quentin Colombetde0e0622013-10-11 18:29:42 +00008367/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8368/// \p UsedBits looks like 0..0 1..1 0..0.
8369static bool areUsedBitsDense(const APInt &UsedBits) {
8370 // If all the bits are one, this is dense!
8371 if (UsedBits.isAllOnesValue())
8372 return true;
8373
8374 // Get rid of the unused bits on the right.
8375 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8376 // Get rid of the unused bits on the left.
8377 if (NarrowedUsedBits.countLeadingZeros())
8378 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8379 // Check that the chunk of bits is completely used.
8380 return NarrowedUsedBits.isAllOnesValue();
8381}
8382
8383/// \brief Check whether or not \p First and \p Second are next to each other
8384/// in memory. This means that there is no hole between the bits loaded
8385/// by \p First and the bits loaded by \p Second.
8386static bool areSlicesNextToEachOther(const LoadedSlice &First,
8387 const LoadedSlice &Second) {
8388 assert(First.Origin == Second.Origin && First.Origin &&
8389 "Unable to match different memory origins.");
8390 APInt UsedBits = First.getUsedBits();
8391 assert((UsedBits & Second.getUsedBits()) == 0 &&
8392 "Slices are not supposed to overlap.");
8393 UsedBits |= Second.getUsedBits();
8394 return areUsedBitsDense(UsedBits);
8395}
8396
8397/// \brief Adjust the \p GlobalLSCost according to the target
8398/// paring capabilities and the layout of the slices.
8399/// \pre \p GlobalLSCost should account for at least as many loads as
8400/// there is in the slices in \p LoadedSlices.
8401static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8402 LoadedSlice::Cost &GlobalLSCost) {
8403 unsigned NumberOfSlices = LoadedSlices.size();
8404 // If there is less than 2 elements, no pairing is possible.
8405 if (NumberOfSlices < 2)
8406 return;
8407
8408 // Sort the slices so that elements that are likely to be next to each
8409 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008410 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8411 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8412 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8413 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8414 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008415 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8416 // First (resp. Second) is the first (resp. Second) potentially candidate
8417 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008418 const LoadedSlice *First = nullptr;
8419 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008420 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8421 // Set the beginning of the pair.
8422 First = Second) {
8423
8424 Second = &LoadedSlices[CurrSlice];
8425
8426 // If First is NULL, it means we start a new pair.
8427 // Get to the next slice.
8428 if (!First)
8429 continue;
8430
8431 EVT LoadedType = First->getLoadedType();
8432
8433 // If the types of the slices are different, we cannot pair them.
8434 if (LoadedType != Second->getLoadedType())
8435 continue;
8436
8437 // Check if the target supplies paired loads for this type.
8438 unsigned RequiredAlignment = 0;
8439 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8440 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008441 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008442 continue;
8443 }
8444 // Check if we meet the alignment requirement.
8445 if (RequiredAlignment > First->getAlignment())
8446 continue;
8447
8448 // Check that both loads are next to each other in memory.
8449 if (!areSlicesNextToEachOther(*First, *Second))
8450 continue;
8451
8452 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8453 --GlobalLSCost.Loads;
8454 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008455 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008456 }
8457}
8458
8459/// \brief Check the profitability of all involved LoadedSlice.
8460/// Currently, it is considered profitable if there is exactly two
8461/// involved slices (1) which are (2) next to each other in memory, and
8462/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8463///
8464/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8465/// the elements themselves.
8466///
8467/// FIXME: When the cost model will be mature enough, we can relax
8468/// constraints (1) and (2).
8469static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8470 const APInt &UsedBits, bool ForCodeSize) {
8471 unsigned NumberOfSlices = LoadedSlices.size();
8472 if (StressLoadSlicing)
8473 return NumberOfSlices > 1;
8474
8475 // Check (1).
8476 if (NumberOfSlices != 2)
8477 return false;
8478
8479 // Check (2).
8480 if (!areUsedBitsDense(UsedBits))
8481 return false;
8482
8483 // Check (3).
8484 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8485 // The original code has one big load.
8486 OrigCost.Loads = 1;
8487 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8488 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8489 // Accumulate the cost of all the slices.
8490 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8491 GlobalSlicingCost += SliceCost;
8492
8493 // Account as cost in the original configuration the gain obtained
8494 // with the current slices.
8495 OrigCost.addSliceGain(LS);
8496 }
8497
8498 // If the target supports paired load, adjust the cost accordingly.
8499 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8500 return OrigCost > GlobalSlicingCost;
8501}
8502
8503/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8504/// operations, split it in the various pieces being extracted.
8505///
8506/// This sort of thing is introduced by SROA.
8507/// This slicing takes care not to insert overlapping loads.
8508/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8509bool DAGCombiner::SliceUpLoad(SDNode *N) {
8510 if (Level < AfterLegalizeDAG)
8511 return false;
8512
8513 LoadSDNode *LD = cast<LoadSDNode>(N);
8514 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8515 !LD->getValueType(0).isInteger())
8516 return false;
8517
8518 // Keep track of already used bits to detect overlapping values.
8519 // In that case, we will just abort the transformation.
8520 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8521
8522 SmallVector<LoadedSlice, 4> LoadedSlices;
8523
8524 // Check if this load is used as several smaller chunks of bits.
8525 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8526 // of computation for each trunc.
8527 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8528 UI != UIEnd; ++UI) {
8529 // Skip the uses of the chain.
8530 if (UI.getUse().getResNo() != 0)
8531 continue;
8532
8533 SDNode *User = *UI;
8534 unsigned Shift = 0;
8535
8536 // Check if this is a trunc(lshr).
8537 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8538 isa<ConstantSDNode>(User->getOperand(1))) {
8539 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8540 User = *User->use_begin();
8541 }
8542
8543 // At this point, User is a Truncate, iff we encountered, trunc or
8544 // trunc(lshr).
8545 if (User->getOpcode() != ISD::TRUNCATE)
8546 return false;
8547
8548 // The width of the type must be a power of 2 and greater than 8-bits.
8549 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008550 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008551 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008552 unsigned Width = User->getValueSizeInBits(0);
8553 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8554 return 0;
8555
8556 // Build the slice for this chain of computations.
8557 LoadedSlice LS(User, LD, Shift, &DAG);
8558 APInt CurrentUsedBits = LS.getUsedBits();
8559
8560 // Check if this slice overlaps with another.
8561 if ((CurrentUsedBits & UsedBits) != 0)
8562 return false;
8563 // Update the bits used globally.
8564 UsedBits |= CurrentUsedBits;
8565
8566 // Check if the new slice would be legal.
8567 if (!LS.isLegal())
8568 return false;
8569
8570 // Record the slice.
8571 LoadedSlices.push_back(LS);
8572 }
8573
8574 // Abort slicing if it does not seem to be profitable.
8575 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8576 return false;
8577
8578 ++SlicedLoads;
8579
8580 // Rewrite each chain to use an independent load.
8581 // By construction, each chain can be represented by a unique load.
8582
8583 // Prepare the argument for the new token factor for all the slices.
8584 SmallVector<SDValue, 8> ArgChains;
8585 for (SmallVectorImpl<LoadedSlice>::const_iterator
8586 LSIt = LoadedSlices.begin(),
8587 LSItEnd = LoadedSlices.end();
8588 LSIt != LSItEnd; ++LSIt) {
8589 SDValue SliceInst = LSIt->loadSlice();
8590 CombineTo(LSIt->Inst, SliceInst, true);
8591 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8592 SliceInst = SliceInst.getOperand(0);
8593 assert(SliceInst->getOpcode() == ISD::LOAD &&
8594 "It takes more than a zext to get to the loaded slice!!");
8595 ArgChains.push_back(SliceInst.getValue(1));
8596 }
8597
8598 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008599 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008600 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8601 return true;
8602}
8603
Chris Lattner4041ab62010-04-15 04:48:01 +00008604/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8605/// load is having specific bytes cleared out. If so, return the byte size
8606/// being masked out and the shift amount.
8607static std::pair<unsigned, unsigned>
8608CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8609 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008610
Chris Lattner4041ab62010-04-15 04:48:01 +00008611 // Check for the structure we're looking for.
8612 if (V->getOpcode() != ISD::AND ||
8613 !isa<ConstantSDNode>(V->getOperand(1)) ||
8614 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8615 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008616
Chris Lattner3245afd2010-04-15 06:10:49 +00008617 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008618 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008619 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008620
Chris Lattner3245afd2010-04-15 06:10:49 +00008621 // The store should be chained directly to the load or be an operand of a
8622 // tokenfactor.
8623 if (LD == Chain.getNode())
8624 ; // ok.
8625 else if (Chain->getOpcode() != ISD::TokenFactor)
8626 return Result; // Fail.
8627 else {
8628 bool isOk = false;
8629 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8630 if (Chain->getOperand(i).getNode() == LD) {
8631 isOk = true;
8632 break;
8633 }
8634 if (!isOk) return Result;
8635 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008636
Chris Lattner4041ab62010-04-15 04:48:01 +00008637 // This only handles simple types.
8638 if (V.getValueType() != MVT::i16 &&
8639 V.getValueType() != MVT::i32 &&
8640 V.getValueType() != MVT::i64)
8641 return Result;
8642
8643 // Check the constant mask. Invert it so that the bits being masked out are
8644 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8645 // follow the sign bit for uniformity.
8646 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008647 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008648 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008649 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008650 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8651 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008652
Chris Lattner4041ab62010-04-15 04:48:01 +00008653 // See if we have a continuous run of bits. If so, we have 0*1+0*
8654 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8655 return Result;
8656
8657 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8658 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8659 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008660
Chris Lattner4041ab62010-04-15 04:48:01 +00008661 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8662 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008663 case 1:
8664 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008665 case 4: break;
8666 default: return Result; // All one mask, or 5-byte mask.
8667 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008668
Chris Lattner4041ab62010-04-15 04:48:01 +00008669 // Verify that the first bit starts at a multiple of mask so that the access
8670 // is aligned the same as the access width.
8671 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008672
Chris Lattner4041ab62010-04-15 04:48:01 +00008673 Result.first = MaskedBytes;
8674 Result.second = NotMaskTZ/8;
8675 return Result;
8676}
8677
8678
8679/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8680/// provides a value as specified by MaskInfo. If so, replace the specified
8681/// store with a narrower store of truncated IVal.
8682static SDNode *
8683ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8684 SDValue IVal, StoreSDNode *St,
8685 DAGCombiner *DC) {
8686 unsigned NumBytes = MaskInfo.first;
8687 unsigned ByteShift = MaskInfo.second;
8688 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008689
Chris Lattner4041ab62010-04-15 04:48:01 +00008690 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8691 // that uses this. If not, this is not a replacement.
8692 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8693 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008694 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008695
Chris Lattner4041ab62010-04-15 04:48:01 +00008696 // Check that it is legal on the target to do this. It is legal if the new
8697 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8698 // legalization.
8699 MVT VT = MVT::getIntegerVT(NumBytes*8);
8700 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008701 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008702
Chris Lattner4041ab62010-04-15 04:48:01 +00008703 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8704 // shifted by ByteShift and truncated down to NumBytes.
8705 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008706 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008707 DAG.getConstant(ByteShift*8,
8708 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008709
8710 // Figure out the offset for the store and the alignment of the access.
8711 unsigned StOffset;
8712 unsigned NewAlign = St->getAlignment();
8713
8714 if (DAG.getTargetLoweringInfo().isLittleEndian())
8715 StOffset = ByteShift;
8716 else
8717 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008718
Chris Lattner4041ab62010-04-15 04:48:01 +00008719 SDValue Ptr = St->getBasePtr();
8720 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008721 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008722 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8723 NewAlign = MinAlign(NewAlign, StOffset);
8724 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008725
Chris Lattner4041ab62010-04-15 04:48:01 +00008726 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008727 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008728
Chris Lattner4041ab62010-04-15 04:48:01 +00008729 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008730 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008731 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008732 false, false, NewAlign).getNode();
8733}
8734
Evan Chenga9cda8a2009-05-28 00:35:15 +00008735
8736/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8737/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8738/// of the loaded bits, try narrowing the load and store if it would end up
8739/// being a win for performance or code size.
8740SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8741 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008742 if (ST->isVolatile())
8743 return SDValue();
8744
Evan Chenga9cda8a2009-05-28 00:35:15 +00008745 SDValue Chain = ST->getChain();
8746 SDValue Value = ST->getValue();
8747 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008748 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008749
8750 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008751 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008752
8753 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008754
Chris Lattner4041ab62010-04-15 04:48:01 +00008755 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8756 // is a byte mask indicating a consecutive number of bytes, check to see if
8757 // Y is known to provide just those bytes. If so, we try to replace the
8758 // load + replace + store sequence with a single (narrower) store, which makes
8759 // the load dead.
8760 if (Opc == ISD::OR) {
8761 std::pair<unsigned, unsigned> MaskedLoad;
8762 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8763 if (MaskedLoad.first)
8764 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8765 Value.getOperand(1), ST,this))
8766 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008767
Chris Lattner4041ab62010-04-15 04:48:01 +00008768 // Or is commutative, so try swapping X and Y.
8769 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8770 if (MaskedLoad.first)
8771 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8772 Value.getOperand(0), ST,this))
8773 return SDValue(NewST, 0);
8774 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008775
Evan Chenga9cda8a2009-05-28 00:35:15 +00008776 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8777 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008778 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008779
8780 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008781 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8782 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008783 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008784 if (LD->getBasePtr() != Ptr ||
8785 LD->getPointerInfo().getAddrSpace() !=
8786 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008787 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008788
8789 // Find the type to narrow it the load / op / store to.
8790 SDValue N1 = Value.getOperand(1);
8791 unsigned BitWidth = N1.getValueSizeInBits();
8792 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8793 if (Opc == ISD::AND)
8794 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008795 if (Imm == 0 || Imm.isAllOnesValue())
8796 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008797 unsigned ShAmt = Imm.countTrailingZeros();
8798 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8799 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008800 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008801 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008802 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008803 TLI.isNarrowingProfitable(VT, NewVT))) {
8804 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008805 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008806 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008807 if (NewBW >= BitWidth)
8808 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008809
8810 // If the lsb changed does not start at the type bitwidth boundary,
8811 // start at the previous one.
8812 if (ShAmt % NewBW)
8813 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008814 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8815 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008816 if ((Imm & Mask) == Imm) {
8817 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8818 if (Opc == ISD::AND)
8819 NewImm ^= APInt::getAllOnesValue(NewBW);
8820 uint64_t PtrOff = ShAmt / 8;
8821 // For big endian targets, we need to adjust the offset to the pointer to
8822 // load the correct bytes.
8823 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008824 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008825
8826 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008827 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008828 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008829 return SDValue();
8830
Andrew Trickef9de2a2013-05-25 02:42:55 +00008831 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008832 Ptr.getValueType(), Ptr,
8833 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008834 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008835 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008836 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008837 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008838 LD->isInvariant(), NewAlign,
8839 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008840 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008841 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008842 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008843 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008844 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008845 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008846
8847 AddToWorkList(NewPtr.getNode());
8848 AddToWorkList(NewLD.getNode());
8849 AddToWorkList(NewVal.getNode());
8850 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008851 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008852 ++OpsNarrowed;
8853 return NewST;
8854 }
8855 }
8856
Evan Cheng6673ff02009-05-28 18:41:02 +00008857 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008858}
8859
Evan Chengd42641c2011-02-02 01:06:55 +00008860/// TransformFPLoadStorePair - For a given floating point load / store pair,
8861/// if the load value isn't used by any other operations, then consider
8862/// transforming the pair to integer load / store operations if the target
8863/// deems the transformation profitable.
8864SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8865 StoreSDNode *ST = cast<StoreSDNode>(N);
8866 SDValue Chain = ST->getChain();
8867 SDValue Value = ST->getValue();
8868 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8869 Value.hasOneUse() &&
8870 Chain == SDValue(Value.getNode(), 1)) {
8871 LoadSDNode *LD = cast<LoadSDNode>(Value);
8872 EVT VT = LD->getMemoryVT();
8873 if (!VT.isFloatingPoint() ||
8874 VT != ST->getMemoryVT() ||
8875 LD->isNonTemporal() ||
8876 ST->isNonTemporal() ||
8877 LD->getPointerInfo().getAddrSpace() != 0 ||
8878 ST->getPointerInfo().getAddrSpace() != 0)
8879 return SDValue();
8880
8881 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8882 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8883 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8884 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8885 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8886 return SDValue();
8887
8888 unsigned LDAlign = LD->getAlignment();
8889 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008890 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008891 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008892 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8893 return SDValue();
8894
Andrew Trickef9de2a2013-05-25 02:42:55 +00008895 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008896 LD->getChain(), LD->getBasePtr(),
8897 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008898 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008899
Andrew Trickef9de2a2013-05-25 02:42:55 +00008900 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008901 NewLD, ST->getBasePtr(),
8902 ST->getPointerInfo(),
8903 false, false, STAlign);
8904
8905 AddToWorkList(NewLD.getNode());
8906 AddToWorkList(NewST.getNode());
8907 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008908 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008909 ++LdStFP2Int;
8910 return NewST;
8911 }
8912
8913 return SDValue();
8914}
8915
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008916/// Helper struct to parse and store a memory address as base + index + offset.
8917/// We ignore sign extensions when it is safe to do so.
8918/// The following two expressions are not equivalent. To differentiate we need
8919/// to store whether there was a sign extension involved in the index
8920/// computation.
8921/// (load (i64 add (i64 copyfromreg %c)
8922/// (i64 signextend (add (i8 load %index)
8923/// (i8 1))))
8924/// vs
8925///
8926/// (load (i64 add (i64 copyfromreg %c)
8927/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8928/// (i32 1)))))
8929struct BaseIndexOffset {
8930 SDValue Base;
8931 SDValue Index;
8932 int64_t Offset;
8933 bool IsIndexSignExt;
8934
8935 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8936
8937 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8938 bool IsIndexSignExt) :
8939 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8940
8941 bool equalBaseIndex(const BaseIndexOffset &Other) {
8942 return Other.Base == Base && Other.Index == Index &&
8943 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008944 }
8945
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008946 /// Parses tree in Ptr for base, index, offset addresses.
8947 static BaseIndexOffset match(SDValue Ptr) {
8948 bool IsIndexSignExt = false;
8949
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008950 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8951 // instruction, then it could be just the BASE or everything else we don't
8952 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008953 if (Ptr->getOpcode() != ISD::ADD)
8954 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8955
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008956 // We know that we have at least an ADD instruction. Try to pattern match
8957 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008958 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8959 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8960 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8961 IsIndexSignExt);
8962 }
8963
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008964 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008965 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008966 // (i64 add (i64 %array_ptr)
8967 // (i64 mul (i64 %induction_var)
8968 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008969 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008970 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008971
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008972 // Look at Base + Index + Offset cases.
8973 SDValue Base = Ptr->getOperand(0);
8974 SDValue IndexOffset = Ptr->getOperand(1);
8975
8976 // Skip signextends.
8977 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8978 IndexOffset = IndexOffset->getOperand(0);
8979 IsIndexSignExt = true;
8980 }
8981
8982 // Either the case of Base + Index (no offset) or something else.
8983 if (IndexOffset->getOpcode() != ISD::ADD)
8984 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8985
8986 // Now we have the case of Base + Index + offset.
8987 SDValue Index = IndexOffset->getOperand(0);
8988 SDValue Offset = IndexOffset->getOperand(1);
8989
8990 if (!isa<ConstantSDNode>(Offset))
8991 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8992
8993 // Ignore signextends.
8994 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8995 Index = Index->getOperand(0);
8996 IsIndexSignExt = true;
8997 } else IsIndexSignExt = false;
8998
8999 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9000 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9001 }
9002};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009003
9004/// Holds a pointer to an LSBaseSDNode as well as information on where it
9005/// is located in a sequence of memory operations connected by a chain.
9006struct MemOpLink {
9007 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9008 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9009 // Ptr to the mem node.
9010 LSBaseSDNode *MemNode;
9011 // Offset from the base ptr.
9012 int64_t OffsetFromBase;
9013 // What is the sequence number of this mem node.
9014 // Lowest mem operand in the DAG starts at zero.
9015 unsigned SequenceNum;
9016};
9017
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009018bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9019 EVT MemVT = St->getMemoryVT();
9020 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009021 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9022 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009023
9024 // Don't merge vectors into wider inputs.
9025 if (MemVT.isVector() || !MemVT.isSimple())
9026 return false;
9027
9028 // Perform an early exit check. Do not bother looking at stored values that
9029 // are not constants or loads.
9030 SDValue StoredVal = St->getValue();
9031 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9032 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9033 !IsLoadSrc)
9034 return false;
9035
9036 // Only look at ends of store sequences.
9037 SDValue Chain = SDValue(St, 1);
9038 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9039 return false;
9040
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009041 // This holds the base pointer, index, and the offset in bytes from the base
9042 // pointer.
9043 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009044
9045 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009046 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009047 return false;
9048
9049 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009050 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009051 return false;
9052
Nadav Rotem307d7672012-11-29 00:00:08 +00009053 // Save the LoadSDNodes that we find in the chain.
9054 // We need to make sure that these nodes do not interfere with
9055 // any of the store nodes.
9056 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9057
9058 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009059 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009060
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009061 // Walk up the chain and look for nodes with offsets from the same
9062 // base pointer. Stop when reaching an instruction with a different kind
9063 // or instruction which has a different base pointer.
9064 unsigned Seq = 0;
9065 StoreSDNode *Index = St;
9066 while (Index) {
9067 // If the chain has more than one use, then we can't reorder the mem ops.
9068 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9069 break;
9070
9071 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009072 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009073
9074 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009075 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009076 break;
9077
9078 // Check that the alignment is the same.
9079 if (Index->getAlignment() != St->getAlignment())
9080 break;
9081
9082 // The memory operands must not be volatile.
9083 if (Index->isVolatile() || Index->isIndexed())
9084 break;
9085
9086 // No truncation.
9087 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9088 if (St->isTruncatingStore())
9089 break;
9090
9091 // The stored memory type must be the same.
9092 if (Index->getMemoryVT() != MemVT)
9093 break;
9094
9095 // We do not allow unaligned stores because we want to prevent overriding
9096 // stores.
9097 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9098 break;
9099
9100 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009101 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009102
Nadav Rotem307d7672012-11-29 00:00:08 +00009103 // Find the next memory operand in the chain. If the next operand in the
9104 // chain is a store then move up and continue the scan with the next
9105 // memory operand. If the next operand is a load save it and use alias
9106 // information to check if it interferes with anything.
9107 SDNode *NextInChain = Index->getChain().getNode();
9108 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009109 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009110 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009111 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009112 break;
9113 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009114 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009115 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009116 break;
9117 }
9118
Nadav Rotem307d7672012-11-29 00:00:08 +00009119 // Save the load node for later. Continue the scan.
9120 AliasLoadNodes.push_back(Ldn);
9121 NextInChain = Ldn->getChain().getNode();
9122 continue;
9123 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009124 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009125 break;
9126 }
9127 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009128 }
9129
9130 // Check if there is anything to merge.
9131 if (StoreNodes.size() < 2)
9132 return false;
9133
9134 // Sort the memory operands according to their distance from the base pointer.
9135 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009136 [](MemOpLink LHS, MemOpLink RHS) {
9137 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9138 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9139 LHS.SequenceNum > RHS.SequenceNum);
9140 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009141
9142 // Scan the memory operations on the chain and find the first non-consecutive
9143 // store memory address.
9144 unsigned LastConsecutiveStore = 0;
9145 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009146 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9147
9148 // Check that the addresses are consecutive starting from the second
9149 // element in the list of stores.
9150 if (i > 0) {
9151 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9152 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9153 break;
9154 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009155
Nadav Rotem307d7672012-11-29 00:00:08 +00009156 bool Alias = false;
9157 // Check if this store interferes with any of the loads that we found.
9158 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9159 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9160 Alias = true;
9161 break;
9162 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009163 // We found a load that alias with this store. Stop the sequence.
9164 if (Alias)
9165 break;
9166
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009167 // Mark this node as useful.
9168 LastConsecutiveStore = i;
9169 }
9170
9171 // The node with the lowest store address.
9172 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9173
9174 // Store the constants into memory as one consecutive store.
9175 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009176 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009177 unsigned LastLegalVectorType = 0;
9178 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009179 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9180 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9181 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009182
9183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009184 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009185 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009186 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009187 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009188 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009189 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009190 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009191
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009192 // Find a legal type for the constant store.
9193 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9194 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9195 if (TLI.isTypeLegal(StoreTy))
9196 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009197 // Or check whether a truncstore is legal.
9198 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9199 TargetLowering::TypePromoteInteger) {
9200 EVT LegalizedStoredValueTy =
9201 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9202 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9203 LastLegalType = i+1;
9204 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009205
9206 // Find a legal type for the vector store.
9207 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9208 if (TLI.isTypeLegal(Ty))
9209 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009210 }
9211
Bob Wilson3365b802012-12-20 01:36:20 +00009212 // We only use vectors if the constant is known to be zero and the
9213 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009214 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009215 LastLegalVectorType = 0;
9216
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009217 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009218 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009219 return false;
9220
Nadav Rotem495b1a42013-02-14 18:28:52 +00009221 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009222 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9223
9224 // Make sure we have something to merge.
9225 if (NumElem < 2)
9226 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009227
9228 unsigned EarliestNodeUsed = 0;
9229 for (unsigned i=0; i < NumElem; ++i) {
9230 // Find a chain for the new wide-store operand. Notice that some
9231 // of the store nodes that we found may not be selected for inclusion
9232 // in the wide store. The chain we use needs to be the chain of the
9233 // earliest store node which is *used* and replaced by the wide store.
9234 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9235 EarliestNodeUsed = i;
9236 }
9237
9238 // The earliest Node in the DAG.
9239 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009240 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009241
Nadav Rotemb27777f2012-10-04 22:35:15 +00009242 SDValue StoredVal;
9243 if (UseVector) {
9244 // Find a legal type for the vector store.
9245 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9246 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9247 StoredVal = DAG.getConstant(0, Ty);
9248 } else {
9249 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9250 APInt StoreInt(StoreBW, 0);
9251
9252 // Construct a single integer constant which is made of the smaller
9253 // constant inputs.
9254 bool IsLE = TLI.isLittleEndian();
9255 for (unsigned i = 0; i < NumElem ; ++i) {
9256 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9257 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9258 SDValue Val = St->getValue();
9259 StoreInt<<=ElementSizeBytes*8;
9260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9261 StoreInt|=C->getAPIntValue().zext(StoreBW);
9262 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9263 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9264 } else {
9265 assert(false && "Invalid constant element type");
9266 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009267 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009268
9269 // Create the new Load and Store operations.
9270 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9271 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009272 }
9273
Nadav Rotemb27777f2012-10-04 22:35:15 +00009274 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009275 FirstInChain->getBasePtr(),
9276 FirstInChain->getPointerInfo(),
9277 false, false,
9278 FirstInChain->getAlignment());
9279
9280 // Replace the first store with the new store
9281 CombineTo(EarliestOp, NewStore);
9282 // Erase all other stores.
9283 for (unsigned i = 0; i < NumElem ; ++i) {
9284 if (StoreNodes[i].MemNode == EarliestOp)
9285 continue;
9286 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009287 // ReplaceAllUsesWith will replace all uses that existed when it was
9288 // called, but graph optimizations may cause new ones to appear. For
9289 // example, the case in pr14333 looks like
9290 //
9291 // St's chain -> St -> another store -> X
9292 //
9293 // And the only difference from St to the other store is the chain.
9294 // When we change it's chain to be St's chain they become identical,
9295 // get CSEed and the net result is that X is now a use of St.
9296 // Since we know that St is redundant, just iterate.
9297 while (!St->use_empty())
9298 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009299 removeFromWorkList(St);
9300 DAG.DeleteNode(St);
9301 }
9302
9303 return true;
9304 }
9305
9306 // Below we handle the case of multiple consecutive stores that
9307 // come from multiple consecutive loads. We merge them into a single
9308 // wide load and a single wide store.
9309
9310 // Look for load nodes which are used by the stored values.
9311 SmallVector<MemOpLink, 8> LoadNodes;
9312
9313 // Find acceptable loads. Loads need to have the same chain (token factor),
9314 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009315 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009316 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9317 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9318 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9319 if (!Ld) break;
9320
9321 // Loads must only have one use.
9322 if (!Ld->hasNUsesOfValue(1, 0))
9323 break;
9324
9325 // Check that the alignment is the same as the stores.
9326 if (Ld->getAlignment() != St->getAlignment())
9327 break;
9328
9329 // The memory operands must not be volatile.
9330 if (Ld->isVolatile() || Ld->isIndexed())
9331 break;
9332
9333 // We do not accept ext loads.
9334 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9335 break;
9336
9337 // The stored memory type must be the same.
9338 if (Ld->getMemoryVT() != MemVT)
9339 break;
9340
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009341 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009342 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009343 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009344 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009345 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009346 break;
9347 } else {
9348 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009349 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009350 }
9351
9352 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009353 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009354 }
9355
9356 if (LoadNodes.size() < 2)
9357 return false;
9358
9359 // Scan the memory operations on the chain and find the first non-consecutive
9360 // load memory address. These variables hold the index in the store node
9361 // array.
9362 unsigned LastConsecutiveLoad = 0;
9363 // This variable refers to the size and not index in the array.
9364 unsigned LastLegalVectorType = 0;
9365 unsigned LastLegalIntegerType = 0;
9366 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009367 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9368 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9369 // All loads much share the same chain.
9370 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9371 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009372
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009373 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9374 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9375 break;
9376 LastConsecutiveLoad = i;
9377
9378 // Find a legal type for the vector store.
9379 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9380 if (TLI.isTypeLegal(StoreTy))
9381 LastLegalVectorType = i + 1;
9382
9383 // Find a legal type for the integer store.
9384 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9385 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9386 if (TLI.isTypeLegal(StoreTy))
9387 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009388 // Or check whether a truncstore and extload is legal.
9389 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9390 TargetLowering::TypePromoteInteger) {
9391 EVT LegalizedStoredValueTy =
9392 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9393 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9394 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9395 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9396 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9397 LastLegalIntegerType = i+1;
9398 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009399 }
9400
9401 // Only use vector types if the vector type is larger than the integer type.
9402 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009403 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009404 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9405
9406 // We add +1 here because the LastXXX variables refer to location while
9407 // the NumElem refers to array/index size.
9408 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9409 NumElem = std::min(LastLegalType, NumElem);
9410
9411 if (NumElem < 2)
9412 return false;
9413
9414 // The earliest Node in the DAG.
9415 unsigned EarliestNodeUsed = 0;
9416 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9417 for (unsigned i=1; i<NumElem; ++i) {
9418 // Find a chain for the new wide-store operand. Notice that some
9419 // of the store nodes that we found may not be selected for inclusion
9420 // in the wide store. The chain we use needs to be the chain of the
9421 // earliest store node which is *used* and replaced by the wide store.
9422 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9423 EarliestNodeUsed = i;
9424 }
9425
9426 // Find if it is better to use vectors or integers to load and store
9427 // to memory.
9428 EVT JointMemOpVT;
9429 if (UseVectorTy) {
9430 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9431 } else {
9432 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9433 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9434 }
9435
Andrew Trickef9de2a2013-05-25 02:42:55 +00009436 SDLoc LoadDL(LoadNodes[0].MemNode);
9437 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009438
9439 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9440 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9441 FirstLoad->getChain(),
9442 FirstLoad->getBasePtr(),
9443 FirstLoad->getPointerInfo(),
9444 false, false, false,
9445 FirstLoad->getAlignment());
9446
9447 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9448 FirstInChain->getBasePtr(),
9449 FirstInChain->getPointerInfo(), false, false,
9450 FirstInChain->getAlignment());
9451
Nadav Rotemac920662012-10-03 19:30:31 +00009452 // Replace one of the loads with the new load.
9453 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9454 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9455 SDValue(NewLoad.getNode(), 1));
9456
9457 // Remove the rest of the load chains.
9458 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009459 // Replace all chain users of the old load nodes with the chain of the new
9460 // load node.
9461 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009462 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9463 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009464
Nadav Rotemac920662012-10-03 19:30:31 +00009465 // Replace the first store with the new store.
9466 CombineTo(EarliestOp, NewStore);
9467 // Erase all other stores.
9468 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009469 // Remove all Store nodes.
9470 if (StoreNodes[i].MemNode == EarliestOp)
9471 continue;
9472 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9473 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9474 removeFromWorkList(St);
9475 DAG.DeleteNode(St);
9476 }
9477
9478 return true;
9479}
9480
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009481SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009482 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009483 SDValue Chain = ST->getChain();
9484 SDValue Value = ST->getValue();
9485 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009486
Evan Chenga4cf58a2007-05-07 21:27:48 +00009487 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009488 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009489 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009490 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009491 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009492 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009493 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009494 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009495 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009496 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009497 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009498 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009499 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009500 ST->isNonTemporal(), OrigAlign,
9501 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009502 }
Owen Andersona5192842011-04-14 17:30:49 +00009503
Chris Lattner41c80e82011-04-09 02:32:02 +00009504 // Turn 'store undef, Ptr' -> nothing.
9505 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9506 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009507
Nate Begeman8e20c762006-12-11 02:23:46 +00009508 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009509 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009510 // NOTE: If the original store is volatile, this transform must not increase
9511 // the number of stores. For example, on x86-32 an f64 can be stored in one
9512 // processor operation but an i64 (which is not legal) requires two. So the
9513 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009514 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009515 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009516 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009517 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009518 case MVT::f16: // We don't do this for these yet.
9519 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009520 case MVT::f128:
9521 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009522 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009523 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009524 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009525 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009526 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009527 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009528 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009529 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009530 }
9531 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009532 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009533 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009534 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009535 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009536 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009537 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009538 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009539 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009540 }
Owen Andersona5192842011-04-14 17:30:49 +00009541
Chris Lattner41c80e82011-04-09 02:32:02 +00009542 if (!ST->isVolatile() &&
9543 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009544 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009545 // argument passing. Since this is so common, custom legalize the
9546 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009547 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009548 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9549 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009550 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009551
Dan Gohman2af30632007-07-09 22:18:38 +00009552 unsigned Alignment = ST->getAlignment();
9553 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009554 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009555 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009556
Andrew Trickef9de2a2013-05-25 02:42:55 +00009557 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009558 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009559 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009560 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009561 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009562 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009563 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009564 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009565 Ptr, ST->getPointerInfo().getWithOffset(4),
9566 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009567 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009568 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009569 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009570 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009571
Chris Lattnerb7524b62006-12-12 04:16:14 +00009572 break;
Evan Cheng21836982006-12-11 17:25:19 +00009573 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009574 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009575 }
9576
Evan Cheng43cd9e32010-04-01 06:04:33 +00009577 // Try to infer better alignment information than the store already has.
9578 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009579 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9580 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009581 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009582 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009583 ST->isVolatile(), ST->isNonTemporal(), Align,
9584 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009585 }
9586 }
9587
Evan Chengd42641c2011-02-02 01:06:55 +00009588 // Try transforming a pair floating point load / store ops to integer
9589 // load / store ops.
9590 SDValue NewST = TransformFPLoadStorePair(N);
9591 if (NewST.getNode())
9592 return NewST;
9593
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009594 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9595 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009596#ifndef NDEBUG
9597 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9598 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9599 UseAA = false;
9600#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009601 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009602 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009603 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009604
Jim Laskey708d0db2006-10-04 16:53:27 +00009605 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009606 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009607 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009608
9609 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009610 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009611 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009612 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009613 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009614 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009615 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009616 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009617
Jim Laskeyd07be232006-09-25 16:29:54 +00009618 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009619 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009620 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009621
Nate Begeman879d8f12009-09-15 00:18:30 +00009622 // Make sure the new and old chains are cleaned up.
9623 AddToWorkList(Token.getNode());
9624
Jim Laskeydcf983c2006-10-13 23:32:28 +00009625 // Don't add users to work list.
9626 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009627 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009628 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009629
Evan Cheng33157702006-11-05 09:31:14 +00009630 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009631 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009632 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009633
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009634 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009635 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009636 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009637 // See if we can simplify the input to this truncstore with knowledge that
9638 // only the low bits are being used. For example:
9639 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009640 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009641 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009642 APInt::getLowBitsSet(
9643 Value.getValueType().getScalarType().getSizeInBits(),
9644 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009645 AddToWorkList(Value.getNode());
9646 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009647 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009648 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009649
Chris Lattnerf47e3062007-10-13 06:58:48 +00009650 // Otherwise, see if we can simplify the operation with
9651 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009652 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009653 APInt::getLowBitsSet(
9654 Value.getValueType().getScalarType().getSizeInBits(),
9655 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009656 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009657 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009658
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009659 // If this is a load followed by a store to the same location, then the store
9660 // is dead/noop.
9661 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009662 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009663 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009664 // There can't be any side effects between the load and store, such as
9665 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009666 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009667 // The store is dead, remove it.
9668 return Chain;
9669 }
9670 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009671
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009672 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9673 // truncating store. We can do this even if this is already a truncstore.
9674 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009675 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009676 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009677 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009678 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009679 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009680 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009681
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009682 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009683 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009684 if (!LegalTypes) {
9685 bool EverChanged = false;
9686
9687 do {
9688 // There can be multiple store sequences on the same chain.
9689 // Keep trying to merge store sequences until we are unable to do so
9690 // or until we merge the last store on the chain.
9691 bool Changed = MergeConsecutiveStores(ST);
9692 EverChanged |= Changed;
9693 if (!Changed) break;
9694 } while (ST->getOpcode() != ISD::DELETED_NODE);
9695
9696 if (EverChanged)
9697 return SDValue(N, 0);
9698 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009699
Evan Chenga9cda8a2009-05-28 00:35:15 +00009700 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009701}
9702
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009703SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9704 SDValue InVec = N->getOperand(0);
9705 SDValue InVal = N->getOperand(1);
9706 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009707 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009708
Bob Wilson42603952010-05-19 23:42:58 +00009709 // If the inserted element is an UNDEF, just use the input vector.
9710 if (InVal.getOpcode() == ISD::UNDEF)
9711 return InVec;
9712
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009713 EVT VT = InVec.getValueType();
9714
Owen Andersonb2c80da2011-02-25 21:41:48 +00009715 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009716 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9717 return SDValue();
9718
Eli Friedmanb7910b72011-09-09 21:04:06 +00009719 // Check that we know which element is being inserted
9720 if (!isa<ConstantSDNode>(EltNo))
9721 return SDValue();
9722 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009723
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009724 // Canonicalize insert_vector_elt dag nodes.
9725 // Example:
9726 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9727 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9728 //
9729 // Do this only if the child insert_vector node has one use; also
9730 // do this only if indices are both constants and Idx1 < Idx0.
9731 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9732 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9733 unsigned OtherElt =
9734 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9735 if (Elt < OtherElt) {
9736 // Swap nodes.
9737 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9738 InVec.getOperand(0), InVal, EltNo);
9739 AddToWorkList(NewOp.getNode());
9740 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9741 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9742 }
9743 }
9744
Eli Friedmanb7910b72011-09-09 21:04:06 +00009745 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9746 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9747 // vector elements.
9748 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009749 // Do not combine these two vectors if the output vector will not replace
9750 // the input vector.
9751 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009752 Ops.append(InVec.getNode()->op_begin(),
9753 InVec.getNode()->op_end());
9754 } else if (InVec.getOpcode() == ISD::UNDEF) {
9755 unsigned NElts = VT.getVectorNumElements();
9756 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9757 } else {
9758 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009759 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009760
9761 // Insert the element
9762 if (Elt < Ops.size()) {
9763 // All the operands of BUILD_VECTOR must have the same type;
9764 // we enforce that here.
9765 EVT OpVT = Ops[0].getValueType();
9766 if (InVal.getValueType() != OpVT)
9767 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9768 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9769 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9770 Ops[Elt] = InVal;
9771 }
9772
9773 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009774 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009775}
9776
Michael J. Spencerf375d802014-05-29 01:42:45 +00009777SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9778 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9779 EVT ResultVT = EVE->getValueType(0);
9780 EVT VecEltVT = InVecVT.getVectorElementType();
9781 unsigned Align = OriginalLoad->getAlignment();
9782 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9783 VecEltVT.getTypeForEVT(*DAG.getContext()));
9784
9785 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9786 return SDValue();
9787
9788 Align = NewAlign;
9789
9790 SDValue NewPtr = OriginalLoad->getBasePtr();
9791 SDValue Offset;
9792 EVT PtrType = NewPtr.getValueType();
9793 MachinePointerInfo MPI;
9794 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9795 int Elt = ConstEltNo->getZExtValue();
9796 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9797 if (TLI.isBigEndian())
9798 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9799 Offset = DAG.getConstant(PtrOff, PtrType);
9800 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9801 } else {
9802 Offset = DAG.getNode(
9803 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9804 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9805 if (TLI.isBigEndian())
9806 Offset = DAG.getNode(
9807 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9808 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9809 MPI = OriginalLoad->getPointerInfo();
9810 }
9811 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9812
9813 // The replacement we need to do here is a little tricky: we need to
9814 // replace an extractelement of a load with a load.
9815 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9816 // Note that this replacement assumes that the extractvalue is the only
9817 // use of the load; that's okay because we don't want to perform this
9818 // transformation in other cases anyway.
9819 SDValue Load;
9820 SDValue Chain;
9821 if (ResultVT.bitsGT(VecEltVT)) {
9822 // If the result type of vextract is wider than the load, then issue an
9823 // extending load instead.
9824 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9825 ? ISD::ZEXTLOAD
9826 : ISD::EXTLOAD;
9827 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(),
9828 NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(),
9829 OriginalLoad->isNonTemporal(), Align,
9830 OriginalLoad->getTBAAInfo());
9831 Chain = Load.getValue(1);
9832 } else {
9833 Load = DAG.getLoad(
9834 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9835 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9836 OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo());
9837 Chain = Load.getValue(1);
9838 if (ResultVT.bitsLT(VecEltVT))
9839 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9840 else
9841 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9842 }
9843 WorkListRemover DeadNodes(*this);
9844 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9845 SDValue To[] = { Load, Chain };
9846 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9847 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9848 // worklist explicitly as well.
9849 AddToWorkList(Load.getNode());
9850 AddUsersToWorkList(Load.getNode()); // Add users too
9851 // Make sure to revisit this node to clean it up; it will usually be dead.
9852 AddToWorkList(EVE);
9853 ++OpsNarrowed;
9854 return SDValue(EVE, 0);
9855}
9856
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009857SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009858 // (vextract (scalar_to_vector val, 0) -> val
9859 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009860 EVT VT = InVec.getValueType();
9861 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009862
Duncan Sands6be291a2011-05-09 08:03:33 +00009863 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9864 // Check if the result type doesn't match the inserted element type. A
9865 // SCALAR_TO_VECTOR may truncate the inserted element and the
9866 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9867 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009868 if (InOp.getValueType() != NVT) {
9869 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009870 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009871 }
9872 return InOp;
9873 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009874
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009875 SDValue EltNo = N->getOperand(1);
9876 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9877
9878 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9879 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009880 // we may introduce new vector instructions which are not backed by TD
9881 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009882 // without using extract_subvector. However, if we can find an underlying
9883 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009884 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009885 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009886 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9887 int NumElem = VT.getVectorNumElements();
9888 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9889 // Find the new index to extract from.
9890 int OrigElt = SVOp->getMaskElt(Elt);
9891
9892 // Extracting an undef index is undef.
9893 if (OrigElt == -1)
9894 return DAG.getUNDEF(NVT);
9895
9896 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009897 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009898 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009899 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009900 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009901 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009902 OrigElt -= NumElem;
9903 }
9904
Hal Finkel02807592014-03-31 11:43:19 +00009905 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9906 SDValue InOp = SVInVec.getOperand(OrigElt);
9907 if (InOp.getValueType() != NVT) {
9908 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9909 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9910 }
9911
9912 return InOp;
9913 }
9914
9915 // FIXME: We should handle recursing on other vector shuffles and
9916 // scalar_to_vector here as well.
9917
9918 if (!LegalOperations) {
9919 EVT IndexTy = TLI.getVectorIdxTy();
9920 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9921 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9922 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009923 }
9924
Michael J. Spencerf375d802014-05-29 01:42:45 +00009925 bool BCNumEltsChanged = false;
9926 EVT ExtVT = VT.getVectorElementType();
9927 EVT LVT = ExtVT;
9928
9929 // If the result of load has to be truncated, then it's not necessarily
9930 // profitable.
9931 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9932 return SDValue();
9933
9934 if (InVec.getOpcode() == ISD::BITCAST) {
9935 // Don't duplicate a load with other uses.
9936 if (!InVec.hasOneUse())
9937 return SDValue();
9938
9939 EVT BCVT = InVec.getOperand(0).getValueType();
9940 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9941 return SDValue();
9942 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9943 BCNumEltsChanged = true;
9944 InVec = InVec.getOperand(0);
9945 ExtVT = BCVT.getVectorElementType();
9946 }
9947
9948 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
9949 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
9950 ISD::isNormalLoad(InVec.getNode())) {
9951 SDValue Index = N->getOperand(1);
9952 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
9953 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
9954 OrigLoad);
9955 }
9956
Evan Cheng1120279a2008-05-13 08:35:03 +00009957 // Perform only after legalization to ensure build_vector / vector_shuffle
9958 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009959 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009960
Mon P Wangca6d6de2009-01-17 00:07:25 +00009961 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9962 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9963 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009964
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009965 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009966 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009967
Craig Topperc0196b12014-04-14 00:51:57 +00009968 LoadSDNode *LN0 = nullptr;
9969 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009970 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009971 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009972 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009973 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009974 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009975 // Don't duplicate a load with other uses.
9976 if (!InVec.hasOneUse())
9977 return SDValue();
9978
Evan Cheng1120279a2008-05-13 08:35:03 +00009979 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009980 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009981 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9982 // =>
9983 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009984
Eli Friedmane96286c2011-12-26 22:49:32 +00009985 // Don't duplicate a load with other uses.
9986 if (!InVec.hasOneUse())
9987 return SDValue();
9988
Mon P Wangb5eb7202008-12-11 00:26:16 +00009989 // If the bit convert changed the number of elements, it is unsafe
9990 // to examine the mask.
9991 if (BCNumEltsChanged)
9992 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009993
9994 // Select the input vector, guarding against out of range extract vector.
9995 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009996 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009997 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9998
Eli Friedmane96286c2011-12-26 22:49:32 +00009999 if (InVec.getOpcode() == ISD::BITCAST) {
10000 // Don't duplicate a load with other uses.
10001 if (!InVec.hasOneUse())
10002 return SDValue();
10003
Evan Cheng1120279a2008-05-13 08:35:03 +000010004 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010005 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010006 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010007 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010008 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencerf375d802014-05-29 01:42:45 +000010009 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010010 }
10011 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010012
Eli Friedmane96286c2011-12-26 22:49:32 +000010013 // Make sure we found a non-volatile load and the extractelement is
10014 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010015 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010016 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010017
Eric Christopherc6418b12010-11-03 20:44:42 +000010018 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10019 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010020 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010021
Michael J. Spencerf375d802014-05-29 01:42:45 +000010022 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010023 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010024
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010025 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010026}
Evan Cheng0de312d2007-10-06 08:19:55 +000010027
Michael Liao6d106b72012-10-23 23:06:52 +000010028// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10029SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10030 // We perform this optimization post type-legalization because
10031 // the type-legalizer often scalarizes integer-promoted vectors.
10032 // Performing this optimization before may create bit-casts which
10033 // will be type-legalized to complex code sequences.
10034 // We perform this optimization only before the operation legalizer because we
10035 // may introduce illegal operations.
10036 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10037 return SDValue();
10038
Dan Gohmana8665142007-06-25 16:23:39 +000010039 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010040 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010041 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010042
Nadav Rotembf6568b2011-10-29 21:23:04 +000010043 // Check to see if this is a BUILD_VECTOR of a bunch of values
10044 // which come from any_extend or zero_extend nodes. If so, we can create
10045 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010046 // optimizations. We do not handle sign-extend because we can't fill the sign
10047 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010048 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010049 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010050
Craig Topper02cb0fb2012-01-17 09:09:48 +000010051 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010052 SDValue In = N->getOperand(i);
10053 // Ignore undef inputs.
10054 if (In.getOpcode() == ISD::UNDEF) continue;
10055
10056 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10057 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10058
Nadav Rotemf3103612011-10-31 20:08:25 +000010059 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010060 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010061 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010062 break;
10063 }
10064
10065 // The input is a ZeroExt or AnyExt. Check the original type.
10066 EVT InTy = In.getOperand(0).getValueType();
10067
10068 // Check that all of the widened source types are the same.
10069 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010070 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010071 SourceType = InTy;
10072 else if (InTy != SourceType) {
10073 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010074 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010075 break;
10076 }
10077
10078 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010079 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010080 }
10081
Nadav Rotemf3103612011-10-31 20:08:25 +000010082 // In order to have valid types, all of the inputs must be extended from the
10083 // same source type and all of the inputs must be any or zero extend.
10084 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010085 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010086 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010087 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10088 isPowerOf2_32(SourceType.getSizeInBits());
10089
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010090 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10091 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010092 if (!ValidTypes)
10093 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010094
Michael Liao6d106b72012-10-23 23:06:52 +000010095 bool isLE = TLI.isLittleEndian();
10096 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10097 assert(ElemRatio > 1 && "Invalid element size ratio");
10098 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10099 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010100
Michael Liao6d106b72012-10-23 23:06:52 +000010101 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10102 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010103
Michael Liao6d106b72012-10-23 23:06:52 +000010104 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010105 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010106 SDValue Cast = N->getOperand(i);
10107 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10108 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10109 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10110 SDValue In;
10111 if (Cast.getOpcode() == ISD::UNDEF)
10112 In = DAG.getUNDEF(SourceType);
10113 else
10114 In = Cast->getOperand(0);
10115 unsigned Index = isLE ? (i * ElemRatio) :
10116 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010117
Michael Liao6d106b72012-10-23 23:06:52 +000010118 assert(Index < Ops.size() && "Invalid index");
10119 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010120 }
Chris Lattner5336a592006-03-19 01:27:56 +000010121
Michael Liao6d106b72012-10-23 23:06:52 +000010122 // The type of the new BUILD_VECTOR node.
10123 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10124 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10125 "Invalid vector size");
10126 // Check if the new vector type is legal.
10127 if (!isTypeLegal(VecVT)) return SDValue();
10128
10129 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010130 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010131
10132 // The new BUILD_VECTOR node has the potential to be further optimized.
10133 AddToWorkList(BV.getNode());
10134 // Bitcast to the desired type.
10135 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10136}
10137
Michael Liao59229792012-10-24 04:14:18 +000010138SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10139 EVT VT = N->getValueType(0);
10140
10141 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010142 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010143
10144 EVT SrcVT = MVT::Other;
10145 unsigned Opcode = ISD::DELETED_NODE;
10146 unsigned NumDefs = 0;
10147
10148 for (unsigned i = 0; i != NumInScalars; ++i) {
10149 SDValue In = N->getOperand(i);
10150 unsigned Opc = In.getOpcode();
10151
10152 if (Opc == ISD::UNDEF)
10153 continue;
10154
10155 // If all scalar values are floats and converted from integers.
10156 if (Opcode == ISD::DELETED_NODE &&
10157 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10158 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010159 }
Tom Stellard567f8862013-01-02 22:13:01 +000010160
Michael Liao59229792012-10-24 04:14:18 +000010161 if (Opc != Opcode)
10162 return SDValue();
10163
10164 EVT InVT = In.getOperand(0).getValueType();
10165
10166 // If all scalar values are typed differently, bail out. It's chosen to
10167 // simplify BUILD_VECTOR of integer types.
10168 if (SrcVT == MVT::Other)
10169 SrcVT = InVT;
10170 if (SrcVT != InVT)
10171 return SDValue();
10172 NumDefs++;
10173 }
10174
10175 // If the vector has just one element defined, it's not worth to fold it into
10176 // a vectorized one.
10177 if (NumDefs < 2)
10178 return SDValue();
10179
10180 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10181 && "Should only handle conversion from integer to float.");
10182 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10183
10184 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010185
10186 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10187 return SDValue();
10188
Michael Liao59229792012-10-24 04:14:18 +000010189 SmallVector<SDValue, 8> Opnds;
10190 for (unsigned i = 0; i != NumInScalars; ++i) {
10191 SDValue In = N->getOperand(i);
10192
10193 if (In.getOpcode() == ISD::UNDEF)
10194 Opnds.push_back(DAG.getUNDEF(SrcVT));
10195 else
10196 Opnds.push_back(In.getOperand(0));
10197 }
Craig Topper48d114b2014-04-26 18:35:24 +000010198 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Michael Liao59229792012-10-24 04:14:18 +000010199 AddToWorkList(BV.getNode());
10200
10201 return DAG.getNode(Opcode, dl, VT, BV);
10202}
10203
Michael Liao6d106b72012-10-23 23:06:52 +000010204SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10205 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010206 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010207 EVT VT = N->getValueType(0);
10208
10209 // A vector built entirely of undefs is undef.
10210 if (ISD::allOperandsUndef(N))
10211 return DAG.getUNDEF(VT);
10212
10213 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10214 if (V.getNode())
10215 return V;
10216
Michael Liao59229792012-10-24 04:14:18 +000010217 V = reduceBuildVecConvertToConvertBuildVec(N);
10218 if (V.getNode())
10219 return V;
10220
Dan Gohmana8665142007-06-25 16:23:39 +000010221 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10222 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10223 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010224
10225 // May only combine to shuffle after legalize if shuffle is legal.
10226 if (LegalOperations &&
10227 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10228 return SDValue();
10229
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010230 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010231 for (unsigned i = 0; i != NumInScalars; ++i) {
10232 // Ignore undef inputs.
10233 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010234
Dan Gohmana8665142007-06-25 16:23:39 +000010235 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010236 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010237 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010238 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010239 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010240 break;
10241 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010242
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010243 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010244 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010245 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10246 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010247
Craig Topperc0196b12014-04-14 00:51:57 +000010248 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010249 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010250 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010251 VecIn2 = ExtractedFromVec;
10252 } else {
10253 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010254 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010255 break;
10256 }
10257 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010258
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010259 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010260 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010261 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010262 for (unsigned i = 0; i != NumInScalars; ++i) {
10263 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010264 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010265 continue;
10266 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010267
Rafael Espindolab93db662009-04-24 12:40:33 +000010268 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010269 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010270 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010271 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010272 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10273 if (ExtIndex > VT.getVectorNumElements())
10274 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010275
Nate Begeman5f829d82009-04-29 05:20:52 +000010276 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010277 continue;
10278 }
10279
10280 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010281 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010282 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010283 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010284
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010285 // We can't generate a shuffle node with mismatched input and output types.
10286 // Attempt to transform a single input vector to the correct type.
10287 if ((VT != VecIn1.getValueType())) {
10288 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010289 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010290 return SDValue();
10291
10292 // We only support widening of vectors which are half the size of the
10293 // output registers. For example XMM->YMM widening on X86 with AVX.
10294 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10295 return SDValue();
10296
James Molloy1e5c6112012-09-10 14:01:21 +000010297 // If the input vector type has a different base type to the output
10298 // vector type, bail out.
10299 if (VecIn1.getValueType().getVectorElementType() !=
10300 VT.getVectorElementType())
10301 return SDValue();
10302
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010303 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010304 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010305 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010306 }
10307
10308 // If VecIn2 is unused then change it to undef.
10309 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10310
Nadav Rotem841c9a82012-09-20 08:53:31 +000010311 // Check that we were able to transform all incoming values to the same
10312 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010313 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10314 VecIn1.getValueType() != VT)
10315 return SDValue();
10316
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010317 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010318 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010319 return SDValue();
10320
Dan Gohmana8665142007-06-25 16:23:39 +000010321 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010322 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010323 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010324 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010325 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010326 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010327
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010328 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010329}
10330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010331SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010332 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10333 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10334 // inputs come from at most two distinct vectors, turn this into a shuffle
10335 // node.
10336
10337 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010338 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010339 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010340
Nadav Rotem01892102012-07-14 21:30:27 +000010341 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010342 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010343 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010344 return DAG.getUNDEF(VT);
10345
10346 // Optimize concat_vectors where one of the vectors is undef.
10347 if (N->getNumOperands() == 2 &&
10348 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10349 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010350 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010351
10352 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10353 if (In->getOpcode() == ISD::BITCAST &&
10354 !In->getOperand(0)->getValueType(0).isVector()) {
10355 SDValue Scalar = In->getOperand(0);
10356 EVT SclTy = Scalar->getValueType(0);
10357
10358 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10359 return SDValue();
10360
10361 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10362 VT.getSizeInBits() / SclTy.getSizeInBits());
10363 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10364 return SDValue();
10365
10366 SDLoc dl = SDLoc(N);
10367 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10368 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10369 }
10370 }
Nadav Rotem01892102012-07-14 21:30:27 +000010371
Robert Lougher7d9084f2014-02-11 15:42:46 +000010372 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10373 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10374 if (N->getNumOperands() == 2 &&
10375 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10376 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10377 EVT VT = N->getValueType(0);
10378 SDValue N0 = N->getOperand(0);
10379 SDValue N1 = N->getOperand(1);
10380 SmallVector<SDValue, 8> Opnds;
10381 unsigned BuildVecNumElts = N0.getNumOperands();
10382
10383 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10384 Opnds.push_back(N0.getOperand(i));
10385 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10386 Opnds.push_back(N1.getOperand(i));
10387
Craig Topper48d114b2014-04-26 18:35:24 +000010388 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010389 }
10390
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010391 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10392 // nodes often generate nop CONCAT_VECTOR nodes.
10393 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10394 // place the incoming vectors at the exact same location.
10395 SDValue SingleSource = SDValue();
10396 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10397
10398 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10399 SDValue Op = N->getOperand(i);
10400
10401 if (Op.getOpcode() == ISD::UNDEF)
10402 continue;
10403
10404 // Check if this is the identity extract:
10405 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10406 return SDValue();
10407
10408 // Find the single incoming vector for the extract_subvector.
10409 if (SingleSource.getNode()) {
10410 if (Op.getOperand(0) != SingleSource)
10411 return SDValue();
10412 } else {
10413 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010414
10415 // Check the source type is the same as the type of the result.
10416 // If not, this concat may extend the vector, so we can not
10417 // optimize it away.
10418 if (SingleSource.getValueType() != N->getValueType(0))
10419 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010420 }
10421
10422 unsigned IdentityIndex = i * PartNumElem;
10423 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10424 // The extract index must be constant.
10425 if (!CS)
10426 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010427
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010428 // Check that we are reading from the identity index.
10429 if (CS->getZExtValue() != IdentityIndex)
10430 return SDValue();
10431 }
10432
10433 if (SingleSource.getNode())
10434 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010435
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010436 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010437}
10438
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010439SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10440 EVT NVT = N->getValueType(0);
10441 SDValue V = N->getOperand(0);
10442
Michael Liao7a442c802012-10-17 20:48:33 +000010443 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10444 // Combine:
10445 // (extract_subvec (concat V1, V2, ...), i)
10446 // Into:
10447 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010448 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10449 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010450 if (V->getOperand(0).getValueType() != NVT)
10451 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010452 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10453 unsigned NumElems = NVT.getVectorNumElements();
10454 assert((Idx % NumElems) == 0 &&
10455 "IDX in concat is not a multiple of the result vector length.");
10456 return V->getOperand(Idx / NumElems);
10457 }
10458
Michael Liaobb05a1d2013-03-25 23:47:35 +000010459 // Skip bitcasting
10460 if (V->getOpcode() == ISD::BITCAST)
10461 V = V.getOperand(0);
10462
10463 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010464 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010465 // Handle only simple case where vector being inserted and vector
10466 // being extracted are of same type, and are half size of larger vectors.
10467 EVT BigVT = V->getOperand(0).getValueType();
10468 EVT SmallVT = V->getOperand(1).getValueType();
10469 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10470 return SDValue();
10471
10472 // Only handle cases where both indexes are constants with the same type.
10473 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10474 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10475
10476 if (InsIdx && ExtIdx &&
10477 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10478 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10479 // Combine:
10480 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10481 // Into:
10482 // indices are equal or bit offsets are equal => V1
10483 // otherwise => (extract_subvec V1, ExtIdx)
10484 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10485 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10486 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10487 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10488 DAG.getNode(ISD::BITCAST, dl,
10489 N->getOperand(0).getValueType(),
10490 V->getOperand(0)), N->getOperand(1));
10491 }
10492 }
10493
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010494 return SDValue();
10495}
10496
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010497// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10498static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10499 EVT VT = N->getValueType(0);
10500 unsigned NumElts = VT.getVectorNumElements();
10501
10502 SDValue N0 = N->getOperand(0);
10503 SDValue N1 = N->getOperand(1);
10504 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10505
10506 SmallVector<SDValue, 4> Ops;
10507 EVT ConcatVT = N0.getOperand(0).getValueType();
10508 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10509 unsigned NumConcats = NumElts / NumElemsPerConcat;
10510
10511 // Look at every vector that's inserted. We're looking for exact
10512 // subvector-sized copies from a concatenated vector
10513 for (unsigned I = 0; I != NumConcats; ++I) {
10514 // Make sure we're dealing with a copy.
10515 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010516 bool AllUndef = true, NoUndef = true;
10517 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10518 if (SVN->getMaskElt(J) >= 0)
10519 AllUndef = false;
10520 else
10521 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010522 }
10523
Hao Liubc601962013-05-13 02:07:05 +000010524 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010525 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10526 return SDValue();
10527
10528 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10529 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10530 return SDValue();
10531
10532 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10533 if (FirstElt < N0.getNumOperands())
10534 Ops.push_back(N0.getOperand(FirstElt));
10535 else
10536 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10537
10538 } else if (AllUndef) {
10539 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10540 } else { // Mixed with general masks and undefs, can't do optimization.
10541 return SDValue();
10542 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010543 }
10544
Craig Topper48d114b2014-04-26 18:35:24 +000010545 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010546}
10547
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010548SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010549 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010550 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010551
Mon P Wang25f01062008-11-10 04:46:22 +000010552 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010553 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010554
Craig Topper5894fe42012-04-09 05:16:56 +000010555 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010556
Craig Topper279c77b2012-01-04 08:07:43 +000010557 // Canonicalize shuffle undef, undef -> undef
10558 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10559 return DAG.getUNDEF(VT);
10560
10561 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10562
10563 // Canonicalize shuffle v, v -> v, undef
10564 if (N0 == N1) {
10565 SmallVector<int, 8> NewMask;
10566 for (unsigned i = 0; i != NumElts; ++i) {
10567 int Idx = SVN->getMaskElt(i);
10568 if (Idx >= (int)NumElts) Idx -= NumElts;
10569 NewMask.push_back(Idx);
10570 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010571 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010572 &NewMask[0]);
10573 }
10574
10575 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10576 if (N0.getOpcode() == ISD::UNDEF) {
10577 SmallVector<int, 8> NewMask;
10578 for (unsigned i = 0; i != NumElts; ++i) {
10579 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010580 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010581 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010582 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010583 else
10584 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010585 }
10586 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010587 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010588 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010589 &NewMask[0]);
10590 }
10591
10592 // Remove references to rhs if it is undef
10593 if (N1.getOpcode() == ISD::UNDEF) {
10594 bool Changed = false;
10595 SmallVector<int, 8> NewMask;
10596 for (unsigned i = 0; i != NumElts; ++i) {
10597 int Idx = SVN->getMaskElt(i);
10598 if (Idx >= (int)NumElts) {
10599 Idx = -1;
10600 Changed = true;
10601 }
10602 NewMask.push_back(Idx);
10603 }
10604 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010605 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010606 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010607
Bob Wilsonf63da122010-10-28 17:06:14 +000010608 // If it is a splat, check if the argument vector is another splat or a
10609 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010610 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010611 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010612
Dan Gohmana8665142007-06-25 16:23:39 +000010613 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010614 // not the number of vector elements, look through it. Be careful not to
10615 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010616 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010617 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010618 if (ConvInput.getValueType().isVector() &&
10619 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010620 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010621 }
10622
Dan Gohmana8665142007-06-25 16:23:39 +000010623 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010624 assert(V->getNumOperands() == NumElts &&
10625 "BUILD_VECTOR has wrong number of operands");
10626 SDValue Base;
10627 bool AllSame = true;
10628 for (unsigned i = 0; i != NumElts; ++i) {
10629 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10630 Base = V->getOperand(i);
10631 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010632 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010633 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010634 // Splat of <u, u, u, u>, return <u, u, u, u>
10635 if (!Base.getNode())
10636 return N0;
10637 for (unsigned i = 0; i != NumElts; ++i) {
10638 if (V->getOperand(i) != Base) {
10639 AllSame = false;
10640 break;
10641 }
10642 }
10643 // Splat of <x, x, x, x>, return <x, x, x, x>
10644 if (AllSame)
10645 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010646 }
10647 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010648
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010649 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10650 Level < AfterLegalizeVectorOps &&
10651 (N1.getOpcode() == ISD::UNDEF ||
10652 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10653 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10654 SDValue V = partitionShuffleOfConcats(N, DAG);
10655
10656 if (V.getNode())
10657 return V;
10658 }
10659
Nadav Rotemb0783502012-04-01 19:31:22 +000010660 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010661 // and it reverses the swizzle of the previous shuffle then we can
10662 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010663 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10664 N1.getOpcode() == ISD::UNDEF) {
10665
Nadav Rotemb0783502012-04-01 19:31:22 +000010666 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10667
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010668 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10669 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10670 return SDValue();
10671
Craig Topper5894fe42012-04-09 05:16:56 +000010672 // The incoming shuffle must be of the same type as the result of the
10673 // current shuffle.
10674 assert(OtherSV->getOperand(0).getValueType() == VT &&
10675 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010676
10677 for (unsigned i = 0; i != NumElts; ++i) {
10678 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010679 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010680 // Next, this index comes from the first value, which is the incoming
10681 // shuffle. Adopt the incoming index.
10682 if (Idx >= 0)
10683 Idx = OtherSV->getMaskElt(Idx);
10684
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010685 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010686 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010687 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010688 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010689
10690 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010691 }
10692
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010693 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010694}
10695
Manman Ren413a6cb2014-01-31 01:10:35 +000010696SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10697 SDValue N0 = N->getOperand(0);
10698 SDValue N2 = N->getOperand(2);
10699
10700 // If the input vector is a concatenation, and the insert replaces
10701 // one of the halves, we can optimize into a single concat_vectors.
10702 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10703 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10704 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10705 EVT VT = N->getValueType(0);
10706
10707 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10708 // (concat_vectors Z, Y)
10709 if (InsIdx == 0)
10710 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10711 N->getOperand(1), N0.getOperand(1));
10712
10713 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10714 // (concat_vectors X, Z)
10715 if (InsIdx == VT.getVectorNumElements()/2)
10716 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10717 N0.getOperand(0), N->getOperand(1));
10718 }
10719
10720 return SDValue();
10721}
10722
Evan Chenga320abc2006-04-20 08:56:16 +000010723/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010724/// an AND to a vector_shuffle with the destination vector and a zero vector.
10725/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010726/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010727SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010728 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010729 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010730 SDValue LHS = N->getOperand(0);
10731 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010732 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010733 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010734 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010735 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010736 SmallVector<int, 8> Indices;
10737 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010738 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010739 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010740 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010741 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010742
10743 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010744 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010745 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010746 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010747 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010748 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010749 }
10750
10751 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010752 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010753 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010754 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010755
Dan Gohmana8665142007-06-25 16:23:39 +000010756 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010757 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010758 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010759 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000010760 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000010761 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010762 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010763 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010764 }
10765 }
Bill Wendling31b50992009-01-30 23:59:18 +000010766
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010767 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010768}
10769
Dan Gohmana8665142007-06-25 16:23:39 +000010770/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010771SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010772 assert(N->getValueType(0).isVector() &&
10773 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010774
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010775 SDValue LHS = N->getOperand(0);
10776 SDValue RHS = N->getOperand(1);
10777 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010778 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010779
Dan Gohmana8665142007-06-25 16:23:39 +000010780 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010781 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010782 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010783 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010784 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010785 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10786 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010787 return SDValue();
10788
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010789 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010790 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010791 SDValue LHSOp = LHS.getOperand(i);
10792 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010793
Evan Cheng64d28462006-05-31 06:08:35 +000010794 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010795 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10796 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010797 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010798 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010799 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010800 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010801 break;
10802 }
Bill Wendling31b50992009-01-30 23:59:18 +000010803
Bob Wilson54081442010-12-17 23:06:49 +000010804 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010805 EVT RVT = RHSOp.getValueType();
10806 if (RVT != VT) {
10807 // Integer BUILD_VECTOR operands may have types larger than the element
10808 // size (e.g., when the element type is not legal). Prior to type
10809 // legalization, the types may not match between the two BUILD_VECTORS.
10810 // Truncate one of the operands to make them match.
10811 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010812 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010813 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010814 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010815 VT = RVT;
10816 }
10817 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010818 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010819 LHSOp, RHSOp);
10820 if (FoldOp.getOpcode() != ISD::UNDEF &&
10821 FoldOp.getOpcode() != ISD::Constant &&
10822 FoldOp.getOpcode() != ISD::ConstantFP)
10823 break;
10824 Ops.push_back(FoldOp);
10825 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010826 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010827
Bob Wilson54081442010-12-17 23:06:49 +000010828 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000010829 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000010830 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010831
Andrea Di Biagio446a5272014-05-30 23:17:53 +000010832 // Type legalization might introduce new shuffles in the DAG.
10833 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10834 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10835 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10836 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10837 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10838 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10839 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10840 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10841
10842 if (SVN0->getMask().equals(SVN1->getMask())) {
10843 EVT VT = N->getValueType(0);
10844 SDValue UndefVector = LHS.getOperand(1);
10845 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10846 LHS.getOperand(0), RHS.getOperand(0));
10847 AddUsersToWorkList(N);
10848 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10849 &SVN0->getMask()[0]);
10850 }
10851 }
10852
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010853 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010854}
10855
Craig Topper82384612012-09-11 01:45:21 +000010856/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10857SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010858 assert(N->getValueType(0).isVector() &&
10859 "SimplifyVUnaryOp only works on vectors!");
10860
10861 SDValue N0 = N->getOperand(0);
10862
10863 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10864 return SDValue();
10865
10866 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10867 SmallVector<SDValue, 8> Ops;
10868 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10869 SDValue Op = N0.getOperand(i);
10870 if (Op.getOpcode() != ISD::UNDEF &&
10871 Op.getOpcode() != ISD::ConstantFP)
10872 break;
10873 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010874 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010875 if (FoldOp.getOpcode() != ISD::UNDEF &&
10876 FoldOp.getOpcode() != ISD::ConstantFP)
10877 break;
10878 Ops.push_back(FoldOp);
10879 AddToWorkList(FoldOp.getNode());
10880 }
10881
10882 if (Ops.size() != N0.getNumOperands())
10883 return SDValue();
10884
Craig Topper48d114b2014-04-26 18:35:24 +000010885 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000010886}
10887
Andrew Trickef9de2a2013-05-25 02:42:55 +000010888SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010889 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010890 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010891
Bill Wendling31b50992009-01-30 23:59:18 +000010892 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010893 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010894
Nate Begeman2042aa52005-10-08 00:29:44 +000010895 // If we got a simplified select_cc node back from SimplifySelectCC, then
10896 // break it down into a new SETCC node, and a new SELECT node, and then return
10897 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010898 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010899 // Check to see if we got a select_cc back (to turn into setcc/select).
10900 // Otherwise, just return whatever node we got back, like fabs.
10901 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010902 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010903 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010904 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010905 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010906 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010907 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10908 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010909 }
Bill Wendling31b50992009-01-30 23:59:18 +000010910
Nate Begeman2042aa52005-10-08 00:29:44 +000010911 return SCC;
10912 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010913 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010914}
10915
Chris Lattner6c14c352005-10-18 06:04:22 +000010916/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10917/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010918/// select. Callers of this should assume that TheSelect is deleted if this
10919/// returns true. As such, they should return the appropriate thing (e.g. the
10920/// node) back to the top-level of the DAG combiner loop to avoid it being
10921/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010922bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010923 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010924
Nadav Rotema49a02a2011-02-11 19:57:47 +000010925 // Cannot simplify select with vector condition
10926 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10927
Chris Lattner6c14c352005-10-18 06:04:22 +000010928 // If this is a select from two identical things, try to pull the operation
10929 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010930 if (LHS.getOpcode() != RHS.getOpcode() ||
10931 !LHS.hasOneUse() || !RHS.hasOneUse())
10932 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010933
Chris Lattner254c4452010-09-21 15:46:59 +000010934 // If this is a load and the token chain is identical, replace the select
10935 // of two loads with a load through a select of the address to load from.
10936 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10937 // constants have been dropped into the constant pool.
10938 if (LHS.getOpcode() == ISD::LOAD) {
10939 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10940 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010941
Chris Lattner254c4452010-09-21 15:46:59 +000010942 // Token chains must be identical.
10943 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010944 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010945 LLD->isVolatile() || RLD->isVolatile() ||
10946 // If this is an EXTLOAD, the VT's must match.
10947 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010948 // If this is an EXTLOAD, the kind of extension must match.
10949 (LLD->getExtensionType() != RLD->getExtensionType() &&
10950 // The only exception is if one of the extensions is anyext.
10951 LLD->getExtensionType() != ISD::EXTLOAD &&
10952 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010953 // FIXME: this discards src value information. This is
10954 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010955 // both potential memory locations. Since we are discarding
10956 // src value info, don't do the transformation if the memory
10957 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010958 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010959 RLD->getPointerInfo().getAddrSpace() != 0 ||
10960 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10961 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010962 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010963
Chris Lattnere3267522010-09-21 15:58:55 +000010964 // Check that the select condition doesn't reach either load. If so,
10965 // folding this will induce a cycle into the DAG. If not, this is safe to
10966 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010967 SDValue Addr;
10968 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010969 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10970 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10971 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10972 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010973 // The loads must not depend on one another.
10974 if (LLD->isPredecessorOf(RLD) ||
10975 RLD->isPredecessorOf(LLD))
10976 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010977 Addr = DAG.getSelect(SDLoc(TheSelect),
10978 LLD->getBasePtr().getValueType(),
10979 TheSelect->getOperand(0), LLD->getBasePtr(),
10980 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010981 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010982 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10983 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10984
10985 if ((LLD->hasAnyUseOfValue(1) &&
10986 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010987 (RLD->hasAnyUseOfValue(1) &&
10988 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010989 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010990
Andrew Trickef9de2a2013-05-25 02:42:55 +000010991 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010992 LLD->getBasePtr().getValueType(),
10993 TheSelect->getOperand(0),
10994 TheSelect->getOperand(1),
10995 LLD->getBasePtr(), RLD->getBasePtr(),
10996 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010997 }
10998
Chris Lattnere3267522010-09-21 15:58:55 +000010999 SDValue Load;
11000 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11001 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011002 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011003 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011004 LLD->getChain(), Addr, MachinePointerInfo(),
11005 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000011006 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011007 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011008 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11009 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011010 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011011 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011012 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011013 LLD->getChain(), Addr, MachinePointerInfo(),
11014 LLD->getMemoryVT(), LLD->isVolatile(),
11015 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000011016 }
Chris Lattnere3267522010-09-21 15:58:55 +000011017
11018 // Users of the select now use the result of the load.
11019 CombineTo(TheSelect, Load);
11020
11021 // Users of the old loads now use the new load's chain. We know the
11022 // old-load value is dead now.
11023 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11024 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11025 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011026 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011027
Chris Lattner6c14c352005-10-18 06:04:22 +000011028 return false;
11029}
11030
Chris Lattner43d63772009-03-11 05:08:08 +000011031/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11032/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011033SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011034 SDValue N2, SDValue N3,
11035 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011036 // (x ? y : y) -> y.
11037 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011038
Owen Anderson53aa7a92009-08-10 22:56:29 +000011039 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011040 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11041 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11042 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011043
11044 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011045 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011046 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011047 if (SCC.getNode()) AddToWorkList(SCC.getNode());
11048 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011049
11050 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011051 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011052 return N2;
11053 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011054 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011055 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011056
Nate Begeman2042aa52005-10-08 00:29:44 +000011057 // Check to see if we can simplify the select into an fabs node
11058 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11059 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011060 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011061 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11062 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11063 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11064 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011065 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011066
Nate Begeman2042aa52005-10-08 00:29:44 +000011067 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11068 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11069 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11070 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011071 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011072 }
11073 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011074
Chris Lattner43d63772009-03-11 05:08:08 +000011075 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11076 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11077 // in it. This is a win when the constant is not otherwise available because
11078 // it replaces two constant pool loads with one. We only do this if the FP
11079 // type is known to be legal, because if it isn't, then we are before legalize
11080 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011081 // messing with soft float) and if the ConstantFP is not legal, because if
11082 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011083 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11084 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11085 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011086 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011087 TargetLowering::Legal &&
11088 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11089 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011090 // If both constants have multiple uses, then we won't need to do an
11091 // extra load, they are likely around in registers for other users.
11092 (TV->hasOneUse() || FV->hasOneUse())) {
11093 Constant *Elts[] = {
11094 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11095 const_cast<ConstantFP*>(TV->getConstantFPValue())
11096 };
Chris Lattner229907c2011-07-18 04:54:35 +000011097 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011098 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011099
Chris Lattner43d63772009-03-11 05:08:08 +000011100 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011101 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011102 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11103 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011104 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011105
11106 // Get the offsets to the 0 and 1 element of the array so that we can
11107 // select between them.
11108 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011109 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011110 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011111
Chris Lattner43d63772009-03-11 05:08:08 +000011112 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011113 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011114 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011115 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011116 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11117 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011118 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011119 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011120 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011121 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011122 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011123 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011124 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011125
11126 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011127 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011128
Nate Begeman2042aa52005-10-08 00:29:44 +000011129 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011130 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011131 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011132 (N1C->isNullValue() || // (a < 0) ? b : 0
11133 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011134 EVT XType = N0.getValueType();
11135 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011136 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011137 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011138 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011139 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11140 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011141 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011142 SDValue ShCt = DAG.getConstant(ShCtV,
11143 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011144 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011145 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011146 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011147
Duncan Sands11dd4242008-06-08 20:54:56 +000011148 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011149 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011150 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011151 }
Bill Wendling31b50992009-01-30 23:59:18 +000011152
11153 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011154 }
Bill Wendling31b50992009-01-30 23:59:18 +000011155
Andrew Trickef9de2a2013-05-25 02:42:55 +000011156 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011157 XType, N0,
11158 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011159 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000011160 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011161
Duncan Sands11dd4242008-06-08 20:54:56 +000011162 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011163 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011164 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011165 }
Bill Wendling31b50992009-01-30 23:59:18 +000011166
11167 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011168 }
11169 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011170
Owen Anderson3231d132010-09-22 22:58:22 +000011171 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11172 // where y is has a single bit set.
11173 // A plaintext description would be, we can turn the SELECT_CC into an AND
11174 // when the condition can be materialized as an all-ones register. Any
11175 // single bit-test can be materialized as an all-ones register with
11176 // shift-left and shift-right-arith.
11177 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11178 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011179 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011180 N2C && N2C->isNullValue()) {
11181 SDValue AndLHS = N0->getOperand(0);
11182 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11183 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11184 // Shift the tested bit over the sign bit.
11185 APInt AndMask = ConstAndRHS->getAPIntValue();
11186 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011187 DAG.getConstant(AndMask.countLeadingZeros(),
11188 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011189 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011190
Owen Anderson3231d132010-09-22 22:58:22 +000011191 // Now arithmetic right shift it all the way over, so the result is either
11192 // all-ones, or zero.
11193 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011194 DAG.getConstant(AndMask.getBitWidth()-1,
11195 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011196 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011197
Owen Anderson3231d132010-09-22 22:58:22 +000011198 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11199 }
11200 }
11201
Nate Begeman6828ed92005-10-10 21:26:48 +000011202 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011203 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000011204 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11205 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011206
Chris Lattnera083ffc2007-04-11 06:50:51 +000011207 // If the caller doesn't want us to simplify this into a zext of a compare,
11208 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011209 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011210 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011211
Nate Begeman6828ed92005-10-10 21:26:48 +000011212 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011213 // NOTE: Don't create a SETCC if it's not legal on this target.
11214 if (!LegalOperations ||
11215 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011216 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011217 SDValue Temp, SCC;
11218 // cast from setcc result type to select result type
11219 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011220 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011221 N0, N1, CC);
11222 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011223 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011224 N2.getValueType());
11225 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011226 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011227 N2.getValueType(), SCC);
11228 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011229 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11230 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011231 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011232 }
11233
11234 AddToWorkList(SCC.getNode());
11235 AddToWorkList(Temp.getNode());
11236
11237 if (N2C->getAPIntValue() == 1)
11238 return Temp;
11239
11240 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011241 return DAG.getNode(
11242 ISD::SHL, DL, N2.getValueType(), Temp,
11243 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11244 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011245 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011246 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011247
Nate Begeman2042aa52005-10-08 00:29:44 +000011248 // Check to see if this is the equivalent of setcc
11249 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11250 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011251 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011252 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011253 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011254 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11255 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011256 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011257 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011258 return Res;
11259 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011260
Bill Wendling31b50992009-01-30 23:59:18 +000011261 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011262 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011263 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011264 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011265 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011266 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011267 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011268 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011269 }
Bill Wendling31b50992009-01-30 23:59:18 +000011270 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011271 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011272 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011273 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011274 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011275 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011276 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011277 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011278 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011279 }
Bill Wendling31b50992009-01-30 23:59:18 +000011280 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011281 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011282 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011283 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011284 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011285 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011286 }
11287 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011288
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011289 // Check to see if this is an integer abs.
11290 // select_cc setg[te] X, 0, X, -X ->
11291 // select_cc setgt X, -1, X, -X ->
11292 // select_cc setl[te] X, 0, -X, X ->
11293 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011294 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011295 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011296 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011297 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11298 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11299 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11300 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11301 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11302 (N1C->isOne() && CC == ISD::SETLT)) &&
11303 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11304 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11305
Owen Anderson53aa7a92009-08-10 22:56:29 +000011306 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011307 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011308 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011309 N0,
11310 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011311 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011312 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011313 XType, N0, Shift);
11314 AddToWorkList(Shift.getNode());
11315 AddToWorkList(Add.getNode());
11316 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011317 }
11318 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011320 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011321}
11322
Evan Cheng92658d52007-02-08 22:13:59 +000011323/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011324SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011325 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011326 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011327 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011328 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011329 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011330}
11331
Nate Begemanc6f067a2005-10-20 02:15:44 +000011332/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11333/// return a DAG expression to select that will generate the same value by
11334/// multiplying by a magic number. See:
11335/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011336SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011337 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11338 if (!C)
11339 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011340
11341 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011342 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011343 return SDValue();
11344
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011345 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011346 SDValue S =
11347 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011348
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011349 for (SDNode *N : Built)
11350 AddToWorkList(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011351 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011352}
11353
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011354/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begemanc6f067a2005-10-20 02:15:44 +000011355/// return a DAG expression to select that will generate the same value by
11356/// multiplying by a magic number. See:
11357/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011358SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011359 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11360 if (!C)
11361 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011362
11363 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011364 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011365 return SDValue();
11366
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011367 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011368 SDValue S =
11369 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011370
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011371 for (SDNode *N : Built)
11372 AddToWorkList(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011373 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011374}
11375
Nate Begeman18150d52009-09-25 06:05:26 +000011376/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011377// to alias with anything but itself. Provides base object and offset as
11378// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011379static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011380 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011381 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011382 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011383
Jim Laskey0463e082006-10-07 23:37:56 +000011384 // If it's an adding a simple constant then integrate the offset.
11385 if (Base.getOpcode() == ISD::ADD) {
11386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11387 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011388 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011389 }
11390 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011391
Nate Begeman18150d52009-09-25 06:05:26 +000011392 // Return the underlying GlobalValue, and update the Offset. Return false
11393 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11394 // by multiple nodes with different offsets.
11395 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11396 GV = G->getGlobal();
11397 Offset += G->getOffset();
11398 return false;
11399 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011400
Nate Begeman18150d52009-09-25 06:05:26 +000011401 // Return the underlying Constant value, and update the Offset. Return false
11402 // for ConstantSDNodes since the same constant pool entry may be represented
11403 // by multiple nodes with different offsets.
11404 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011405 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11406 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011407 Offset += C->getOffset();
11408 return false;
11409 }
Jim Laskey0463e082006-10-07 23:37:56 +000011410 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011411 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011412}
11413
11414/// isAlias - Return true if there is any possibility that the two addresses
11415/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011416bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011417 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011418 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011419
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011420 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011421 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011422
Jim Laskey0463e082006-10-07 23:37:56 +000011423 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011424 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011425 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011426 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011427 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011428 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11429 Base1, Offset1, GV1, CV1);
11430 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11431 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011432
Nate Begeman18150d52009-09-25 06:05:26 +000011433 // If they have a same base address then check to see if they overlap.
11434 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011435 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11436 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011437
Owen Anderson272ff942010-09-20 20:39:59 +000011438 // It is possible for different frame indices to alias each other, mostly
11439 // when tail call optimization reuses return address slots for arguments.
11440 // To catch this case, look up the actual index of frame indices to compute
11441 // the real alias relationship.
11442 if (isFrameIndex1 && isFrameIndex2) {
11443 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11444 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11445 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011446 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11447 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011448 }
11449
Wesley Peck527da1b2010-11-23 03:31:01 +000011450 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011451 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011452 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11453 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011454
Nate Begeman879d8f12009-09-15 00:18:30 +000011455 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11456 // compared to the size and offset of the access, we may be able to prove they
11457 // do not alias. This check is conservative for now to catch cases created by
11458 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011459 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11460 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11461 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11462 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11463 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11464 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11465 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011466
Nate Begeman879d8f12009-09-15 00:18:30 +000011467 // There is no overlap between these relatively aligned accesses of similar
11468 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011469 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11470 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011471 return false;
11472 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011473
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011474 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11475 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011476#ifndef NDEBUG
11477 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11478 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11479 UseAA = false;
11480#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011481 if (UseAA &&
11482 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011483 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011484 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11485 Op1->getSrcValueOffset());
11486 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11487 Op0->getSrcValueOffset() - MinOffset;
11488 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11489 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011490 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011491 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11492 Overlap1,
11493 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11494 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11495 Overlap2,
11496 UseTBAA ? Op1->getTBAAInfo() : nullptr));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011497 if (AAResult == AliasAnalysis::NoAlias)
11498 return false;
11499 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011500
11501 // Otherwise we have to assume they alias.
11502 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011503}
11504
Jim Laskey708d0db2006-10-04 16:53:27 +000011505/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11506/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011507void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011508 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011509 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011510 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011511
Jim Laskeyd07be232006-09-25 16:29:54 +000011512 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011513 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011514
Jim Laskey708d0db2006-10-04 16:53:27 +000011515 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011516 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011517 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011518
Jim Laskey6549d222006-10-05 15:07:25 +000011519 // Look at each chain and determine if it is an alias. If so, add it to the
11520 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011521 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011522 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011523 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011524 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011525
11526 // For TokenFactor nodes, look at each operand and only continue up the
11527 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011528 // find more and revert to original chain since the xform is unlikely to be
11529 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011530 //
11531 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011532 // chain we found before we hit a tokenfactor rather than the original
11533 // chain.
11534 if (Depth > 6 || Aliases.size() == 2) {
11535 Aliases.clear();
11536 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011537 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011538 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011539
Nate Begeman879d8f12009-09-15 00:18:30 +000011540 // Don't bother if we've been before.
11541 if (!Visited.insert(Chain.getNode()))
11542 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011543
Jim Laskey6549d222006-10-05 15:07:25 +000011544 switch (Chain.getOpcode()) {
11545 case ISD::EntryToken:
11546 // Entry token is ideal chain operand, but handled in FindBetterChain.
11547 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011548
Jim Laskey6549d222006-10-05 15:07:25 +000011549 case ISD::LOAD:
11550 case ISD::STORE: {
11551 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011552 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11553 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011554
Jim Laskey6549d222006-10-05 15:07:25 +000011555 // If chain is alias then stop here.
11556 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011557 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011558 Aliases.push_back(Chain);
11559 } else {
11560 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011561 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011562 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011563 }
Jim Laskey6549d222006-10-05 15:07:25 +000011564 break;
11565 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011566
Jim Laskey6549d222006-10-05 15:07:25 +000011567 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011568 // We have to check each of the operands of the token factor for "small"
11569 // token factors, so we queue them up. Adding the operands to the queue
11570 // (stack) in reverse order maintains the original order and increases the
11571 // likelihood that getNode will find a matching token factor (CSE.)
11572 if (Chain.getNumOperands() > 16) {
11573 Aliases.push_back(Chain);
11574 break;
11575 }
Jim Laskey6549d222006-10-05 15:07:25 +000011576 for (unsigned n = Chain.getNumOperands(); n;)
11577 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011578 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011579 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011580
Jim Laskey6549d222006-10-05 15:07:25 +000011581 default:
11582 // For all other instructions we will just have to take what we can get.
11583 Aliases.push_back(Chain);
11584 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011585 }
11586 }
Hal Finkel51a98382014-01-24 20:12:02 +000011587
11588 // We need to be careful here to also search for aliases through the
11589 // value operand of a store, etc. Consider the following situation:
11590 // Token1 = ...
11591 // L1 = load Token1, %52
11592 // S1 = store Token1, L1, %51
11593 // L2 = load Token1, %52+8
11594 // S2 = store Token1, L2, %51+8
11595 // Token2 = Token(S1, S2)
11596 // L3 = load Token2, %53
11597 // S3 = store Token2, L3, %52
11598 // L4 = load Token2, %53+8
11599 // S4 = store Token2, L4, %52+8
11600 // If we search for aliases of S3 (which loads address %52), and we look
11601 // only through the chain, then we'll miss the trivial dependence on L1
11602 // (which also loads from %52). We then might change all loads and
11603 // stores to use Token1 as their chain operand, which could result in
11604 // copying %53 into %52 before copying %52 into %51 (which should
11605 // happen first).
11606 //
11607 // The problem is, however, that searching for such data dependencies
11608 // can become expensive, and the cost is not directly related to the
11609 // chain depth. Instead, we'll rule out such configurations here by
11610 // insisting that we've visited all chain users (except for users
11611 // of the original chain, which is not necessary). When doing this,
11612 // we need to look through nodes we don't care about (otherwise, things
11613 // like register copies will interfere with trivial cases).
11614
11615 SmallVector<const SDNode *, 16> Worklist;
11616 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11617 IE = Visited.end(); I != IE; ++I)
11618 if (*I != OriginalChain.getNode())
11619 Worklist.push_back(*I);
11620
11621 while (!Worklist.empty()) {
11622 const SDNode *M = Worklist.pop_back_val();
11623
11624 // We have already visited M, and want to make sure we've visited any uses
11625 // of M that we care about. For uses that we've not visisted, and don't
11626 // care about, queue them to the worklist.
11627
11628 for (SDNode::use_iterator UI = M->use_begin(),
11629 UIE = M->use_end(); UI != UIE; ++UI)
11630 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11631 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11632 // We've not visited this use, and we care about it (it could have an
11633 // ordering dependency with the original node).
11634 Aliases.clear();
11635 Aliases.push_back(OriginalChain);
11636 return;
11637 }
11638
11639 // We've not visited this use, but we don't care about it. Mark it as
11640 // visited and enqueue it to the worklist.
11641 Worklist.push_back(*UI);
11642 }
11643 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011644}
11645
11646/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11647/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011648SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11649 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011650
Jim Laskey708d0db2006-10-04 16:53:27 +000011651 // Accumulate all the aliases to this node.
11652 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011653
Dan Gohman4298df62011-05-17 22:20:36 +000011654 // If no operands then chain to entry token.
11655 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011656 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011657
11658 // If a single operand then chain to it. We don't need to revisit it.
11659 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011660 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011661
Jim Laskey708d0db2006-10-04 16:53:27 +000011662 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011663 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011664}
11665
Nate Begeman21158fc2005-09-01 00:19:25 +000011666// SelectionDAG::Combine - This is the entry point for the file.
11667//
Bill Wendling084669a2009-04-29 00:15:41 +000011668void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011669 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011670 /// run - This is the main entry point to this class.
11671 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011672 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011673}