blob: 849508891d3846a7f2e8df4eaff37a7b81934a4c [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"
Chandler Carruthd9903882015-01-14 11:23:27 +000020#include "llvm/ADT/SetVector.h"
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000021#include "llvm/ADT/SmallBitVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000032#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000034#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043#define DEBUG_TYPE "dagcombine"
44
Chris Lattneraee775a2006-12-19 22:41:21 +000045STATISTIC(NodesCombined , "Number of dag nodes combined");
46STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000048STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000049STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000050STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000051
Nate Begeman21158fc2005-09-01 00:19:25 +000052namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000053 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000054 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000055 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000056
Jim Laskey55e4dca2006-10-18 19:08:31 +000057 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000059 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000060
Hal Finkeldbebb522014-01-25 19:24:54 +000061 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000062 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000063 cl::desc("Enable DAG combiner's use of TBAA"));
64
Hal Finkel9b2617a2014-01-25 17:32:39 +000065#ifndef NDEBUG
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
69 " function"));
70#endif
71
Quentin Colombetde0e0622013-10-11 18:29:42 +000072 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
74 static cl::opt<bool>
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
77 "slicing"),
78 cl::init(false));
79
Hal Finkel51e6fa22014-09-02 06:24:04 +000080 static cl::opt<bool>
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
83
Jim Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
Chandler Carruth9a0051c2014-07-23 07:08:53 +000095 /// \brief Worklist of all of the nodes that need to be simplified.
96 ///
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
99 ///
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
103
104 /// \brief Mapping from an SDNode to its position on the worklist.
105 ///
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000110
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000111 /// \brief Set of nodes which have been combined (at least once).
112 ///
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
116
Jim Laskeydcb2b832006-10-16 20:52:31 +0000117 // AA - Used for DAG load/store alias analysis.
118 AliasAnalysis &AA;
119
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000123 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000124 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000125 }
126
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000127 /// Call the node-specific routine that folds each particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000128 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000129
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000130 public:
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000131 /// Add to the worklist making sure its instance is at the back (next to be
132 /// processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000133 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
137 return;
138
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000141 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000142
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000143 /// Remove all instances of N from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000144 void removeFromWorklist(SDNode *N) {
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000145 CombinedNodes.erase(N);
146
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
150
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000155
Chandler Carruth18066972014-08-02 10:02:07 +0000156 void deleteAndRecombine(SDNode *N);
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000157 bool recursivelyDeleteUnusedNodes(SDNode *N);
158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000160 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000161
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000163 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000164 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000167 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000168 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000169 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000170 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000171
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000173
174 private:
175
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000179 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000182 return SimplifyDemandedBits(Op, Demanded);
183 }
184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000186
Chris Lattnerffad2162006-11-11 00:39:41 +0000187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
Hal Finkel51e6fa22014-09-02 06:24:04 +0000189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000190 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000191
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193 /// load.
194 ///
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000206 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000207 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000210
Craig Toppere0b71182013-07-13 07:43:40 +0000211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000213 ISD::NodeType ExtType);
214
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000215 /// Call the node-specific routine that knows how to fold each
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000218 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000219
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
222 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000226 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000232 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000234 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000252 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000256 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000257 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000259 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000263 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000271 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000276 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000279 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
Matt Arsenault7c936902014-10-21 23:01:01 +0000293 SDValue visitFMINNUM(SDNode *N);
294 SDValue visitFMAXNUM(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000295 SDValue visitBRCOND(SDNode *N);
296 SDValue visitBR_CC(SDNode *N);
297 SDValue visitLOAD(SDNode *N);
298 SDValue visitSTORE(SDNode *N);
299 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301 SDValue visitBUILD_VECTOR(SDNode *N);
302 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000304 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000305 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +0000306 SDValue visitMLOAD(SDNode *N);
307 SDValue visitMSTORE(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000308
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000309 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000311
Matt Arsenault985b9de2014-03-17 18:58:01 +0000312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000313
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000318 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000319 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000321 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000322
323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
324 SDValue &CC) const;
325 bool isOneUseSetCC(SDValue N) const;
326
Scott Michelcf0da6c2009-02-17 22:15:04 +0000327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000328 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000330 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000331 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000332 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000333 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000334 SDValue BuildReciprocalEstimate(SDValue Op);
335 SDValue BuildRsqrtEstimate(SDValue Op);
Sanjay Patel957efc232014-10-24 17:02:16 +0000336 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000338 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339 bool DemandHighBits = true);
340 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000341 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342 SDValue InnerPos, SDValue InnerNeg,
343 unsigned PosOpcode, unsigned NegOpcode,
344 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000345 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000346 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000347 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000348 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000349 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000350 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000351
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000352 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000353
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000354 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000355 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000356 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000357 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000358
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000359 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000360 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000361
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000362 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000364 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000365
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000366 /// Merge consecutive store operations into a wide store.
367 /// This optimization uses wide integers or vectors when possible.
368 /// \return True if some memory operations were changed.
369 bool MergeConsecutiveStores(StoreSDNode *N);
370
Adam Nemet67483892014-03-04 23:28:31 +0000371 /// \brief Try to transform a truncation where C is a constant:
372 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
373 ///
374 /// \p N needs to be a truncation and its first operand an AND. Other
375 /// requirements are checked by the function (e.g. that trunc is
376 /// single-use) and if missed an empty SDValue is returned.
377 SDValue distributeTruncateThroughAnd(SDNode *N);
378
Chris Lattner4041ab62010-04-15 04:48:01 +0000379 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000380 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000381 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383 AttributeSet FnAttrs =
384 DAG.getMachineFunction().getFunction()->getAttributes();
385 ForCodeSize =
386 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387 Attribute::OptimizeForSize) ||
388 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
389 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000390
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000391 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000392 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000393
Chris Lattner4041ab62010-04-15 04:48:01 +0000394 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000395
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000396 /// Returns a type large enough to hold any valid shift amount - before type
397 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000398 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000399 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400 if (LHSTy.isVector())
401 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000402 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000404 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000405
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000406 /// This method returns true if we are running before type legalization or
407 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000408 bool isTypeLegal(const EVT &VT) {
409 if (!LegalTypes) return true;
410 return TLI.isTypeLegal(VT);
411 }
Matt Arsenault758659232013-05-18 00:21:46 +0000412
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000413 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000414 EVT getSetCCResultType(EVT VT) const {
415 return TLI.getSetCCResultType(*DAG.getContext(), VT);
416 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000417 };
418}
419
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000420
421namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000422/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000423/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000424class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000425 DAGCombiner &DC;
426public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000427 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000428 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000429
Craig Topper7b883b32014-03-08 06:31:39 +0000430 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000431 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000432 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000433};
434}
435
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000436//===----------------------------------------------------------------------===//
437// TargetLowering::DAGCombinerInfo implementation
438//===----------------------------------------------------------------------===//
439
440void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000441 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000442}
443
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000444void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000445 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000446}
447
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000448SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000449CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000451}
452
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000453SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000454CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000456}
457
458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000459SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000460CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000462}
463
Dan Gohmane58ab792009-01-29 01:59:02 +0000464void TargetLowering::DAGCombinerInfo::
465CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
467}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000468
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000469//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000470// Helper Functions
471//===----------------------------------------------------------------------===//
472
Chandler Carruth18066972014-08-02 10:02:07 +0000473void DAGCombiner::deleteAndRecombine(SDNode *N) {
474 removeFromWorklist(N);
475
476 // If the operands of this node are only used by the node, they will now be
477 // dead. Make sure to re-visit them and recursively delete dead nodes.
478 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000479 // For an operand generating multiple values, one of the values may
480 // become dead allowing further simplification (e.g. split index
481 // arithmetic from an indexed load).
482 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000483 AddToWorklist(Op.getNode());
484
485 DAG.DeleteNode(N);
486}
487
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000488/// Return 1 if we can compute the negated form of the specified expression for
489/// the same cost as the expression itself, or 2 if we can compute the negated
490/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000491static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000492 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000493 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000494 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000495 // fneg is removable even if it has multiple uses.
496 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000497
Chris Lattnere49c9742007-05-14 22:04:50 +0000498 // Don't allow anything with multiple uses.
499 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000500
Chris Lattner46980832007-05-25 02:19:06 +0000501 // Don't recurse exponentially.
502 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000503
Chris Lattnere49c9742007-05-14 22:04:50 +0000504 switch (Op.getOpcode()) {
505 default: return false;
506 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000507 // Don't invert constant FP values after legalize. The negated constant
508 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000509 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000510 case ISD::FADD:
511 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000512 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000513
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000514 // After operation legalization, it might not be legal to create new FSUBs.
515 if (LegalOperations &&
516 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
517 return 0;
518
Craig Topper03f39772012-09-09 22:58:45 +0000519 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000520 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000523 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000524 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000525 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000526 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000527 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000528 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000529
Bill Wendling6fbf5492009-01-30 23:10:18 +0000530 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000531 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000532
Chris Lattnere49c9742007-05-14 22:04:50 +0000533 case ISD::FMUL:
534 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000535 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000536
Bill Wendling6fbf5492009-01-30 23:10:18 +0000537 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000538 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
539 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000540 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000541
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000542 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000543 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000544
Chris Lattnere49c9742007-05-14 22:04:50 +0000545 case ISD::FP_EXTEND:
546 case ISD::FP_ROUND:
547 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000548 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000549 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000550 }
551}
552
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000553/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000554static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000555 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000556 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000557 // fneg is removable even if it has multiple uses.
558 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000559
Chris Lattnere49c9742007-05-14 22:04:50 +0000560 // Don't allow anything with multiple uses.
561 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562
Chris Lattner46980832007-05-25 02:19:06 +0000563 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000564 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000565 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000566 case ISD::ConstantFP: {
567 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
568 V.changeSign();
569 return DAG.getConstantFP(V, Op.getValueType());
570 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000571 case ISD::FADD:
572 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000573 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000574
Bill Wendling6fbf5492009-01-30 23:10:18 +0000575 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000576 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000577 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000578 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000580 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000581 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000582 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000583 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000584 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000585 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000586 Op.getOperand(0));
587 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000588 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000589 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000590
Bill Wendling6fbf5492009-01-30 23:10:18 +0000591 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000592 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000593 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000594 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000595
Bill Wendling6fbf5492009-01-30 23:10:18 +0000596 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000597 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000598 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000599
Chris Lattnere49c9742007-05-14 22:04:50 +0000600 case ISD::FMUL:
601 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000602 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000603
Bill Wendling6fbf5492009-01-30 23:10:18 +0000604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000605 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000606 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000607 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000608 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000609 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000610 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000611
Bill Wendling6fbf5492009-01-30 23:10:18 +0000612 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000613 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000614 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000615 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000616 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000617
Chris Lattnere49c9742007-05-14 22:04:50 +0000618 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000619 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000620 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000621 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000622 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000623 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000624 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000625 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000626 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000627 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000628 }
629}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000630
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000631// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000632// that selects between the target values used for true and false, making it
633// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634// the appropriate nodes based on the type of node we are checking. This
635// simplifies life a bit for the callers.
636bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
637 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000638 if (N.getOpcode() == ISD::SETCC) {
639 LHS = N.getOperand(0);
640 RHS = N.getOperand(1);
641 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000642 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000643 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000644
645 if (N.getOpcode() != ISD::SELECT_CC ||
646 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
648 return false;
649
Oliver Stannardd29db9b2014-11-17 10:49:31 +0000650 if (TLI.getBooleanContents(N.getValueType()) ==
651 TargetLowering::UndefinedBooleanContent)
652 return false;
653
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000654 LHS = N.getOperand(0);
655 RHS = N.getOperand(1);
656 CC = N.getOperand(4);
657 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000658}
659
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000660/// Return true if this is a SetCC-equivalent operation with only one use.
661/// If this is true, it allows the users to invert the operation for free when
662/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000663bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000664 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000665 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000666 return true;
667 return false;
668}
669
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000670/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000671/// elements are all the same constant or undefined.
672static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
674 if (!C)
675 return false;
676
677 APInt SplatUndef;
678 unsigned SplatBitSize;
679 bool HasAnyUndefs;
680 EVT EltVT = N->getValueType(0).getVectorElementType();
681 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
682 HasAnyUndefs) &&
683 EltVT.getSizeInBits() >= SplatBitSize);
684}
685
686// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000687static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688 if (isa<ConstantSDNode>(N))
689 return N.getNode();
690 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000691 if (BV && BV->isConstant())
Juergen Ributzka68402822014-01-13 21:49:25 +0000692 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000693 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000694}
695
Matt Arsenault985b9de2014-03-17 18:58:01 +0000696// \brief Returns the SDNode if it is a constant splat BuildVector or constant
697// int.
698static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
700 return CN;
701
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000702 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000703 BitVector UndefElements;
704 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000705
706 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000707 // FIXME: We blindly ignore splats which include undef which is overly
708 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000709 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000710 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000711 return CN;
712 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000713
714 return nullptr;
715}
716
Matt Arsenault6cc00422014-08-16 10:14:19 +0000717// \brief Returns the SDNode if it is a constant splat BuildVector or constant
718// float.
719static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
721 return CN;
722
723 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724 BitVector UndefElements;
725 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
726
Matt Arsenault965de302014-09-02 18:33:51 +0000727 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000728 return CN;
729 }
730
731 return nullptr;
732}
733
Andrew Trickef9de2a2013-05-25 02:42:55 +0000734SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000735 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000736 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000737 if (N0.getOpcode() == Opc) {
738 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000741 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
742 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
743 return SDValue();
Juergen Ributzka73844052014-01-13 20:51:35 +0000744 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000745 if (N0.hasOneUse()) {
746 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
747 // use
748 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
749 if (!OpNode.getNode())
750 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000751 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000752 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000753 }
754 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000755 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000756
Juergen Ributzka68402822014-01-13 21:49:25 +0000757 if (N1.getOpcode() == Opc) {
758 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
759 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
760 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000761 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
762 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
763 return SDValue();
Juergen Ributzka68402822014-01-13 21:49:25 +0000764 }
765 if (N1.hasOneUse()) {
766 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
767 // use
768 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
769 if (!OpNode.getNode())
770 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000771 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000772 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000774 }
775 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000776
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000777 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000778}
779
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000780SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
781 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000782 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
783 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000784 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000785 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000786 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000787 To[0].getNode()->dump(&DAG);
Mehdi Aminid3892082014-12-23 18:59:02 +0000788 dbgs() << " and " << NumTo-1 << " other values\n");
789 for (unsigned i = 0, e = NumTo; i != e; ++i)
790 assert((!To[i].getNode() ||
791 N->getValueType(i) == To[i].getValueType()) &&
792 "Cannot combine value to value of different type!");
793
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000794 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000795 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000796 if (AddTo) {
797 // Push the new nodes and any users onto the worklist
798 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000799 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000800 AddToWorklist(To[i].getNode());
801 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000802 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000803 }
804 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000805
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000806 // Finally, if the node is now dead, remove it from the graph. The node
807 // may not be dead if the replacement process recursively simplified to
808 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000809 if (N->use_empty())
810 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000811 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000812}
813
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000814void DAGCombiner::
815CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000816 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000817 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000818 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000819 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000820
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000821 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000822 AddToWorklist(TLO.New.getNode());
823 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000824
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000825 // Finally, if the node is now dead, remove it from the graph. The node
826 // may not be dead if the replacement process recursively simplified to
827 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000828 if (TLO.Old.getNode()->use_empty())
829 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000830}
831
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000832/// Check the specified integer node value to see if it can be simplified or if
833/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000834bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000835 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000836 APInt KnownZero, KnownOne;
837 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
838 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000839
Dan Gohmane58ab792009-01-29 01:59:02 +0000840 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000841 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000842
Dan Gohmane58ab792009-01-29 01:59:02 +0000843 // Replace the old value with the new one.
844 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000845 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000846 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000847 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000848 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000849 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000850
Dan Gohmane58ab792009-01-29 01:59:02 +0000851 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000852 return true;
853}
854
Evan Cheng0abb54d2010-04-24 04:43:44 +0000855void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000856 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000857 EVT VT = Load->getValueType(0);
858 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000859
Evan Cheng0abb54d2010-04-24 04:43:44 +0000860 DEBUG(dbgs() << "\nReplacing.9 ";
861 Load->dump(&DAG);
862 dbgs() << "\nWith: ";
863 Trunc.getNode()->dump(&DAG);
864 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000865 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000866 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
867 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000868 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000869 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000870}
871
872SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
873 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000874 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000875 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000876 EVT MemVT = LD->getMemoryVT();
877 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000878 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
879 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000880 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000881 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000882 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000883 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000884 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000885 }
886
Evan Chenge19aa5c2010-04-19 19:29:22 +0000887 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000888 switch (Opc) {
889 default: break;
890 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000891 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000892 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000893 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000894 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000895 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000896 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000897 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000898 case ISD::Constant: {
899 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000900 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000901 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000902 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000903 }
904
905 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000906 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000907 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000908}
909
Evan Cheng0abb54d2010-04-24 04:43:44 +0000910SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000911 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
912 return SDValue();
913 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000914 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000915 bool Replace = false;
916 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000917 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000918 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000919 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000920
921 if (Replace)
922 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
923 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000924 DAG.getValueType(OldVT));
925}
926
Evan Cheng0abb54d2010-04-24 04:43:44 +0000927SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000928 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000929 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000930 bool Replace = false;
931 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000932 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000933 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000934 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000935
936 if (Replace)
937 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
938 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000939}
940
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000941/// Promote the specified integer binary operation if the target indicates it is
942/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
943/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000944SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
945 if (!LegalOperations)
946 return SDValue();
947
948 EVT VT = Op.getValueType();
949 if (VT.isVector() || !VT.isInteger())
950 return SDValue();
951
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000952 // If operation type is 'undesirable', e.g. i16 on x86, consider
953 // promoting it.
954 unsigned Opc = Op.getOpcode();
955 if (TLI.isTypeDesirableForOp(Opc, VT))
956 return SDValue();
957
Evan Chengaf56fac2010-04-16 06:14:10 +0000958 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000959 // Consult target whether it is a good idea to promote this operation and
960 // what's the right type to promote it to.
961 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000962 assert(PVT != VT && "Don't know what type to promote to!");
963
Evan Cheng0abb54d2010-04-24 04:43:44 +0000964 bool Replace0 = false;
965 SDValue N0 = Op.getOperand(0);
966 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000967 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000968 return SDValue();
969
Evan Cheng0abb54d2010-04-24 04:43:44 +0000970 bool Replace1 = false;
971 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000972 SDValue NN1;
973 if (N0 == N1)
974 NN1 = NN0;
975 else {
976 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000977 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000978 return SDValue();
979 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000980
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000981 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000982 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000983 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000984
985 if (Replace0)
986 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
987 if (Replace1)
988 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000989
Evan Chenge8136902010-04-27 19:48:13 +0000990 DEBUG(dbgs() << "\nPromoting ";
991 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000992 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000993 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000994 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000995 }
996 return SDValue();
997}
998
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000999/// Promote the specified integer shift operation if the target indicates it is
1000/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1001/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +00001002SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1003 if (!LegalOperations)
1004 return SDValue();
1005
1006 EVT VT = Op.getValueType();
1007 if (VT.isVector() || !VT.isInteger())
1008 return SDValue();
1009
1010 // If operation type is 'undesirable', e.g. i16 on x86, consider
1011 // promoting it.
1012 unsigned Opc = Op.getOpcode();
1013 if (TLI.isTypeDesirableForOp(Opc, VT))
1014 return SDValue();
1015
1016 EVT PVT = VT;
1017 // Consult target whether it is a good idea to promote this operation and
1018 // what's the right type to promote it to.
1019 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1020 assert(PVT != VT && "Don't know what type to promote to!");
1021
Evan Cheng0abb54d2010-04-24 04:43:44 +00001022 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001023 SDValue N0 = Op.getOperand(0);
1024 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001025 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001026 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001027 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001028 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001029 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001030 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001031 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001032
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001033 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001034 if (Replace)
1035 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001036
Evan Chenge8136902010-04-27 19:48:13 +00001037 DEBUG(dbgs() << "\nPromoting ";
1038 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001039 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001040 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001041 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001042 }
1043 return SDValue();
1044}
1045
Evan Chenge19aa5c2010-04-19 19:29:22 +00001046SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1047 if (!LegalOperations)
1048 return SDValue();
1049
1050 EVT VT = Op.getValueType();
1051 if (VT.isVector() || !VT.isInteger())
1052 return SDValue();
1053
1054 // If operation type is 'undesirable', e.g. i16 on x86, consider
1055 // promoting it.
1056 unsigned Opc = Op.getOpcode();
1057 if (TLI.isTypeDesirableForOp(Opc, VT))
1058 return SDValue();
1059
1060 EVT PVT = VT;
1061 // Consult target whether it is a good idea to promote this operation and
1062 // what's the right type to promote it to.
1063 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1064 assert(PVT != VT && "Don't know what type to promote to!");
1065 // fold (aext (aext x)) -> (aext x)
1066 // fold (aext (zext x)) -> (zext x)
1067 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001068 DEBUG(dbgs() << "\nPromoting ";
1069 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001070 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001071 }
1072 return SDValue();
1073}
1074
1075bool DAGCombiner::PromoteLoad(SDValue Op) {
1076 if (!LegalOperations)
1077 return false;
1078
1079 EVT VT = Op.getValueType();
1080 if (VT.isVector() || !VT.isInteger())
1081 return false;
1082
1083 // If operation type is 'undesirable', e.g. i16 on x86, consider
1084 // promoting it.
1085 unsigned Opc = Op.getOpcode();
1086 if (TLI.isTypeDesirableForOp(Opc, VT))
1087 return false;
1088
1089 EVT PVT = VT;
1090 // Consult target whether it is a good idea to promote this operation and
1091 // what's the right type to promote it to.
1092 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1093 assert(PVT != VT && "Don't know what type to promote to!");
1094
Andrew Trickef9de2a2013-05-25 02:42:55 +00001095 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001096 SDNode *N = Op.getNode();
1097 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001098 EVT MemVT = LD->getMemoryVT();
1099 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00001100 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1101 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001102 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001103 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001104 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001105 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001106 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1107
Evan Cheng0abb54d2010-04-24 04:43:44 +00001108 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001109 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001110 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001111 Result.getNode()->dump(&DAG);
1112 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001113 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001114 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1115 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001116 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001117 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001118 return true;
1119 }
1120 return false;
1121}
1122
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001123/// \brief Recursively delete a node which has no uses and any operands for
1124/// which it is the only use.
1125///
1126/// Note that this both deletes the nodes and removes them from the worklist.
1127/// It also adds any nodes who have had a user deleted to the worklist as they
1128/// may now have only one use and subject to other combines.
1129bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1130 if (!N->use_empty())
1131 return false;
1132
1133 SmallSetVector<SDNode *, 16> Nodes;
1134 Nodes.insert(N);
1135 do {
1136 N = Nodes.pop_back_val();
1137 if (!N)
1138 continue;
1139
1140 if (N->use_empty()) {
1141 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1142 Nodes.insert(N->getOperand(i).getNode());
1143
1144 removeFromWorklist(N);
1145 DAG.DeleteNode(N);
1146 } else {
1147 AddToWorklist(N);
1148 }
1149 } while (!Nodes.empty());
1150 return true;
1151}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001152
Chris Lattnere49c9742007-05-14 22:04:50 +00001153//===----------------------------------------------------------------------===//
1154// Main DAG Combiner implementation
1155//===----------------------------------------------------------------------===//
1156
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001157void DAGCombiner::Run(CombineLevel AtLevel) {
1158 // set the instance variables, so that the various visit routines may use it.
1159 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001160 LegalOperations = Level >= AfterLegalizeVectorOps;
1161 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001162
Paul Robinsonad06e432014-11-03 18:19:26 +00001163 // Early exit if this basic block is in an optnone function.
1164 AttributeSet FnAttrs =
1165 DAG.getMachineFunction().getFunction()->getAttributes();
1166 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1167 Attribute::OptimizeNone))
1168 return;
1169
Evan Cheng5e7658c2008-08-29 22:21:44 +00001170 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001171 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1172 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001173 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001174
Evan Cheng5e7658c2008-08-29 22:21:44 +00001175 // Create a dummy node (which is not added to allnodes), that adds a reference
1176 // to the root node, preventing it from being deleted, and tracking any
1177 // changes of the root.
1178 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001179
James Molloy67b6b112012-02-16 09:17:04 +00001180 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001181 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001182 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001183 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001184 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001185 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001186 N = Worklist.pop_back_val();
1187 } while (!N);
1188
1189 bool GoodWorklistEntry = WorklistMap.erase(N);
1190 (void)GoodWorklistEntry;
1191 assert(GoodWorklistEntry &&
1192 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001193
Evan Cheng5e7658c2008-08-29 22:21:44 +00001194 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1195 // N is deleted from the DAG, since they too may now be dead or may have a
1196 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001197 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001198 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001199
1200 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001201
Chandler Carruth411fb402014-07-26 05:49:40 +00001202 // If this combine is running after legalizing the DAG, re-legalize any
1203 // nodes pulled off the worklist.
1204 if (Level == AfterLegalizeDAG) {
1205 SmallSetVector<SDNode *, 16> UpdatedNodes;
1206 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1207
1208 for (SDNode *LN : UpdatedNodes) {
1209 AddToWorklist(LN);
1210 AddUsersToWorklist(LN);
1211 }
1212 if (!NIsValid)
1213 continue;
1214 }
1215
Chandler Carruthb1432742014-07-28 17:55:07 +00001216 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1217
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001218 // Add any operands of the new node which have not yet been combined to the
1219 // worklist as well. Because the worklist uniques things already, this
1220 // won't repeatedly process the same operand.
1221 CombinedNodes.insert(N);
1222 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1223 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1224 AddToWorklist(N->getOperand(i).getNode());
1225
Evan Cheng5e7658c2008-08-29 22:21:44 +00001226 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001227
Craig Topperc0196b12014-04-14 00:51:57 +00001228 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001229 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001230
Evan Cheng5e7658c2008-08-29 22:21:44 +00001231 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001232
Evan Cheng5e7658c2008-08-29 22:21:44 +00001233 // If we get back the same node we passed in, rather than a new node or
1234 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001235 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001236 // mechanics for us, we have no work to do in this case.
1237 if (RV.getNode() == N)
1238 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001239
Evan Cheng5e7658c2008-08-29 22:21:44 +00001240 assert(N->getOpcode() != ISD::DELETED_NODE &&
1241 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1242 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001243
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001244 DEBUG(dbgs() << " ... into: ";
1245 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001246
Devang Patelefec7712011-05-23 22:04:42 +00001247 // Transfer debug value.
1248 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001249 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001250 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001251 else {
1252 assert(N->getValueType(0) == RV.getValueType() &&
1253 N->getNumValues() == 1 && "Type mismatch");
1254 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001255 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001256 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001257
Evan Cheng5e7658c2008-08-29 22:21:44 +00001258 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001259 AddToWorklist(RV.getNode());
1260 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001261
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001262 // Finally, if the node is now dead, remove it from the graph. The node
1263 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001264 // something else needing this node. This will also take care of adding any
1265 // operands which have lost a user to the worklist.
1266 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001267 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001268
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001269 // If the root changed (e.g. it was a dead load, update the root).
1270 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001271 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001272}
1273
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001274SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001275 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001276 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001277 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001278 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001279 case ISD::ADD: return visitADD(N);
1280 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001281 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001282 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001283 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001284 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001285 case ISD::MUL: return visitMUL(N);
1286 case ISD::SDIV: return visitSDIV(N);
1287 case ISD::UDIV: return visitUDIV(N);
1288 case ISD::SREM: return visitSREM(N);
1289 case ISD::UREM: return visitUREM(N);
1290 case ISD::MULHU: return visitMULHU(N);
1291 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001292 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1293 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001294 case ISD::SMULO: return visitSMULO(N);
1295 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001296 case ISD::SDIVREM: return visitSDIVREM(N);
1297 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001298 case ISD::AND: return visitAND(N);
1299 case ISD::OR: return visitOR(N);
1300 case ISD::XOR: return visitXOR(N);
1301 case ISD::SHL: return visitSHL(N);
1302 case ISD::SRA: return visitSRA(N);
1303 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001304 case ISD::ROTR:
1305 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001306 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001307 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001308 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001309 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001310 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001311 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001312 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001313 case ISD::SELECT_CC: return visitSELECT_CC(N);
1314 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001315 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1316 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001317 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001318 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1319 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001320 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001321 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001322 case ISD::FADD: return visitFADD(N);
1323 case ISD::FSUB: return visitFSUB(N);
1324 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001325 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001326 case ISD::FDIV: return visitFDIV(N);
1327 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001328 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001329 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001330 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1331 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1332 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1333 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1334 case ISD::FP_ROUND: return visitFP_ROUND(N);
1335 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1336 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1337 case ISD::FNEG: return visitFNEG(N);
1338 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001339 case ISD::FFLOOR: return visitFFLOOR(N);
Matt Arsenault7c936902014-10-21 23:01:01 +00001340 case ISD::FMINNUM: return visitFMINNUM(N);
1341 case ISD::FMAXNUM: return visitFMAXNUM(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001342 case ISD::FCEIL: return visitFCEIL(N);
1343 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001344 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001345 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001346 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001347 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001348 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001349 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001350 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1351 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001352 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001353 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001354 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001355 case ISD::MLOAD: return visitMLOAD(N);
1356 case ISD::MSTORE: return visitMSTORE(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001357 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001358 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001359}
1360
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001361SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001362 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001363
1364 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001365 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001366 assert(N->getOpcode() != ISD::DELETED_NODE &&
1367 "Node was deleted but visit returned NULL!");
1368
1369 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1370 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1371
1372 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001373 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001374 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001375
1376 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1377 }
1378 }
1379
Evan Chengf1005572010-04-28 07:10:39 +00001380 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001381 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001382 switch (N->getOpcode()) {
1383 default: break;
1384 case ISD::ADD:
1385 case ISD::SUB:
1386 case ISD::MUL:
1387 case ISD::AND:
1388 case ISD::OR:
1389 case ISD::XOR:
1390 RV = PromoteIntBinOp(SDValue(N, 0));
1391 break;
1392 case ISD::SHL:
1393 case ISD::SRA:
1394 case ISD::SRL:
1395 RV = PromoteIntShiftOp(SDValue(N, 0));
1396 break;
1397 case ISD::SIGN_EXTEND:
1398 case ISD::ZERO_EXTEND:
1399 case ISD::ANY_EXTEND:
1400 RV = PromoteExtend(SDValue(N, 0));
1401 break;
1402 case ISD::LOAD:
1403 if (PromoteLoad(SDValue(N, 0)))
1404 RV = SDValue(N, 0);
1405 break;
1406 }
1407 }
1408
Scott Michelcf0da6c2009-02-17 22:15:04 +00001409 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001410 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001411 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001412 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001413 SDValue N0 = N->getOperand(0);
1414 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001415
Evan Cheng31604a62008-03-22 01:55:50 +00001416 // Constant operands are canonicalized to RHS.
1417 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001418 SDValue Ops[] = {N1, N0};
1419 SDNode *CSENode;
1420 if (const BinaryWithFlagsSDNode *BinNode =
1421 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1422 CSENode = DAG.getNodeIfExists(
1423 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1424 BinNode->hasNoSignedWrap(), BinNode->isExact());
1425 } else {
1426 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1427 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001428 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001429 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001430 }
1431 }
1432
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001433 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001434}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001435
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001436/// Given a node, return its input chain if it has one, otherwise return a null
1437/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001438static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001439 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001440 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001441 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001442 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001443 return N->getOperand(NumOps-1);
1444 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001445 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001446 return N->getOperand(i);
1447 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001448 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001449}
1450
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001451SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001452 // If N has two operands, where one has an input chain equal to the other,
1453 // the 'other' chain is redundant.
1454 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001455 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001456 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001457 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001458 return N->getOperand(1);
1459 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001460
Chris Lattner48fb92f2007-05-16 06:37:59 +00001461 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001462 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001463 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001464 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001465
Jim Laskey708d0db2006-10-04 16:53:27 +00001466 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001467 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001468
Jim Laskey0463e082006-10-07 23:37:56 +00001469 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001470 // encountered.
1471 for (unsigned i = 0; i < TFs.size(); ++i) {
1472 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001473
Jim Laskey708d0db2006-10-04 16:53:27 +00001474 // Check each of the operands.
1475 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001476 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001477
Jim Laskey708d0db2006-10-04 16:53:27 +00001478 switch (Op.getOpcode()) {
1479 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001480 // Entry tokens don't need to be added to the list. They are
1481 // rededundant.
1482 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001483 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001484
Jim Laskey708d0db2006-10-04 16:53:27 +00001485 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001486 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001487 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001488 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001489 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001490 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001491 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001492 Changed = true;
1493 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001494 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001495 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001496
Jim Laskey708d0db2006-10-04 16:53:27 +00001497 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001498 // Only add if it isn't already in the list.
David Blaikie70573dc2014-11-19 07:49:26 +00001499 if (SeenOps.insert(Op.getNode()).second)
Jim Laskey6549d222006-10-05 15:07:25 +00001500 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001501 else
1502 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001503 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001504 }
1505 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001506 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001507
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001508 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001509
1510 // If we've change things around then replace token factor.
1511 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001512 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001513 // The entry token is the only possible outcome.
1514 Result = DAG.getEntryNode();
1515 } else {
1516 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001517 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001518 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001519
Jim Laskeydcf983c2006-10-13 23:32:28 +00001520 // Don't add users to work list.
1521 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001522 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001523
Jim Laskey708d0db2006-10-04 16:53:27 +00001524 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001525}
1526
Chris Lattneree322b42008-02-13 07:25:05 +00001527/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001528SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001529 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001530 // Replacing results may cause a different MERGE_VALUES to suddenly
1531 // be CSE'd with N, and carry its uses with it. Iterate until no
1532 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001533 // First add the users of this node to the work list so that they
1534 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001535 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001536 do {
1537 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001538 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001539 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001540 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001541 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001542}
1543
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001544SDValue DAGCombiner::visitADD(SDNode *N) {
1545 SDValue N0 = N->getOperand(0);
1546 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001547 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1548 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001549 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001550
1551 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001552 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001553 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001554 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001555
1556 // fold (add x, 0) -> x, vector edition
1557 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1558 return N0;
1559 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1560 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001561 }
Bill Wendling0864a752008-12-10 22:36:00 +00001562
Dan Gohman06563a82007-07-03 14:03:57 +00001563 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001564 if (N0.getOpcode() == ISD::UNDEF)
1565 return N0;
1566 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001567 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001568 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001569 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001570 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001571 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001572 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001573 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001574 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001575 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001576 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001577 // fold (add Sym, c) -> Sym+c
1578 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001579 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001580 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001581 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001582 GA->getOffset() +
1583 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001584 // fold ((c1-A)+c2) -> (c1+c2)-A
1585 if (N1C && N0.getOpcode() == ISD::SUB)
1586 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001587 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001588 DAG.getConstant(N1C->getAPIntValue()+
1589 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001590 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001591 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001592 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001593 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001594 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001595 // fold ((0-A) + B) -> B-A
1596 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1597 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001598 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001599 // fold (A + (0-B)) -> A-B
1600 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1601 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001602 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001603 // fold (A+(B-A)) -> B
1604 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001605 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001606 // fold ((B-A)+A) -> B
1607 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1608 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001609 // fold (A+(B-(A+C))) to (B-C)
1610 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001611 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001612 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001613 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001614 // fold (A+(B-(C+A))) to (B-C)
1615 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001616 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001617 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001618 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001619 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001620 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1621 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001622 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001623 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001624 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001625
Dale Johannesen8c766702008-12-02 01:30:54 +00001626 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1627 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1628 SDValue N00 = N0.getOperand(0);
1629 SDValue N01 = N0.getOperand(1);
1630 SDValue N10 = N1.getOperand(0);
1631 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001632
1633 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001634 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1635 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1636 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001637 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001638
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001639 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1640 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001641
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001642 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001643 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001644 APInt LHSZero, LHSOne;
1645 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001646 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001647
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001648 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001649 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001650
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001651 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1652 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001653 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1654 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1655 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1656 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001657 }
1658 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001659
Dan Gohman954f4902010-01-19 23:30:49 +00001660 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1661 if (N1.getOpcode() == ISD::SHL &&
1662 N1.getOperand(0).getOpcode() == ISD::SUB)
1663 if (ConstantSDNode *C =
1664 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1665 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001666 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1667 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001668 N1.getOperand(0).getOperand(1),
1669 N1.getOperand(1)));
1670 if (N0.getOpcode() == ISD::SHL &&
1671 N0.getOperand(0).getOpcode() == ISD::SUB)
1672 if (ConstantSDNode *C =
1673 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1674 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001675 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1676 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001677 N0.getOperand(0).getOperand(1),
1678 N0.getOperand(1)));
1679
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001680 if (N1.getOpcode() == ISD::AND) {
1681 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001682 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001683 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1684 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001685
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001686 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1687 // and similar xforms where the inner op is either ~0 or 0.
1688 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001689 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001690 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1691 }
1692 }
1693
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001694 // add (sext i1), X -> sub X, (zext i1)
1695 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1696 N0.getOperand(0).getValueType() == MVT::i1 &&
1697 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001698 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001699 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1700 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1701 }
1702
Jan Veselyaf62cf42014-10-17 14:45:25 +00001703 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1704 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1705 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1706 if (TN->getVT() == MVT::i1) {
1707 SDLoc DL(N);
1708 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1709 DAG.getConstant(1, VT));
1710 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1711 }
1712 }
1713
Evan Chengf1005572010-04-28 07:10:39 +00001714 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001715}
1716
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001717SDValue DAGCombiner::visitADDC(SDNode *N) {
1718 SDValue N0 = N->getOperand(0);
1719 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001720 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1721 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001722 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001723
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001724 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001725 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001726 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001727 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001728 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001729
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001730 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001731 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001732 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001733
Chris Lattner47206662007-03-04 20:40:38 +00001734 // fold (addc x, 0) -> x + no carry out
1735 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001736 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001737 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001738
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001739 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001740 APInt LHSZero, LHSOne;
1741 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001742 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001743
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001744 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001745 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001746
Chris Lattner47206662007-03-04 20:40:38 +00001747 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1748 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001749 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001750 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001751 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001752 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001753 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001754
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001755 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001756}
1757
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001758SDValue DAGCombiner::visitADDE(SDNode *N) {
1759 SDValue N0 = N->getOperand(0);
1760 SDValue N1 = N->getOperand(1);
1761 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1763 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001764
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001765 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001766 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001767 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001768 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001769
Chris Lattner47206662007-03-04 20:40:38 +00001770 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001771 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001772 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001773
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001774 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001775}
1776
Eric Christophere5ca1e02011-02-16 04:50:12 +00001777// Since it may not be valid to emit a fold to zero for vector initializers
1778// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001779static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001780 SelectionDAG &DAG,
1781 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001782 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001783 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001784 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1785 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001786 return SDValue();
1787}
1788
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001789SDValue DAGCombiner::visitSUB(SDNode *N) {
1790 SDValue N0 = N->getOperand(0);
1791 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001794 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001795 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001796 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001797
Dan Gohmana8665142007-06-25 16:23:39 +00001798 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001799 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001800 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001801 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001802
1803 // fold (sub x, 0) -> x, vector edition
1804 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1805 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001806 }
Bill Wendling0864a752008-12-10 22:36:00 +00001807
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001808 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001809 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001810 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001811 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001812 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001813 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001814 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001815 // fold (sub x, c) -> (add x, -c)
1816 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001817 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001818 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001819 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1820 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001821 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001822 // fold A-(A-B) -> B
1823 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1824 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001825 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001826 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001827 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001828 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001829 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001830 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001831 // fold C2-(A+C1) -> (C2-C1)-A
1832 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001833 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1834 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001835 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001836 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001837 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001838 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001839 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001840 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1841 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001842 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001843 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001844 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001845 // fold ((A+(C+B))-B) -> A+C
1846 if (N0.getOpcode() == ISD::ADD &&
1847 N0.getOperand(1).getOpcode() == ISD::ADD &&
1848 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001849 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001850 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001851 // fold ((A-(B-C))-C) -> A-B
1852 if (N0.getOpcode() == ISD::SUB &&
1853 N0.getOperand(1).getOpcode() == ISD::SUB &&
1854 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001855 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001856 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001857
Dan Gohman06563a82007-07-03 14:03:57 +00001858 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001859 if (N0.getOpcode() == ISD::UNDEF)
1860 return N0;
1861 if (N1.getOpcode() == ISD::UNDEF)
1862 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001863
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001864 // If the relocation model supports it, consider symbol offsets.
1865 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001866 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001867 // fold (sub Sym, c) -> Sym-c
1868 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001869 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001870 GA->getOffset() -
1871 (uint64_t)N1C->getSExtValue());
1872 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1873 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1874 if (GA->getGlobal() == GB->getGlobal())
1875 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1876 VT);
1877 }
1878
Jan Veselyaf62cf42014-10-17 14:45:25 +00001879 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1880 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1881 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1882 if (TN->getVT() == MVT::i1) {
1883 SDLoc DL(N);
1884 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1885 DAG.getConstant(1, VT));
1886 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1887 }
1888 }
1889
Evan Chengf1005572010-04-28 07:10:39 +00001890 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001891}
1892
Craig Topper43a1bd62012-01-07 09:06:39 +00001893SDValue DAGCombiner::visitSUBC(SDNode *N) {
1894 SDValue N0 = N->getOperand(0);
1895 SDValue N1 = N->getOperand(1);
1896 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1897 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1898 EVT VT = N0.getValueType();
1899
1900 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001901 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001902 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1903 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001904 MVT::Glue));
1905
1906 // fold (subc x, x) -> 0 + no borrow
1907 if (N0 == N1)
1908 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001909 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001910 MVT::Glue));
1911
1912 // fold (subc x, 0) -> x + no borrow
1913 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001914 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001915 MVT::Glue));
1916
1917 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1918 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001919 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1920 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001921 MVT::Glue));
1922
1923 return SDValue();
1924}
1925
1926SDValue DAGCombiner::visitSUBE(SDNode *N) {
1927 SDValue N0 = N->getOperand(0);
1928 SDValue N1 = N->getOperand(1);
1929 SDValue CarryIn = N->getOperand(2);
1930
1931 // fold (sube x, y, false) -> (subc x, y)
1932 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001933 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001934
1935 return SDValue();
1936}
1937
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001938SDValue DAGCombiner::visitMUL(SDNode *N) {
1939 SDValue N0 = N->getOperand(0);
1940 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001941 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001942
Dan Gohman06563a82007-07-03 14:03:57 +00001943 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001944 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001945 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001946
1947 bool N0IsConst = false;
1948 bool N1IsConst = false;
1949 APInt ConstValue0, ConstValue1;
1950 // fold vector ops
1951 if (VT.isVector()) {
1952 SDValue FoldedVOp = SimplifyVBinOp(N);
1953 if (FoldedVOp.getNode()) return FoldedVOp;
1954
1955 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1956 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1957 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001958 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001959 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1960 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001961 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001962 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1963 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001964 }
1965
Nate Begeman21158fc2005-09-01 00:19:25 +00001966 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001967 if (N0IsConst && N1IsConst)
1968 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1969
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001970 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001971 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001972 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001973 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001974 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001975 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001976 // We require a splat of the entire scalar bit width for non-contiguous
1977 // bit patterns.
1978 bool IsFullSplat =
1979 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001980 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001981 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001982 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001983 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001984 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001985 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001986 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001987 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001988 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001989 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001990 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001991 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001992 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001993 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001994 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001995 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001996 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001997 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001998 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001999 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002000 DAG.getConstant(Log2Val,
2001 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00002002 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002003
2004 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00002005 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00002006 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002007 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2008 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002009 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002010 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002011 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002012 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002013 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002014 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002015
Chris Lattner324871e2006-03-01 03:44:24 +00002016 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2017 // use.
2018 {
Craig Topperc0196b12014-04-14 00:51:57 +00002019 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002020 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002021 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002022 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2023 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002024 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002025 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002026 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002027 isa<ConstantSDNode>(N1.getOperand(1)) &&
2028 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002029 Sh = N1; Y = N0;
2030 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002031
Gabor Greiff304a7a2008-08-28 21:40:38 +00002032 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002033 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002034 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002035 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002036 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002037 }
2038 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002039
Chris Lattnerf29f5202006-03-04 23:33:26 +00002040 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002041 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2042 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002044 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2045 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002046 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002047 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002048 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002049
Nate Begeman22e251a2006-02-03 06:46:56 +00002050 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002051 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002052 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002053 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002054
Evan Chengf1005572010-04-28 07:10:39 +00002055 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002056}
2057
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002058SDValue DAGCombiner::visitSDIV(SDNode *N) {
2059 SDValue N0 = N->getOperand(0);
2060 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002061 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2062 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002063 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002064
Dan Gohmana8665142007-06-25 16:23:39 +00002065 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002066 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002067 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002068 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002069 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002070
Nate Begeman21158fc2005-09-01 00:19:25 +00002071 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002072 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002073 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002074 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002075 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002076 return N0;
2077 // fold (sdiv X, -1) -> 0-X
2078 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002079 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002080 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002081 // If we know the sign bits of both operands are zero, strength reduce to a
2082 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002083 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002084 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002085 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002086 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002087 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002088
Nate Begeman57b35672006-02-17 07:26:20 +00002089 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002090 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2091 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002092 // If dividing by powers of two is cheap, then don't perform the following
2093 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002094 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002095 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002096
Chad Rosier17020f92014-07-23 14:57:52 +00002097 // Target-specific implementation of sdiv x, pow2.
2098 SDValue Res = BuildSDIVPow2(N);
2099 if (Res.getNode())
2100 return Res;
2101
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002102 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002103
Chris Lattner471627c2006-02-16 08:02:36 +00002104 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002105 SDValue SGN =
2106 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2107 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2108 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002109 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002110
Chris Lattner471627c2006-02-16 08:02:36 +00002111 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002112 SDValue SRL =
2113 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2114 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2115 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002116 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002117 AddToWorklist(SRL.getNode());
2118 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002119 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002120 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002121
Nate Begeman4dd38312005-10-21 00:02:42 +00002122 // If we're dividing by a positive value, we're done. Otherwise, we must
2123 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002124 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002125 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002126
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002127 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002128 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002129 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002130
Nate Begemanc6f067a2005-10-20 02:15:44 +00002131 // if integer divide is expensive and we satisfy the requirements, emit an
2132 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002133 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002134 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002135 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002136 }
Dan Gohmana8665142007-06-25 16:23:39 +00002137
Dan Gohman06563a82007-07-03 14:03:57 +00002138 // undef / X -> 0
2139 if (N0.getOpcode() == ISD::UNDEF)
2140 return DAG.getConstant(0, VT);
2141 // X / undef -> undef
2142 if (N1.getOpcode() == ISD::UNDEF)
2143 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002144
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002145 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002146}
2147
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002148SDValue DAGCombiner::visitUDIV(SDNode *N) {
2149 SDValue N0 = N->getOperand(0);
2150 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002151 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2152 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002153 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002154
Dan Gohmana8665142007-06-25 16:23:39 +00002155 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002156 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002157 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002158 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002159 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002160
Nate Begeman21158fc2005-09-01 00:19:25 +00002161 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002162 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002163 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002164 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002165 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002166 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002167 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002168 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002169 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002170 if (N1.getOpcode() == ISD::SHL) {
2171 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002172 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002173 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002174 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002175 N1.getOperand(1),
2176 DAG.getConstant(SHC->getAPIntValue()
2177 .logBase2(),
2178 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002179 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002180 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002181 }
2182 }
2183 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002184 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002185 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002186 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002187 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002188 }
Dan Gohmana8665142007-06-25 16:23:39 +00002189
Dan Gohman06563a82007-07-03 14:03:57 +00002190 // undef / X -> 0
2191 if (N0.getOpcode() == ISD::UNDEF)
2192 return DAG.getConstant(0, VT);
2193 // X / undef -> undef
2194 if (N1.getOpcode() == ISD::UNDEF)
2195 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002196
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002197 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002198}
2199
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002200SDValue DAGCombiner::visitSREM(SDNode *N) {
2201 SDValue N0 = N->getOperand(0);
2202 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002203 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2204 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002205 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002206
Nate Begeman21158fc2005-09-01 00:19:25 +00002207 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002208 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002209 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002210 // If we know the sign bits of both operands are zero, strength reduce to a
2211 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002212 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002213 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002214 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002215 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002216
Dan Gohman9a693412007-11-26 23:46:11 +00002217 // If X/C can be simplified by the division-by-constant logic, lower
2218 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002219 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002220 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002221 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002222 SDValue OptimizedDiv = combine(Div.getNode());
2223 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002224 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002225 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002226 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002227 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002228 return Sub;
2229 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002230 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002231
Dan Gohman06563a82007-07-03 14:03:57 +00002232 // undef % X -> 0
2233 if (N0.getOpcode() == ISD::UNDEF)
2234 return DAG.getConstant(0, VT);
2235 // X % undef -> undef
2236 if (N1.getOpcode() == ISD::UNDEF)
2237 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002238
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002239 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002240}
2241
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002242SDValue DAGCombiner::visitUREM(SDNode *N) {
2243 SDValue N0 = N->getOperand(0);
2244 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002245 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2246 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002247 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002248
Nate Begeman21158fc2005-09-01 00:19:25 +00002249 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002250 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002251 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002252 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002253 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002254 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002255 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002256 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2257 if (N1.getOpcode() == ISD::SHL) {
2258 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002259 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002260 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002261 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002262 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002263 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002264 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002265 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002266 }
2267 }
2268 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002269
Dan Gohman9a693412007-11-26 23:46:11 +00002270 // If X/C can be simplified by the division-by-constant logic, lower
2271 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002272 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002273 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002274 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002275 SDValue OptimizedDiv = combine(Div.getNode());
2276 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002277 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002278 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002279 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002280 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002281 return Sub;
2282 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002283 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002284
Dan Gohman06563a82007-07-03 14:03:57 +00002285 // undef % X -> 0
2286 if (N0.getOpcode() == ISD::UNDEF)
2287 return DAG.getConstant(0, VT);
2288 // X % undef -> undef
2289 if (N1.getOpcode() == ISD::UNDEF)
2290 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002291
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002292 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002293}
2294
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002295SDValue DAGCombiner::visitMULHS(SDNode *N) {
2296 SDValue N0 = N->getOperand(0);
2297 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002298 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002299 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002300 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002301
Nate Begeman21158fc2005-09-01 00:19:25 +00002302 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002303 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002304 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002305 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002306 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002307 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002308 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002309 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002310 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002311 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002312 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002313
Chris Lattner10bd29f2010-12-13 08:39:01 +00002314 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2315 // plus a shift.
2316 if (VT.isSimple() && !VT.isVector()) {
2317 MVT Simple = VT.getSimpleVT();
2318 unsigned SimpleSize = Simple.getSizeInBits();
2319 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2320 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2321 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2322 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2323 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002324 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002325 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002326 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2327 }
2328 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002329
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002330 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002331}
2332
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002333SDValue DAGCombiner::visitMULHU(SDNode *N) {
2334 SDValue N0 = N->getOperand(0);
2335 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002336 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002337 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002338 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002339
Nate Begeman21158fc2005-09-01 00:19:25 +00002340 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002341 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002342 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002343 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002344 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002345 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002346 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002347 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002348 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002349
Chris Lattner10bd29f2010-12-13 08:39:01 +00002350 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2351 // plus a shift.
2352 if (VT.isSimple() && !VT.isVector()) {
2353 MVT Simple = VT.getSimpleVT();
2354 unsigned SimpleSize = Simple.getSizeInBits();
2355 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2356 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2357 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2358 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2359 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2360 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002361 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002362 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2363 }
2364 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002365
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002366 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002367}
2368
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002369/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2370/// give the opcodes for the two computations that are being performed. Return
2371/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002372SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002373 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002374 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002375 bool HiExists = N->hasAnyUseOfValue(1);
2376 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002377 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002378 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002379 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002380 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002381 }
2382
2383 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002384 bool LoExists = N->hasAnyUseOfValue(0);
2385 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002386 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002387 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002388 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002389 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002390 }
2391
Evan Chengece4c682007-11-08 09:25:29 +00002392 // If both halves are used, return as it is.
2393 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002394 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002395
2396 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002397 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002398 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002399 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002400 SDValue LoOpt = combine(Lo.getNode());
2401 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002402 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002403 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002404 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002405 }
2406
Evan Chengece4c682007-11-08 09:25:29 +00002407 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002408 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002409 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002410 SDValue HiOpt = combine(Hi.getNode());
2411 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002412 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002413 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002414 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002415 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002416
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002417 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002418}
2419
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002420SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2421 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002422 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002423
Chris Lattner15090e12010-12-15 06:04:19 +00002424 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002425 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002426
2427 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2428 // plus a shift.
2429 if (VT.isSimple() && !VT.isVector()) {
2430 MVT Simple = VT.getSimpleVT();
2431 unsigned SimpleSize = Simple.getSizeInBits();
2432 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2433 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2434 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2435 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2436 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2437 // Compute the high part as N1.
2438 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002439 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002440 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2441 // Compute the low part as N0.
2442 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2443 return CombineTo(N, Lo, Hi);
2444 }
2445 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002446
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002447 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002448}
2449
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002450SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2451 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002452 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002453
Chris Lattner15090e12010-12-15 06:04:19 +00002454 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002455 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002456
Chris Lattner15090e12010-12-15 06:04:19 +00002457 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2458 // plus a shift.
2459 if (VT.isSimple() && !VT.isVector()) {
2460 MVT Simple = VT.getSimpleVT();
2461 unsigned SimpleSize = Simple.getSizeInBits();
2462 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2463 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2464 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2465 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2466 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2467 // Compute the high part as N1.
2468 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002469 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002470 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2471 // Compute the low part as N0.
2472 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2473 return CombineTo(N, Lo, Hi);
2474 }
2475 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002476
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002477 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002478}
2479
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002480SDValue DAGCombiner::visitSMULO(SDNode *N) {
2481 // (smulo x, 2) -> (saddo x, x)
2482 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2483 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002484 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002485 N->getOperand(0), N->getOperand(0));
2486
2487 return SDValue();
2488}
2489
2490SDValue DAGCombiner::visitUMULO(SDNode *N) {
2491 // (umulo x, 2) -> (uaddo x, x)
2492 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2493 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002494 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002495 N->getOperand(0), N->getOperand(0));
2496
2497 return SDValue();
2498}
2499
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002500SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2501 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002502 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002503
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002504 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002505}
2506
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002507SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2508 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002509 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002510
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002511 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002512}
2513
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002514/// If this is a binary operator with two operands of the same opcode, try to
2515/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002516SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2517 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002518 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002519 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002520
Dan Gohmandd5286d2010-01-14 03:08:49 +00002521 // Bail early if none of these transforms apply.
2522 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2523
Chris Lattner002ee912006-05-05 06:31:05 +00002524 // For each of OP in AND/OR/XOR:
2525 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2526 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2527 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002528 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002529 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002530 //
2531 // do not sink logical op inside of a vector extend, since it may combine
2532 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002533 EVT Op0VT = N0.getOperand(0).getValueType();
2534 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002535 N0.getOpcode() == ISD::SIGN_EXTEND ||
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002536 N0.getOpcode() == ISD::BSWAP ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002537 // Avoid infinite looping with PromoteIntBinOp.
2538 (N0.getOpcode() == ISD::ANY_EXTEND &&
2539 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002540 (N0.getOpcode() == ISD::TRUNCATE &&
2541 (!TLI.isZExtFree(VT, Op0VT) ||
2542 !TLI.isTruncateFree(Op0VT, VT)) &&
2543 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002544 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002545 Op0VT == N1.getOperand(0).getValueType() &&
2546 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002547 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002548 N0.getOperand(0).getValueType(),
2549 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002550 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002551 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002552 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002553
Chris Lattner5ac42932006-05-05 06:10:43 +00002554 // For each of OP in SHL/SRL/SRA/AND...
2555 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2556 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2557 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002558 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002559 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002560 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002561 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002562 N0.getOperand(0).getValueType(),
2563 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002564 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002565 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002566 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002567 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002568
Nadav Rotemb0783502012-04-01 19:31:22 +00002569 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2570 // Only perform this optimization after type legalization and before
2571 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2572 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2573 // we don't want to undo this promotion.
2574 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2575 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002576 if ((N0.getOpcode() == ISD::BITCAST ||
2577 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2578 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002579 SDValue In0 = N0.getOperand(0);
2580 SDValue In1 = N1.getOperand(0);
2581 EVT In0Ty = In0.getValueType();
2582 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002583 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002584 // If both incoming values are integers, and the original types are the
2585 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002586 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002587 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2588 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002589 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002590 return BC;
2591 }
2592 }
2593
2594 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2595 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2596 // If both shuffles use the same mask, and both shuffle within a single
2597 // vector, then it is worthwhile to move the swizzle after the operation.
2598 // The type-legalizer generates this pattern when loading illegal
2599 // vector types from memory. In many cases this allows additional shuffle
2600 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002601 // There are other cases where moving the shuffle after the xor/and/or
2602 // is profitable even if shuffles don't perform a swizzle.
2603 // If both shuffles use the same mask, and both shuffles have the same first
2604 // or second operand, then it might still be profitable to move the shuffle
2605 // after the xor/and/or operation.
2606 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002607 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2608 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002609
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002610 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002611 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002612
Nadav Rotemb0783502012-04-01 19:31:22 +00002613 // Check that both shuffles use the same mask. The masks are known to be of
2614 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002615 // Check also that shuffles have only one use to avoid introducing extra
2616 // instructions.
2617 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2618 SVN0->getMask().equals(SVN1->getMask())) {
2619 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002620
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002621 // Don't try to fold this node if it requires introducing a
2622 // build vector of all zeros that might be illegal at this stage.
2623 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2624 if (!LegalTypes)
2625 ShOp = DAG.getConstant(0, VT);
2626 else
2627 ShOp = SDValue();
2628 }
2629
2630 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2631 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2632 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2633 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2634 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2635 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002636 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002637 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2638 &SVN0->getMask()[0]);
2639 }
2640
2641 // Don't try to fold this node if it requires introducing a
2642 // build vector of all zeros that might be illegal at this stage.
2643 ShOp = N0->getOperand(0);
2644 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2645 if (!LegalTypes)
2646 ShOp = DAG.getConstant(0, VT);
2647 else
2648 ShOp = SDValue();
2649 }
2650
2651 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2652 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2653 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2654 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2655 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2656 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002657 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002658 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2659 &SVN0->getMask()[0]);
2660 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002661 }
2662 }
Craig Topper9c3da312012-04-09 07:19:09 +00002663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002664 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002665}
2666
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002667SDValue DAGCombiner::visitAND(SDNode *N) {
2668 SDValue N0 = N->getOperand(0);
2669 SDValue N1 = N->getOperand(1);
2670 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002671 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2672 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002673 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002674 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002675
Dan Gohmana8665142007-06-25 16:23:39 +00002676 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002677 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002678 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002679 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002680
2681 // fold (and x, 0) -> 0, vector edition
2682 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002683 // do not return N0, because undef node may exist in N0
2684 return DAG.getConstant(
2685 APInt::getNullValue(
2686 N0.getValueType().getScalarType().getSizeInBits()),
2687 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002688 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002689 // do not return N1, because undef node may exist in N1
2690 return DAG.getConstant(
2691 APInt::getNullValue(
2692 N1.getValueType().getScalarType().getSizeInBits()),
2693 N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002694
2695 // fold (and x, -1) -> x, vector edition
2696 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2697 return N1;
2698 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2699 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002700 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002701
Dan Gohman06563a82007-07-03 14:03:57 +00002702 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002703 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002704 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002705 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002706 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002707 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002708 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002709 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002710 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002711 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002712 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002713 return N0;
2714 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002715 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002716 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002717 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002718 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002719 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002720 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002721 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002722 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002723 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002724 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002725 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002726 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002727 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2728 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002729 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002730 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002731 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002732 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002733 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002734 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002735
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002736 // Replace uses of the AND with uses of the Zero extend node.
2737 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002738
Chris Lattner49beaf42006-02-02 07:17:31 +00002739 // We actually want to replace all uses of the any_extend with the
2740 // zero_extend, to avoid duplicating things. This will later cause this
2741 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002742 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002743 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002744 }
2745 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002746 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002747 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2748 // already be zero by virtue of the width of the base type of the load.
2749 //
2750 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2751 // more cases.
2752 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2753 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2754 N0.getOpcode() == ISD::LOAD) {
2755 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2756 N0 : N0.getOperand(0) );
2757
2758 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2759 // This can be a pure constant or a vector splat, in which case we treat the
2760 // vector as a scalar and use the splat value.
2761 APInt Constant = APInt::getNullValue(1);
2762 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2763 Constant = C->getAPIntValue();
2764 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2765 APInt SplatValue, SplatUndef;
2766 unsigned SplatBitSize;
2767 bool HasAnyUndefs;
2768 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2769 SplatBitSize, HasAnyUndefs);
2770 if (IsSplat) {
2771 // Undef bits can contribute to a possible optimisation if set, so
2772 // set them.
2773 SplatValue |= SplatUndef;
2774
2775 // The splat value may be something like "0x00FFFFFF", which means 0 for
2776 // the first vector value and FF for the rest, repeating. We need a mask
2777 // that will apply equally to all members of the vector, so AND all the
2778 // lanes of the constant together.
2779 EVT VT = Vector->getValueType(0);
2780 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002781
2782 // If the splat value has been compressed to a bitlength lower
2783 // than the size of the vector lane, we need to re-expand it to
2784 // the lane size.
2785 if (BitWidth > SplatBitSize)
2786 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2787 SplatBitSize < BitWidth;
2788 SplatBitSize = SplatBitSize * 2)
2789 SplatValue |= SplatValue.shl(SplatBitSize);
2790
James Molloy862fe492012-02-20 12:02:38 +00002791 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002792 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002793 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2794 }
2795 }
2796
2797 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2798 // actually legal and isn't going to get expanded, else this is a false
2799 // optimisation.
2800 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002801 Load->getValueType(0),
James Molloy862fe492012-02-20 12:02:38 +00002802 Load->getMemoryVT());
2803
2804 // Resize the constant to the same size as the original memory access before
2805 // extension. If it is still the AllOnesValue then this AND is completely
2806 // unneeded.
2807 Constant =
2808 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2809
2810 bool B;
2811 switch (Load->getExtensionType()) {
2812 default: B = false; break;
2813 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2814 case ISD::ZEXTLOAD:
2815 case ISD::NON_EXTLOAD: B = true; break;
2816 }
2817
2818 if (B && Constant.isAllOnesValue()) {
2819 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2820 // preserve semantics once we get rid of the AND.
2821 SDValue NewLoad(Load, 0);
2822 if (Load->getExtensionType() == ISD::EXTLOAD) {
2823 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002824 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002825 Load->getChain(), Load->getBasePtr(),
2826 Load->getOffset(), Load->getMemoryVT(),
2827 Load->getMemOperand());
2828 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002829 if (Load->getNumValues() == 3) {
2830 // PRE/POST_INC loads have 3 values.
2831 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2832 NewLoad.getValue(2) };
2833 CombineTo(Load, To, 3, true);
2834 } else {
2835 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2836 }
James Molloy862fe492012-02-20 12:02:38 +00002837 }
2838
2839 // Fold the AND away, taking care not to fold to the old load node if we
2840 // replaced it.
2841 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2842
2843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2844 }
2845 }
Nate Begeman049b7482005-09-09 19:49:52 +00002846 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2847 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2848 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2849 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002850
Tom Stellard7783b0a2014-06-12 16:04:47 +00002851 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002852 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002853 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002854 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002855 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002856 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002857 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002858 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002859 }
Bill Wendling86171912009-01-30 20:43:18 +00002860 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002861 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002862 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002863 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002864 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002865 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002866 }
Bill Wendling86171912009-01-30 20:43:18 +00002867 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002868 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002869 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002870 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002871 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002872 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002873 }
2874 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002875 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2876 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2877 Op0 == Op1 && LL.getValueType().isInteger() &&
2878 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2879 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2880 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2881 cast<ConstantSDNode>(RR)->isNullValue()))) {
2882 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2883 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002884 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002885 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2886 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2887 }
Nate Begeman049b7482005-09-09 19:49:52 +00002888 // canonicalize equivalent to ll == rl
2889 if (LL == RR && LR == RL) {
2890 Op1 = ISD::getSetCCSwappedOperands(Op1);
2891 std::swap(RL, RR);
2892 }
2893 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002894 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002895 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002896 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002897 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002898 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2899 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002900 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002901 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002902 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002903 }
2904 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002905
Bill Wendling86171912009-01-30 20:43:18 +00002906 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002907 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002908 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002909 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002910 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002911
Nate Begemandc7bba92006-02-03 22:24:05 +00002912 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2913 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002914 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002915 SimplifyDemandedBits(SDValue(N, 0)))
2916 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002917
Nate Begeman02b23c62005-10-13 03:11:28 +00002918 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002919 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002920 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002921 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002922 // If we zero all the possible extended bits, then we can turn this into
2923 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002924 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002925 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002926 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002927 ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002928 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002929 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002930 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002931 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002932 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002933 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002934 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002935 }
2936 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002937 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002938 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002939 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002940 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002941 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002942 // If we zero all the possible extended bits, then we can turn this into
2943 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002944 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002945 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002946 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002947 ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002948 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002949 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002950 LN0->getChain(), LN0->getBasePtr(),
2951 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002952 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002953 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002954 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002955 }
2956 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002957
Chris Lattnerf0032b32006-02-28 06:49:37 +00002958 // fold (and (load x), 255) -> (zextload x, i8)
2959 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002960 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2961 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2962 (N0.getOpcode() == ISD::ANY_EXTEND &&
2963 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2964 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2965 LoadSDNode *LN0 = HasAnyExt
2966 ? cast<LoadSDNode>(N0.getOperand(0))
2967 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002968 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002969 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002970 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002971 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2972 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2973 EVT LoadedVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002974 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Duncan Sands93b66092008-06-09 11:32:28 +00002975
Evan Cheng166a4e62010-01-06 19:38:29 +00002976 if (ExtVT == LoadedVT &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002977 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2978 ExtVT))) {
Wesley Peck527da1b2010-11-23 03:31:01 +00002979
2980 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002981 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002982 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2983 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002984 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002985 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2986 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2987 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002988
Chris Lattner88de3842010-01-07 21:53:27 +00002989 // Do not change the width of a volatile load.
2990 // Do not generate loads of non-round integer types since these can
2991 // be expensive (and would be wrong if the type is not byte sized).
2992 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002993 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2994 ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002995 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002996
Chris Lattner88de3842010-01-07 21:53:27 +00002997 unsigned Alignment = LN0->getAlignment();
2998 SDValue NewPtr = LN0->getBasePtr();
2999
3000 // For big endian targets, we need to add an offset to the pointer
3001 // to load the correct bytes. For little endian systems, we merely
3002 // need to read fewer bytes from the same pointer.
3003 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00003004 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3005 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3006 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003007 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00003008 NewPtr, DAG.getConstant(PtrOff, PtrType));
3009 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00003010 }
Chris Lattner88de3842010-01-07 21:53:27 +00003011
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003012 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00003013
Chris Lattner88de3842010-01-07 21:53:27 +00003014 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003015 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00003016 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00003017 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00003018 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00003019 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003020 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003021 CombineTo(LN0, Load, Load.getValue(1));
3022 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003023 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003024 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003025 }
3026 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003027
Evan Chenge6a3b032012-07-17 18:54:11 +00003028 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3029 VT.getSizeInBits() <= 64) {
3030 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3031 APInt ADDC = ADDI->getAPIntValue();
3032 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3033 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3034 // immediate for an add, but it is legal if its top c2 bits are set,
3035 // transform the ADD so the immediate doesn't need to be materialized
3036 // in a register.
3037 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3038 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3039 SRLI->getZExtValue());
3040 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3041 ADDC |= Mask;
3042 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3043 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003044 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00003045 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3046 CombineTo(N0.getNode(), NewAdd);
3047 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3048 }
3049 }
3050 }
3051 }
3052 }
3053 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003054
Tim Northover819bfb52013-08-27 13:46:45 +00003055 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3056 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3057 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3058 N0.getOperand(1), false);
3059 if (BSwap.getNode())
3060 return BSwap;
3061 }
3062
Evan Chengf1005572010-04-28 07:10:39 +00003063 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003064}
3065
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003066/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003067SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3068 bool DemandHighBits) {
3069 if (!LegalOperations)
3070 return SDValue();
3071
3072 EVT VT = N->getValueType(0);
3073 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3074 return SDValue();
3075 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3076 return SDValue();
3077
3078 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3079 bool LookPassAnd0 = false;
3080 bool LookPassAnd1 = false;
3081 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3082 std::swap(N0, N1);
3083 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3084 std::swap(N0, N1);
3085 if (N0.getOpcode() == ISD::AND) {
3086 if (!N0.getNode()->hasOneUse())
3087 return SDValue();
3088 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3089 if (!N01C || N01C->getZExtValue() != 0xFF00)
3090 return SDValue();
3091 N0 = N0.getOperand(0);
3092 LookPassAnd0 = true;
3093 }
3094
3095 if (N1.getOpcode() == ISD::AND) {
3096 if (!N1.getNode()->hasOneUse())
3097 return SDValue();
3098 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3099 if (!N11C || N11C->getZExtValue() != 0xFF)
3100 return SDValue();
3101 N1 = N1.getOperand(0);
3102 LookPassAnd1 = true;
3103 }
3104
3105 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3106 std::swap(N0, N1);
3107 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3108 return SDValue();
3109 if (!N0.getNode()->hasOneUse() ||
3110 !N1.getNode()->hasOneUse())
3111 return SDValue();
3112
3113 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3115 if (!N01C || !N11C)
3116 return SDValue();
3117 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3118 return SDValue();
3119
3120 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3121 SDValue N00 = N0->getOperand(0);
3122 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3123 if (!N00.getNode()->hasOneUse())
3124 return SDValue();
3125 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3126 if (!N001C || N001C->getZExtValue() != 0xFF)
3127 return SDValue();
3128 N00 = N00.getOperand(0);
3129 LookPassAnd0 = true;
3130 }
3131
3132 SDValue N10 = N1->getOperand(0);
3133 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3134 if (!N10.getNode()->hasOneUse())
3135 return SDValue();
3136 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3137 if (!N101C || N101C->getZExtValue() != 0xFF00)
3138 return SDValue();
3139 N10 = N10.getOperand(0);
3140 LookPassAnd1 = true;
3141 }
3142
3143 if (N00 != N10)
3144 return SDValue();
3145
Tim Northover819bfb52013-08-27 13:46:45 +00003146 // Make sure everything beyond the low halfword gets set to zero since the SRL
3147 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003148 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003149 if (DemandHighBits && OpSizeInBits > 16) {
3150 // If the left-shift isn't masked out then the only way this is a bswap is
3151 // if all bits beyond the low 8 are 0. In that case the entire pattern
3152 // reduces to a left shift anyway: leave it for other parts of the combiner.
3153 if (!LookPassAnd0)
3154 return SDValue();
3155
3156 // However, if the right shift isn't masked out then it might be because
3157 // it's not needed. See if we can spot that too.
3158 if (!LookPassAnd1 &&
3159 !DAG.MaskedValueIsZero(
3160 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3161 return SDValue();
3162 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003163
Andrew Trickef9de2a2013-05-25 02:42:55 +00003164 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003165 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003166 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003167 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3168 return Res;
3169}
3170
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003171/// Return true if the specified node is an element that makes up a 32-bit
3172/// packed halfword byteswap.
3173/// ((x & 0x000000ff) << 8) |
3174/// ((x & 0x0000ff00) >> 8) |
3175/// ((x & 0x00ff0000) << 8) |
3176/// ((x & 0xff000000) >> 8)
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003177static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003178 if (!N.getNode()->hasOneUse())
3179 return false;
3180
3181 unsigned Opc = N.getOpcode();
3182 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3183 return false;
3184
3185 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3186 if (!N1C)
3187 return false;
3188
3189 unsigned Num;
3190 switch (N1C->getZExtValue()) {
3191 default:
3192 return false;
3193 case 0xFF: Num = 0; break;
3194 case 0xFF00: Num = 1; break;
3195 case 0xFF0000: Num = 2; break;
3196 case 0xFF000000: Num = 3; break;
3197 }
3198
3199 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3200 SDValue N0 = N.getOperand(0);
3201 if (Opc == ISD::AND) {
3202 if (Num == 0 || Num == 2) {
3203 // (x >> 8) & 0xff
3204 // (x >> 8) & 0xff0000
3205 if (N0.getOpcode() != ISD::SRL)
3206 return false;
3207 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3208 if (!C || C->getZExtValue() != 8)
3209 return false;
3210 } else {
3211 // (x << 8) & 0xff00
3212 // (x << 8) & 0xff000000
3213 if (N0.getOpcode() != ISD::SHL)
3214 return false;
3215 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3216 if (!C || C->getZExtValue() != 8)
3217 return false;
3218 }
3219 } else if (Opc == ISD::SHL) {
3220 // (x & 0xff) << 8
3221 // (x & 0xff0000) << 8
3222 if (Num != 0 && Num != 2)
3223 return false;
3224 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3225 if (!C || C->getZExtValue() != 8)
3226 return false;
3227 } else { // Opc == ISD::SRL
3228 // (x & 0xff00) >> 8
3229 // (x & 0xff000000) >> 8
3230 if (Num != 1 && Num != 3)
3231 return false;
3232 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3233 if (!C || C->getZExtValue() != 8)
3234 return false;
3235 }
3236
3237 if (Parts[Num])
3238 return false;
3239
3240 Parts[Num] = N0.getOperand(0).getNode();
3241 return true;
3242}
3243
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003244/// Match a 32-bit packed halfword bswap. That is
3245/// ((x & 0x000000ff) << 8) |
3246/// ((x & 0x0000ff00) >> 8) |
3247/// ((x & 0x00ff0000) << 8) |
3248/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003249/// => (rotl (bswap x), 16)
3250SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3251 if (!LegalOperations)
3252 return SDValue();
3253
3254 EVT VT = N->getValueType(0);
3255 if (VT != MVT::i32)
3256 return SDValue();
3257 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3258 return SDValue();
3259
Evan Cheng4c0bd962011-06-21 06:01:08 +00003260 // Look for either
3261 // (or (or (and), (and)), (or (and), (and)))
3262 // (or (or (or (and), (and)), (and)), (and))
3263 if (N0.getOpcode() != ISD::OR)
3264 return SDValue();
3265 SDValue N00 = N0.getOperand(0);
3266 SDValue N01 = N0.getOperand(1);
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003267 SDNode *Parts[4] = {};
Evan Cheng4c0bd962011-06-21 06:01:08 +00003268
Evan Chengbf0baa92012-12-13 01:34:32 +00003269 if (N1.getOpcode() == ISD::OR &&
3270 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003271 // (or (or (and), (and)), (or (and), (and)))
3272 SDValue N000 = N00.getOperand(0);
3273 if (!isBSwapHWordElement(N000, Parts))
3274 return SDValue();
3275
3276 SDValue N001 = N00.getOperand(1);
3277 if (!isBSwapHWordElement(N001, Parts))
3278 return SDValue();
3279 SDValue N010 = N01.getOperand(0);
3280 if (!isBSwapHWordElement(N010, Parts))
3281 return SDValue();
3282 SDValue N011 = N01.getOperand(1);
3283 if (!isBSwapHWordElement(N011, Parts))
3284 return SDValue();
3285 } else {
3286 // (or (or (or (and), (and)), (and)), (and))
3287 if (!isBSwapHWordElement(N1, Parts))
3288 return SDValue();
3289 if (!isBSwapHWordElement(N01, Parts))
3290 return SDValue();
3291 if (N00.getOpcode() != ISD::OR)
3292 return SDValue();
3293 SDValue N000 = N00.getOperand(0);
3294 if (!isBSwapHWordElement(N000, Parts))
3295 return SDValue();
3296 SDValue N001 = N00.getOperand(1);
3297 if (!isBSwapHWordElement(N001, Parts))
3298 return SDValue();
3299 }
3300
3301 // Make sure the parts are all coming from the same node.
3302 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3303 return SDValue();
3304
Andrew Trickef9de2a2013-05-25 02:42:55 +00003305 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003306 SDValue(Parts[0],0));
3307
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003308 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003309 // do (x << 16) | (x >> 16).
3310 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3311 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003312 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003313 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003314 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3315 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3316 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3317 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003318}
3319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003320SDValue DAGCombiner::visitOR(SDNode *N) {
3321 SDValue N0 = N->getOperand(0);
3322 SDValue N1 = N->getOperand(1);
3323 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003324 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3325 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003326 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003327
Dan Gohmana8665142007-06-25 16:23:39 +00003328 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003329 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003330 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003331 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003332
3333 // fold (or x, 0) -> x, vector edition
3334 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3335 return N1;
3336 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3337 return N0;
3338
3339 // fold (or x, -1) -> -1, vector edition
3340 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003341 // do not return N0, because undef node may exist in N0
3342 return DAG.getConstant(
3343 APInt::getAllOnesValue(
3344 N0.getValueType().getScalarType().getSizeInBits()),
3345 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003346 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003347 // do not return N1, because undef node may exist in N1
3348 return DAG.getConstant(
3349 APInt::getAllOnesValue(
3350 N1.getValueType().getScalarType().getSizeInBits()),
3351 N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003352
3353 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3354 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3355 // Do this only if the resulting shuffle is legal.
3356 if (isa<ShuffleVectorSDNode>(N0) &&
3357 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003358 // Avoid folding a node with illegal type.
3359 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003360 N0->getOperand(1) == N1->getOperand(1) &&
3361 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3362 bool CanFold = true;
3363 unsigned NumElts = VT.getVectorNumElements();
3364 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3365 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3366 // We construct two shuffle masks:
3367 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3368 // and N1 as the second operand.
3369 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3370 // and N0 as the second operand.
3371 // We do this because OR is commutable and therefore there might be
3372 // two ways to fold this node into a shuffle.
3373 SmallVector<int,4> Mask1;
3374 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003375
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003376 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3377 int M0 = SV0->getMaskElt(i);
3378 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003379
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003380 // Both shuffle indexes are undef. Propagate Undef.
3381 if (M0 < 0 && M1 < 0) {
3382 Mask1.push_back(M0);
3383 Mask2.push_back(M0);
3384 continue;
3385 }
3386
3387 if (M0 < 0 || M1 < 0 ||
3388 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3389 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3390 CanFold = false;
3391 break;
3392 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003393
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003394 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3395 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3396 }
3397
3398 if (CanFold) {
3399 // Fold this sequence only if the resulting shuffle is 'legal'.
3400 if (TLI.isShuffleMaskLegal(Mask1, VT))
3401 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3402 N1->getOperand(0), &Mask1[0]);
3403 if (TLI.isShuffleMaskLegal(Mask2, VT))
3404 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3405 N0->getOperand(0), &Mask2[0]);
3406 }
3407 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003408 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003409
Dan Gohman06563a82007-07-03 14:03:57 +00003410 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003411 if (!LegalOperations &&
3412 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003413 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3414 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3415 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003416 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003417 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003418 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003419 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003420 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003421 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003422 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003423 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003424 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003425 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003426 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003427 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003428 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003429 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003430 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003431
3432 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3433 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003434 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003435 return BSwap;
3436 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003437 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003438 return BSwap;
3439
Nate Begeman22e251a2006-02-03 06:46:56 +00003440 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003441 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003442 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003443 return ROR;
3444 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003445 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003446 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003447 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003448 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003449 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
Matthias Braunf50ab432015-01-13 22:17:46 +00003450 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3451 return DAG.getNode(
3452 ISD::AND, SDLoc(N), VT,
3453 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3454 return SDValue();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003455 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003456 }
Nate Begeman049b7482005-09-09 19:49:52 +00003457 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3458 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3459 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3460 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003461
Nate Begeman049b7482005-09-09 19:49:52 +00003462 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003463 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003464 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3465 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003466 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003467 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003468 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003469 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003470 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003471 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003472 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003473 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3474 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003475 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003476 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003477 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003478 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003479 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003480 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003481 }
3482 }
3483 // canonicalize equivalent to ll == rl
3484 if (LL == RR && LR == RL) {
3485 Op1 = ISD::getSetCCSwappedOperands(Op1);
3486 std::swap(RL, RR);
3487 }
3488 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003489 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003490 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003491 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003492 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003493 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3494 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003495 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003496 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003497 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003498 }
3499 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003500
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003501 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003502 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003503 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003504 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003505 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003506
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003507 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003508 if (N0.getOpcode() == ISD::AND &&
3509 N1.getOpcode() == ISD::AND &&
3510 N0.getOperand(1).getOpcode() == ISD::Constant &&
3511 N1.getOperand(1).getOpcode() == ISD::Constant &&
3512 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003513 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003514 // We can only do this xform if we know that bits from X that are set in C2
3515 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003516 const APInt &LHSMask =
3517 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3518 const APInt &RHSMask =
3519 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003520
Dan Gohman309d3d52007-06-22 14:59:07 +00003521 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3522 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003523 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003524 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003525 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003526 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003527 }
3528 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003529
Tim Northover3007ba02015-01-21 23:17:19 +00003530 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3531 if (N0.getOpcode() == ISD::AND &&
3532 N1.getOpcode() == ISD::AND &&
3533 N0.getOperand(0) == N1.getOperand(0) &&
3534 // Don't increase # computations.
3535 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3536 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3537 N0.getOperand(1), N1.getOperand(1));
3538 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), X);
3539 }
3540
Chris Lattner97614c82006-09-14 20:50:57 +00003541 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003542 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003543 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003544
Dan Gohman600f62b2010-06-24 14:30:44 +00003545 // Simplify the operands using demanded-bits information.
3546 if (!VT.isVector() &&
3547 SimplifyDemandedBits(SDValue(N, 0)))
3548 return SDValue(N, 0);
3549
Evan Chengf1005572010-04-28 07:10:39 +00003550 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003551}
3552
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003553/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003554static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003555 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003556 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003557 Mask = Op.getOperand(1);
3558 Op = Op.getOperand(0);
3559 } else {
3560 return false;
3561 }
3562 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003563
Chris Lattner97614c82006-09-14 20:50:57 +00003564 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3565 Shift = Op;
3566 return true;
3567 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003568
Scott Michelcf0da6c2009-02-17 22:15:04 +00003569 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003570}
3571
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003572// Return true if we can prove that, whenever Neg and Pos are both in the
3573// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003574// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3575//
3576// (or (shift1 X, Neg), (shift2 X, Pos))
3577//
Adam Nemetc6553a82014-03-07 23:56:24 +00003578// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3579// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3580// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003581static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003582 // If OpSize is a power of 2 then:
3583 //
3584 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3585 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3586 //
3587 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3588 // for the stronger condition:
3589 //
3590 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3591 //
3592 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3593 // we can just replace Neg with Neg' for the rest of the function.
3594 //
3595 // In other cases we check for the even stronger condition:
3596 //
3597 // Neg == OpSize - Pos [B]
3598 //
3599 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3600 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003601 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003602 // We could actually use [A] whenever OpSize is a power of 2, but the
3603 // only extra cases that it would match are those uninteresting ones
3604 // where Neg and Pos are never in range at the same time. E.g. for
3605 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3606 // as well as (sub 32, Pos), but:
3607 //
3608 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3609 //
3610 // always invokes undefined behavior for 32-bit X.
3611 //
3612 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003613 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003614 if (Neg.getOpcode() == ISD::AND &&
3615 isPowerOf2_64(OpSize) &&
3616 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3617 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3618 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003619 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003620 }
3621
Richard Sandiford0f264db2014-01-09 10:49:40 +00003622 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3623 if (Neg.getOpcode() != ISD::SUB)
3624 return 0;
3625 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3626 if (!NegC)
3627 return 0;
3628 SDValue NegOp1 = Neg.getOperand(1);
3629
Adam Nemet5117f5d2014-03-07 23:56:28 +00003630 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3631 // Pos'. The truncation is redundant for the purpose of the equality.
3632 if (MaskLoBits &&
3633 Pos.getOpcode() == ISD::AND &&
3634 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3635 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3636 Pos = Pos.getOperand(0);
3637
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003638 // The condition we need is now:
3639 //
3640 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3641 //
3642 // If NegOp1 == Pos then we need:
3643 //
3644 // OpSize & Mask == NegC & Mask
3645 //
3646 // (because "x & Mask" is a truncation and distributes through subtraction).
3647 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003648 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003649 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003650 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3651 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003652 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003653 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3654 //
3655 // which, again because "x & Mask" is a truncation, becomes:
3656 //
3657 // NegC & Mask == (OpSize - PosC) & Mask
3658 // OpSize & Mask == (NegC + PosC) & Mask
3659 else if (Pos.getOpcode() == ISD::ADD &&
3660 Pos.getOperand(0) == NegOp1 &&
3661 Pos.getOperand(1).getOpcode() == ISD::Constant)
3662 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3663 NegC->getAPIntValue());
3664 else
3665 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003666
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003667 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003668 if (MaskLoBits)
3669 // Opsize & Mask is 0 since Mask is Opsize - 1.
3670 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003671 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003672}
3673
Richard Sandiford95c864d2014-01-08 15:40:47 +00003674// A subroutine of MatchRotate used once we have found an OR of two opposite
3675// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3676// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3677// former being preferred if supported. InnerPos and InnerNeg are Pos and
3678// Neg with outer conversions stripped away.
3679SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3680 SDValue Neg, SDValue InnerPos,
3681 SDValue InnerNeg, unsigned PosOpcode,
3682 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003683 // fold (or (shl x, (*ext y)),
3684 // (srl x, (*ext (sub 32, y)))) ->
3685 // (rotl x, y) or (rotr x, (sub 32, y))
3686 //
3687 // fold (or (shl x, (*ext (sub 32, y))),
3688 // (srl x, (*ext y))) ->
3689 // (rotr x, y) or (rotl x, (sub 32, y))
3690 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003691 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003692 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3693 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3694 HasPos ? Pos : Neg).getNode();
3695 }
3696
Craig Topperc0196b12014-04-14 00:51:57 +00003697 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003698}
3699
Chris Lattner97614c82006-09-14 20:50:57 +00003700// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3701// idioms for rotate, and if the target supports rotation instructions, generate
3702// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003703SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003704 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003705 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003706 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003707
3708 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003709 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3710 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003711 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003712
Chris Lattner97614c82006-09-14 20:50:57 +00003713 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003714 SDValue LHSShift; // The shift.
3715 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003716 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003717 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003718
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003719 SDValue RHSShift; // The shift.
3720 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003721 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003722 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003723
Chris Lattner97614c82006-09-14 20:50:57 +00003724 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003725 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003726
3727 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003728 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003729
Chris Lattner97614c82006-09-14 20:50:57 +00003730 // Canonicalize shl to left side in a shl/srl pair.
3731 if (RHSShift.getOpcode() == ISD::SHL) {
3732 std::swap(LHS, RHS);
3733 std::swap(LHSShift, RHSShift);
3734 std::swap(LHSMask , RHSMask );
3735 }
3736
Duncan Sands13237ac2008-06-06 12:08:01 +00003737 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003738 SDValue LHSShiftArg = LHSShift.getOperand(0);
3739 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003740 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003741 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003742
3743 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3744 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003745 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3746 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003747 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3748 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003749 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003750 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003751
Craig Topper65161fa2012-09-29 06:54:22 +00003752 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3753 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003754
Chris Lattner97614c82006-09-14 20:50:57 +00003755 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003756 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003757 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003758
Gabor Greiff304a7a2008-08-28 21:40:38 +00003759 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003760 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3761 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003762 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003763 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003764 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3765 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003766 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003767
Bill Wendling35972a92009-01-30 21:14:50 +00003768 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003769 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003770
Gabor Greiff304a7a2008-08-28 21:40:38 +00003771 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003772 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003773
Chris Lattner97614c82006-09-14 20:50:57 +00003774 // If there is a mask here, and we have a variable shift, we can't be sure
3775 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003776 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003777 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003778
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003779 // If the shift amount is sign/zext/any-extended just peel it off.
3780 SDValue LExtOp0 = LHSShiftAmt;
3781 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003782 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3783 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3784 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3785 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3786 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3787 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3788 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3789 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003790 LExtOp0 = LHSShiftAmt.getOperand(0);
3791 RExtOp0 = RHSShiftAmt.getOperand(0);
3792 }
3793
Richard Sandiford95c864d2014-01-08 15:40:47 +00003794 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3795 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3796 if (TryL)
3797 return TryL;
3798
3799 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3800 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3801 if (TryR)
3802 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003803
Craig Topperc0196b12014-04-14 00:51:57 +00003804 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003805}
3806
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003807SDValue DAGCombiner::visitXOR(SDNode *N) {
3808 SDValue N0 = N->getOperand(0);
3809 SDValue N1 = N->getOperand(1);
3810 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003811 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3812 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003813 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003814
Dan Gohmana8665142007-06-25 16:23:39 +00003815 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003816 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003817 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003818 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003819
3820 // fold (xor x, 0) -> x, vector edition
3821 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3822 return N1;
3823 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3824 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003825 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003826
Evan Chengdf1690d2008-03-25 20:08:07 +00003827 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3828 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3829 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003830 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003831 if (N0.getOpcode() == ISD::UNDEF)
3832 return N0;
3833 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003834 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003835 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003836 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003837 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003838 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003839 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003840 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003841 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003842 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003843 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003844 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003845 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003846 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003847 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003848
Nate Begeman21158fc2005-09-01 00:19:25 +00003849 // fold !(x cc y) -> (x !cc y)
Oliver Stannardd29db9b2014-11-17 10:49:31 +00003850 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003851 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003852 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3853 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003854
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003855 if (!LegalOperations ||
3856 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003857 switch (N0.getOpcode()) {
3858 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003859 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003860 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003861 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003862 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003863 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003864 N0.getOperand(3), NotCC);
3865 }
3866 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003867 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003868
Chris Lattner58c227b2007-09-10 21:39:07 +00003869 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003870 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003871 N0.getNode()->hasOneUse() &&
3872 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003873 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003874 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003875 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003876 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003877 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003878 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003879
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003880 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003881 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003882 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003883 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003884 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3885 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003886 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3887 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003888 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003889 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003890 }
3891 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003892 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003893 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003894 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003895 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003896 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3897 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003898 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3899 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003900 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003901 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003902 }
3903 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003904 // fold (xor (and x, y), y) -> (and (not x), y)
3905 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003906 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003907 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003908 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003909 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003910 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003911 }
Bill Wendling35972a92009-01-30 21:14:50 +00003912 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003913 if (N1C && N0.getOpcode() == ISD::XOR) {
3914 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3915 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3916 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003917 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003918 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003919 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003920 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003921 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003922 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003923 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003924 }
3925 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003926 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003927 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003928
Chris Lattner8d6fc202006-05-05 05:51:50 +00003929 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3930 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003931 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003932 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003933 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003934
Chris Lattner098c01e2006-04-08 04:15:24 +00003935 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003936 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003937 SimplifyDemandedBits(SDValue(N, 0)))
3938 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003939
Evan Chengf1005572010-04-28 07:10:39 +00003940 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003941}
3942
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003943/// Handle transforms common to the three shifts, when the shift amount is a
3944/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003945SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003946 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003947 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003948 return SDValue();
3949
Gabor Greiff304a7a2008-08-28 21:40:38 +00003950 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003951 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003952
Chris Lattner7c709a52007-12-06 07:33:36 +00003953 // We want to pull some binops through shifts, so that we have (and (shift))
3954 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3955 // thing happens with address calculations, so it's important to canonicalize
3956 // it.
3957 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003958
Chris Lattner7c709a52007-12-06 07:33:36 +00003959 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003960 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003961 case ISD::OR:
3962 case ISD::XOR:
3963 HighBitSet = false; // We can only transform sra if the high bit is clear.
3964 break;
3965 case ISD::AND:
3966 HighBitSet = true; // We can only transform sra if the high bit is set.
3967 break;
3968 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003969 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003970 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003971 HighBitSet = false; // We can only transform sra if the high bit is clear.
3972 break;
3973 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003974
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003975 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003976 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003977 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003978
3979 // FIXME: disable this unless the input to the binop is a shift by a constant.
3980 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003981 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003982 // void foo(int *X, int i) { X[i & 1235] = 1; }
3983 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003984 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003985 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003986 BinOpLHSVal->getOpcode() != ISD::SRA &&
3987 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3988 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003989 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003990
Owen Anderson53aa7a92009-08-10 22:56:29 +00003991 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003992
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003993 // If this is a signed shift right, and the high bit is modified by the
3994 // logical operation, do not perform the transformation. The highBitSet
3995 // boolean indicates the value of the high bit of the constant which would
3996 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003997 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003998 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3999 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004000 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004001 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004002
Weiming Zhao7f6daf12014-04-30 21:07:24 +00004003 if (!TLI.isDesirableToCommuteWithShift(LHS))
4004 return SDValue();
4005
Chris Lattner7c709a52007-12-06 07:33:36 +00004006 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004007 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004008 N->getValueType(0),
4009 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004010 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00004011
4012 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004013 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004014 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004015 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00004016
4017 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004018 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00004019}
4020
Adam Nemet67483892014-03-04 23:28:31 +00004021SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4022 assert(N->getOpcode() == ISD::TRUNCATE);
4023 assert(N->getOperand(0).getOpcode() == ISD::AND);
4024
4025 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4026 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4027 SDValue N01 = N->getOperand(0).getOperand(1);
4028
Matt Arsenault985b9de2014-03-17 18:58:01 +00004029 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00004030 EVT TruncVT = N->getValueType(0);
4031 SDValue N00 = N->getOperand(0).getOperand(0);
4032 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004033 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00004034
4035 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4036 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4037 DAG.getConstant(TruncC, TruncVT));
4038 }
4039 }
4040
4041 return SDValue();
4042}
Adam Nemet7f928f12014-03-07 23:56:30 +00004043
4044SDValue DAGCombiner::visitRotate(SDNode *N) {
4045 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4046 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4047 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4048 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4049 if (NewOp1.getNode())
4050 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4051 N->getOperand(0), NewOp1);
4052 }
4053 return SDValue();
4054}
4055
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004056SDValue DAGCombiner::visitSHL(SDNode *N) {
4057 SDValue N0 = N->getOperand(0);
4058 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004059 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4060 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004061 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004062 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004063
Daniel Sandersa1840d22013-11-11 17:23:41 +00004064 // fold vector ops
4065 if (VT.isVector()) {
4066 SDValue FoldedVOp = SimplifyVBinOp(N);
4067 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004068
4069 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4070 // If setcc produces all-one true value then:
4071 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004072 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004073 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004074 SDValue N00 = N0->getOperand(0);
4075 SDValue N01 = N0->getOperand(1);
4076 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004077
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004078 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4079 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4080 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matthias Braunf50ab432015-01-13 22:17:46 +00004081 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004082 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4083 }
4084 } else {
4085 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004086 }
4087 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004088 }
4089
Nate Begeman21158fc2005-09-01 00:19:25 +00004090 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004091 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004092 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004093 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004094 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004095 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004096 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004097 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004098 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004099 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004100 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004101 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004102 // fold (shl undef, x) -> 0
4103 if (N0.getOpcode() == ISD::UNDEF)
4104 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004105 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004106 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004107 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004108 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004109 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004110 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004111 N1.getOperand(0).getOpcode() == ISD::AND) {
4112 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4113 if (NewOp1.getNode())
4114 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004115 }
4116
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004117 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4118 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004119
4120 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004121 if (N1C && N0.getOpcode() == ISD::SHL) {
4122 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4123 uint64_t c1 = N0C1->getZExtValue();
4124 uint64_t c2 = N1C->getZExtValue();
4125 if (c1 + c2 >= OpSizeInBits)
4126 return DAG.getConstant(0, VT);
4127 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4128 DAG.getConstant(c1 + c2, N1.getValueType()));
4129 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004130 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004131
4132 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4133 // For this to be valid, the second form must not preserve any of the bits
4134 // that are shifted out by the inner shift in the first form. This means
4135 // the outer shift size must be >= the number of bits added by the ext.
4136 // As a corollary, we don't care what kind of ext it is.
4137 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4138 N0.getOpcode() == ISD::ANY_EXTEND ||
4139 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004140 N0.getOperand(0).getOpcode() == ISD::SHL) {
4141 SDValue N0Op0 = N0.getOperand(0);
4142 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4143 uint64_t c1 = N0Op0C1->getZExtValue();
4144 uint64_t c2 = N1C->getZExtValue();
4145 EVT InnerShiftVT = N0Op0.getValueType();
4146 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4147 if (c2 >= OpSizeInBits - InnerShiftSize) {
4148 if (c1 + c2 >= OpSizeInBits)
4149 return DAG.getConstant(0, VT);
4150 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4151 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4152 N0Op0->getOperand(0)),
4153 DAG.getConstant(c1 + c2, N1.getValueType()));
4154 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004155 }
4156 }
4157
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004158 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4159 // Only fold this if the inner zext has no other uses to avoid increasing
4160 // the total number of instructions.
4161 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004162 N0.getOperand(0).getOpcode() == ISD::SRL) {
4163 SDValue N0Op0 = N0.getOperand(0);
4164 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4165 uint64_t c1 = N0Op0C1->getZExtValue();
4166 if (c1 < VT.getScalarSizeInBits()) {
4167 uint64_t c2 = N1C->getZExtValue();
4168 if (c1 == c2) {
4169 SDValue NewOp0 = N0.getOperand(0);
4170 EVT CountVT = NewOp0.getOperand(1).getValueType();
4171 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4172 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004173 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004174 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4175 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004176 }
4177 }
4178 }
4179
Eli Friedman1877ac92011-06-09 22:14:44 +00004180 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4181 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004182 // Only fold this if the inner shift has no other uses -- if it does, folding
4183 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004184 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4185 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4186 uint64_t c1 = N0C1->getZExtValue();
4187 if (c1 < OpSizeInBits) {
4188 uint64_t c2 = N1C->getZExtValue();
4189 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4190 SDValue Shift;
4191 if (c2 > c1) {
4192 Mask = Mask.shl(c2 - c1);
4193 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4194 DAG.getConstant(c2 - c1, N1.getValueType()));
4195 } else {
4196 Mask = Mask.lshr(c1 - c2);
4197 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4198 DAG.getConstant(c1 - c2, N1.getValueType()));
4199 }
4200 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4201 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004202 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004203 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004204 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004205 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004206 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004207 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004208 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004209 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4210 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004211 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004212 HiBitsMask);
4213 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004214
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004215 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4216 // Variant of version done on multiply, except mul by a power of 2 is turned
4217 // into a shift.
4218 APInt Val;
4219 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4220 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4221 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4222 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4223 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4224 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4225 }
4226
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004227 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004228 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004229 if (NewSHL.getNode())
4230 return NewSHL;
4231 }
4232
Evan Chengf1005572010-04-28 07:10:39 +00004233 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004234}
4235
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004236SDValue DAGCombiner::visitSRA(SDNode *N) {
4237 SDValue N0 = N->getOperand(0);
4238 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004239 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4240 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004241 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004242 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004243
Daniel Sandersa1840d22013-11-11 17:23:41 +00004244 // fold vector ops
4245 if (VT.isVector()) {
4246 SDValue FoldedVOp = SimplifyVBinOp(N);
4247 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004248
4249 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004250 }
4251
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004252 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004253 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004254 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004255 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004256 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004257 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004258 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004259 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004260 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004261 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004262 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004263 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004264 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004265 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004266 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004267 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4268 // sext_inreg.
4269 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004270 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004271 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4272 if (VT.isVector())
4273 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4274 ExtVT, VT.getVectorNumElements());
4275 if ((!LegalOperations ||
4276 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004277 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004278 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004279 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004280
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004281 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004282 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004283 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004284 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004285 if (Sum >= OpSizeInBits)
4286 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004287 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004288 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004289 }
4290 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004291
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004292 // fold (sra (shl X, m), (sub result_size, n))
4293 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004294 // result_size - n != m.
4295 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004296 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004297 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004298 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004299 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4300 if (N01C) {
4301 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004302 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004303 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4304
4305 if (VT.isVector())
4306 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4307
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004308 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004309 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004310
Scott Michelcf0da6c2009-02-17 22:15:04 +00004311 // If the shift is not a no-op (in which case this should be just a sign
4312 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004313 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004314 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004315 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004316 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4317 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004318 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004319
Owen Andersonb2c80da2011-02-25 21:41:48 +00004320 SDValue Amt = DAG.getConstant(ShiftAmt,
4321 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004322 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004323 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004324 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004325 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004326 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004327 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004328 }
4329 }
4330 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004331
Duncan Sands3ed76882009-02-01 18:06:53 +00004332 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004333 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004334 N1.getOperand(0).getOpcode() == ISD::AND) {
4335 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4336 if (NewOp1.getNode())
4337 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004338 }
4339
Matt Arsenault985b9de2014-03-17 18:58:01 +00004340 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004341 // if c1 is equal to the number of bits the trunc removes
4342 if (N0.getOpcode() == ISD::TRUNCATE &&
4343 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4344 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4345 N0.getOperand(0).hasOneUse() &&
4346 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004347 N1C) {
4348 SDValue N0Op0 = N0.getOperand(0);
4349 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4350 unsigned LargeShiftVal = LargeShift->getZExtValue();
4351 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004352
Matt Arsenault985b9de2014-03-17 18:58:01 +00004353 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4354 SDValue Amt =
4355 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4356 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4357 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4358 N0Op0.getOperand(0), Amt);
4359 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4360 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004361 }
4362 }
4363
Scott Michelcf0da6c2009-02-17 22:15:04 +00004364 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004365 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4366 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004367
4368
Nate Begeman21158fc2005-09-01 00:19:25 +00004369 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004370 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004371 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004372
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004373 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004374 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004375 if (NewSRA.getNode())
4376 return NewSRA;
4377 }
4378
Evan Chengf1005572010-04-28 07:10:39 +00004379 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004380}
4381
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004382SDValue DAGCombiner::visitSRL(SDNode *N) {
4383 SDValue N0 = N->getOperand(0);
4384 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004385 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4386 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004387 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004388 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004389
Daniel Sandersa1840d22013-11-11 17:23:41 +00004390 // fold vector ops
4391 if (VT.isVector()) {
4392 SDValue FoldedVOp = SimplifyVBinOp(N);
4393 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004394
4395 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004396 }
4397
Nate Begeman21158fc2005-09-01 00:19:25 +00004398 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004399 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004400 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004401 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004402 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004403 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004404 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004405 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004406 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004407 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004408 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004409 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004410 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004411 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004412 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004413 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004414
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004415 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004416 if (N1C && N0.getOpcode() == ISD::SRL) {
4417 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4418 uint64_t c1 = N01C->getZExtValue();
4419 uint64_t c2 = N1C->getZExtValue();
4420 if (c1 + c2 >= OpSizeInBits)
4421 return DAG.getConstant(0, VT);
4422 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4423 DAG.getConstant(c1 + c2, N1.getValueType()));
4424 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004425 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004426
Dale Johannesencd538af2010-12-17 21:45:49 +00004427 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004428 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4429 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004430 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004431 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004432 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4433 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004434 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4435 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004436 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004437 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004438 if (c1 + OpSizeInBits == InnerShiftSize) {
4439 if (c1 + c2 >= InnerShiftSize)
4440 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004441 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4442 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004443 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004444 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004445 }
4446 }
4447
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004448 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004449 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4450 unsigned BitSize = N0.getScalarValueSizeInBits();
4451 if (BitSize <= 64) {
4452 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4453 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4454 DAG.getConstant(~0ULL >> ShAmt, VT));
4455 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004456 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004457
Michael Liao62ebfd82013-06-21 18:45:27 +00004458 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004459 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4460 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004461 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004462 unsigned BitSize = SmallVT.getScalarSizeInBits();
4463 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004464 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004465
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004466 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004467 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004468 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004469 N0.getOperand(0),
4470 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004471 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004472 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004473 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4474 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4475 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004476 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004477 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004478
Chris Lattner2e33fb42006-10-12 20:23:19 +00004479 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4480 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004481 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004482 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004483 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004484 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004485
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004486 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004487 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004488 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004489 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004490 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004491
Chris Lattner49932492006-04-02 06:11:11 +00004492 // If any of the input bits are KnownOne, then the input couldn't be all
4493 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004494 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004495
Chris Lattner49932492006-04-02 06:11:11 +00004496 // If all of the bits input the to ctlz node are known to be zero, then
4497 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004498 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004499 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004500
Chris Lattner49932492006-04-02 06:11:11 +00004501 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004502 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004503 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004504 // could be set on input to the CTLZ node. If this bit is set, the SRL
4505 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4506 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004507 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004508 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004509
Chris Lattner49932492006-04-02 06:11:11 +00004510 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004511 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004512 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004513 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004514 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004515
Andrew Trickef9de2a2013-05-25 02:42:55 +00004516 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004517 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004518 }
4519 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004520
Duncan Sands3ed76882009-02-01 18:06:53 +00004521 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004522 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004523 N1.getOperand(0).getOpcode() == ISD::AND) {
4524 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4525 if (NewOp1.getNode())
4526 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004527 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004528
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004529 // fold operands of srl based on knowledge that the low bits are not
4530 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004531 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4532 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004533
Evan Chengb175de62009-12-18 21:31:31 +00004534 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004535 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004536 if (NewSRL.getNode())
4537 return NewSRL;
4538 }
4539
Dan Gohman600f62b2010-06-24 14:30:44 +00004540 // Attempt to convert a srl of a load into a narrower zero-extending load.
4541 SDValue NarrowLoad = ReduceLoadWidth(N);
4542 if (NarrowLoad.getNode())
4543 return NarrowLoad;
4544
Evan Chengb175de62009-12-18 21:31:31 +00004545 // Here is a common situation. We want to optimize:
4546 //
4547 // %a = ...
4548 // %b = and i32 %a, 2
4549 // %c = srl i32 %b, 1
4550 // brcond i32 %c ...
4551 //
4552 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004553 //
Evan Chengb175de62009-12-18 21:31:31 +00004554 // %a = ...
4555 // %b = and %a, 2
4556 // %c = setcc eq %b, 0
4557 // brcond %c ...
4558 //
4559 // However when after the source operand of SRL is optimized into AND, the SRL
4560 // itself may not be optimized further. Look for it and add the BRCOND into
4561 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004562 if (N->hasOneUse()) {
4563 SDNode *Use = *N->use_begin();
4564 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004565 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004566 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4567 // Also look pass the truncate.
4568 Use = *Use->use_begin();
4569 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004570 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004571 }
4572 }
Evan Chengb175de62009-12-18 21:31:31 +00004573
Evan Chengf1005572010-04-28 07:10:39 +00004574 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004575}
4576
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004577SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4578 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004579 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004580
4581 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004582 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004583 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004584 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004585}
4586
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004587SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4588 SDValue N0 = N->getOperand(0);
4589 EVT VT = N->getValueType(0);
4590
4591 // fold (ctlz_zero_undef c1) -> c2
4592 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004593 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004594 return SDValue();
4595}
4596
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004597SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4598 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004599 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004600
Nate Begeman21158fc2005-09-01 00:19:25 +00004601 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004602 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004603 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004604 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004605}
4606
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004607SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4608 SDValue N0 = N->getOperand(0);
4609 EVT VT = N->getValueType(0);
4610
4611 // fold (cttz_zero_undef c1) -> c2
4612 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004613 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004614 return SDValue();
4615}
4616
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004617SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4618 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004619 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004620
Nate Begeman21158fc2005-09-01 00:19:25 +00004621 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004622 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004623 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004624 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004625}
4626
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004627
4628/// \brief Generate Min/Max node
4629static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4630 SDValue True, SDValue False,
4631 ISD::CondCode CC, const TargetLowering &TLI,
4632 SelectionDAG &DAG) {
4633 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4634 return SDValue();
4635
4636 switch (CC) {
4637 case ISD::SETOLT:
4638 case ISD::SETOLE:
4639 case ISD::SETLT:
4640 case ISD::SETLE:
4641 case ISD::SETULT:
4642 case ISD::SETULE: {
4643 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4644 if (TLI.isOperationLegal(Opcode, VT))
4645 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4646 return SDValue();
4647 }
4648 case ISD::SETOGT:
4649 case ISD::SETOGE:
4650 case ISD::SETGT:
4651 case ISD::SETGE:
4652 case ISD::SETUGT:
4653 case ISD::SETUGE: {
4654 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4655 if (TLI.isOperationLegal(Opcode, VT))
4656 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4657 return SDValue();
4658 }
4659 default:
4660 return SDValue();
4661 }
4662}
4663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004664SDValue DAGCombiner::visitSELECT(SDNode *N) {
4665 SDValue N0 = N->getOperand(0);
4666 SDValue N1 = N->getOperand(1);
4667 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004668 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4669 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4670 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004671 EVT VT = N->getValueType(0);
4672 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004673
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004674 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004675 if (N1 == N2)
4676 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004677 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004678 if (N0C && !N0C->isNullValue())
4679 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004680 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004681 if (N0C && N0C->isNullValue())
4682 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004683 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004684 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004685 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004686 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004687 // We can't do this reliably if integer based booleans have different contents
4688 // to floating point based booleans. This is because we can't tell whether we
4689 // have an integer-based boolean or a floating-point-based boolean unless we
4690 // can find the SETCC that produced it and inspect its operands. This is
4691 // fairly easy if C is the SETCC node, but it can potentially be
4692 // undiscoverable (or not reasonably discoverable). For example, it could be
4693 // in another basic block or it could require searching a complicated
4694 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004695 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004696 (VT0 == MVT::i1 || (VT0.isInteger() &&
4697 TLI.getBooleanContents(false, false) ==
4698 TLI.getBooleanContents(false, true) &&
4699 TLI.getBooleanContents(false, false) ==
4700 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004701 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004702 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004703 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004704 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004705 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004706 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004707 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004708 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004709 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004710 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4711 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004712 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004713 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004714 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004715 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004716 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004717 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004718 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004719 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004720 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004721 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004722 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004723 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004724 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004725 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004726 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004727 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004728 // fold (select X, X, Y) -> (or X, Y)
4729 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004730 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004731 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004732 // fold (select X, Y, X) -> (and X, Y)
4733 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004734 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004735 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004736
Chris Lattner6c14c352005-10-18 06:04:22 +00004737 // If we can fold this based on the true/false value, do so.
4738 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004739 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004740
Nate Begemanc760f802005-09-19 22:34:01 +00004741 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004742 if (N0.getOpcode() == ISD::SETCC) {
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004743 // select x, y (fcmp lt x, y) -> fminnum x, y
4744 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4745 //
4746 // This is OK if we don't care about what happens if either operand is a
4747 // NaN.
4748 //
4749
4750 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4751 // no signed zeros as well as no nans.
4752 const TargetOptions &Options = DAG.getTarget().Options;
4753 if (Options.UnsafeFPMath &&
4754 VT.isFloatingPoint() && N0.hasOneUse() &&
4755 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4756 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4757
4758 SDValue FMinMax =
4759 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4760 N1, N2, CC, TLI, DAG);
4761 if (FMinMax)
4762 return FMinMax;
4763 }
4764
Tom Stellard3787b122014-06-10 16:01:29 +00004765 if ((!LegalOperations &&
4766 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004767 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004768 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004769 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004770 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004771 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004772 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004773
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004774 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004775}
4776
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004777static
4778std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4779 SDLoc DL(N);
4780 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004781 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004782
4783 // Split the inputs.
4784 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004785 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4786 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004787
4788 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4789 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4790
4791 return std::make_pair(Lo, Hi);
4792}
4793
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004794// This function assumes all the vselect's arguments are CONCAT_VECTOR
4795// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4796static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4797 SDLoc dl(N);
4798 SDValue Cond = N->getOperand(0);
4799 SDValue LHS = N->getOperand(1);
4800 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004801 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004802 int NumElems = VT.getVectorNumElements();
4803 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4804 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4805 Cond.getOpcode() == ISD::BUILD_VECTOR);
4806
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004807 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4808 // binary ones here.
4809 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4810 return SDValue();
4811
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004812 // We're sure we have an even number of elements due to the
4813 // concat_vectors we have as arguments to vselect.
4814 // Skip BV elements until we find one that's not an UNDEF
4815 // After we find an UNDEF element, keep looping until we get to half the
4816 // length of the BV and see if all the non-undef nodes are the same.
4817 ConstantSDNode *BottomHalf = nullptr;
4818 for (int i = 0; i < NumElems / 2; ++i) {
4819 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4820 continue;
4821
4822 if (BottomHalf == nullptr)
4823 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4824 else if (Cond->getOperand(i).getNode() != BottomHalf)
4825 return SDValue();
4826 }
4827
4828 // Do the same for the second half of the BuildVector
4829 ConstantSDNode *TopHalf = nullptr;
4830 for (int i = NumElems / 2; i < NumElems; ++i) {
4831 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4832 continue;
4833
4834 if (TopHalf == nullptr)
4835 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4836 else if (Cond->getOperand(i).getNode() != TopHalf)
4837 return SDValue();
4838 }
4839
4840 assert(TopHalf && BottomHalf &&
4841 "One half of the selector was all UNDEFs and the other was all the "
4842 "same value. This should have been addressed before this function.");
4843 return DAG.getNode(
4844 ISD::CONCAT_VECTORS, dl, VT,
4845 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4846 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4847}
4848
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004849SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4850
4851 if (Level >= AfterLegalizeTypes)
4852 return SDValue();
4853
4854 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4855 SDValue Mask = MST->getMask();
4856 SDValue Data = MST->getData();
4857 SDLoc DL(N);
4858
4859 // If the MSTORE data type requires splitting and the mask is provided by a
4860 // SETCC, then split both nodes and its operands before legalization. This
4861 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4862 // and enables future optimizations (e.g. min/max pattern matching on X86).
4863 if (Mask.getOpcode() == ISD::SETCC) {
4864
4865 // Check if any splitting is required.
4866 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4867 TargetLowering::TypeSplitVector)
4868 return SDValue();
4869
4870 SDValue MaskLo, MaskHi, Lo, Hi;
4871 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4872
4873 EVT LoVT, HiVT;
4874 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4875
4876 SDValue Chain = MST->getChain();
4877 SDValue Ptr = MST->getBasePtr();
4878
4879 EVT MemoryVT = MST->getMemoryVT();
4880 unsigned Alignment = MST->getOriginalAlignment();
4881
4882 // if Alignment is equal to the vector size,
4883 // take the half of it for the second part
4884 unsigned SecondHalfAlignment =
4885 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4886 Alignment/2 : Alignment;
4887
4888 EVT LoMemVT, HiMemVT;
4889 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4890
4891 SDValue DataLo, DataHi;
4892 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4893
4894 MachineMemOperand *MMO = DAG.getMachineFunction().
4895 getMachineMemOperand(MST->getPointerInfo(),
4896 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4897 Alignment, MST->getAAInfo(), MST->getRanges());
4898
4899 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4900
4901 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4902 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4903 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4904
4905 MMO = DAG.getMachineFunction().
4906 getMachineMemOperand(MST->getPointerInfo(),
4907 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4908 SecondHalfAlignment, MST->getAAInfo(),
4909 MST->getRanges());
4910
4911 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4912
4913 AddToWorklist(Lo.getNode());
4914 AddToWorklist(Hi.getNode());
4915
4916 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4917 }
4918 return SDValue();
4919}
4920
4921SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4922
4923 if (Level >= AfterLegalizeTypes)
4924 return SDValue();
4925
4926 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4927 SDValue Mask = MLD->getMask();
4928 SDLoc DL(N);
4929
4930 // If the MLOAD result requires splitting and the mask is provided by a
4931 // SETCC, then split both nodes and its operands before legalization. This
4932 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4933 // and enables future optimizations (e.g. min/max pattern matching on X86).
4934
4935 if (Mask.getOpcode() == ISD::SETCC) {
4936 EVT VT = N->getValueType(0);
4937
4938 // Check if any splitting is required.
4939 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4940 TargetLowering::TypeSplitVector)
4941 return SDValue();
4942
4943 SDValue MaskLo, MaskHi, Lo, Hi;
4944 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4945
4946 SDValue Src0 = MLD->getSrc0();
4947 SDValue Src0Lo, Src0Hi;
4948 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4949
4950 EVT LoVT, HiVT;
4951 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4952
4953 SDValue Chain = MLD->getChain();
4954 SDValue Ptr = MLD->getBasePtr();
4955 EVT MemoryVT = MLD->getMemoryVT();
4956 unsigned Alignment = MLD->getOriginalAlignment();
4957
4958 // if Alignment is equal to the vector size,
4959 // take the half of it for the second part
4960 unsigned SecondHalfAlignment =
4961 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4962 Alignment/2 : Alignment;
4963
4964 EVT LoMemVT, HiMemVT;
4965 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4966
4967 MachineMemOperand *MMO = DAG.getMachineFunction().
4968 getMachineMemOperand(MLD->getPointerInfo(),
4969 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4970 Alignment, MLD->getAAInfo(), MLD->getRanges());
4971
4972 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4973
4974 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4975 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4976 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4977
4978 MMO = DAG.getMachineFunction().
4979 getMachineMemOperand(MLD->getPointerInfo(),
4980 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
4981 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4982
4983 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4984
4985 AddToWorklist(Lo.getNode());
4986 AddToWorklist(Hi.getNode());
4987
4988 // Build a factor node to remember that this load is independent of the
4989 // other one.
4990 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4991 Hi.getValue(1));
4992
4993 // Legalized the chain result - switch anything that used the old chain to
4994 // use the new one.
4995 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4996
4997 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4998
4999 SDValue RetOps[] = { LoadRes, Chain };
5000 return DAG.getMergeValues(RetOps, DL);
5001 }
5002 return SDValue();
5003}
5004
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005005SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5006 SDValue N0 = N->getOperand(0);
5007 SDValue N1 = N->getOperand(1);
5008 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005009 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005010
5011 // Canonicalize integer abs.
5012 // vselect (setg[te] X, 0), X, -X ->
5013 // vselect (setgt X, -1), X, -X ->
5014 // vselect (setl[te] X, 0), -X, X ->
5015 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5016 if (N0.getOpcode() == ISD::SETCC) {
5017 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5018 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5019 bool isAbs = false;
5020 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5021
5022 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5023 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5024 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5025 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5026 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5027 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5028 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5029
5030 if (isAbs) {
5031 EVT VT = LHS.getValueType();
5032 SDValue Shift = DAG.getNode(
5033 ISD::SRA, DL, VT, LHS,
5034 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5035 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005036 AddToWorklist(Shift.getNode());
5037 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005038 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5039 }
5040 }
5041
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005042 // If the VSELECT result requires splitting and the mask is provided by a
5043 // SETCC, then split both nodes and its operands before legalization. This
5044 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5045 // and enables future optimizations (e.g. min/max pattern matching on X86).
5046 if (N0.getOpcode() == ISD::SETCC) {
5047 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005048
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005049 // Check if any splitting is required.
5050 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5051 TargetLowering::TypeSplitVector)
5052 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005053
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005054 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005055 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5056 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5057 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005058
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005059 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5060 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005061
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005062 // Add the new VSELECT nodes to the work list in case they need to be split
5063 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005064 AddToWorklist(Lo.getNode());
5065 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005066
5067 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005068 }
5069
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00005070 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5071 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5072 return N1;
5073 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5074 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5075 return N2;
5076
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005077 // The ConvertSelectToConcatVector function is assuming both the above
5078 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5079 // and addressed.
5080 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5081 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5082 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5083 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5084 if (CV.getNode())
5085 return CV;
5086 }
5087
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005088 return SDValue();
5089}
5090
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005091SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5092 SDValue N0 = N->getOperand(0);
5093 SDValue N1 = N->getOperand(1);
5094 SDValue N2 = N->getOperand(2);
5095 SDValue N3 = N->getOperand(3);
5096 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00005097 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005098
Nate Begemanc760f802005-09-19 22:34:01 +00005099 // fold select_cc lhs, rhs, x, x, cc -> x
5100 if (N2 == N3)
5101 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005102
Chris Lattner8b68dec2006-09-20 06:19:26 +00005103 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00005104 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005105 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00005106 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005107 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00005108
Stephen Lin605207f2013-06-15 04:03:33 +00005109 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5110 if (!SCCC->isNullValue())
5111 return N2; // cond always true -> true val
5112 else
5113 return N3; // cond always false -> false val
Mehdi Amini648eff12015-01-14 05:45:24 +00005114 } else if (SCC->getOpcode() == ISD::UNDEF) {
5115 // When the condition is UNDEF, just return the first operand. This is
5116 // coherent the DAG creation, no setcc node is created in this case
5117 return N2;
5118 } else if (SCC.getOpcode() == ISD::SETCC) {
5119 // Fold to a simpler select_cc
Stephen Lin605207f2013-06-15 04:03:33 +00005120 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5121 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5122 SCC.getOperand(2));
Mehdi Amini648eff12015-01-14 05:45:24 +00005123 }
Chris Lattner8b68dec2006-09-20 06:19:26 +00005124 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005125
Chris Lattner6c14c352005-10-18 06:04:22 +00005126 // If we can fold this based on the true/false value, do so.
5127 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005128 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00005129
Nate Begemanc760f802005-09-19 22:34:01 +00005130 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00005131 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00005132}
5133
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005134SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00005135 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00005136 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005137 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00005138}
5139
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005140// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5141// dag node into a ConstantSDNode or a build_vector of constants.
5142// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005143// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005144// Vector extends are not folded if operations are legal; this is to
5145// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005146static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5147 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005148 bool LegalOperations) {
5149 unsigned Opcode = N->getOpcode();
5150 SDValue N0 = N->getOperand(0);
5151 EVT VT = N->getValueType(0);
5152
5153 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5154 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5155
5156 // fold (sext c1) -> c1
5157 // fold (zext c1) -> c1
5158 // fold (aext c1) -> c1
5159 if (isa<ConstantSDNode>(N0))
5160 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5161
5162 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5163 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5164 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005165 EVT SVT = VT.getScalarType();
5166 if (!(VT.isVector() &&
5167 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005168 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00005169 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005170
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005171 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005172 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005173 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5174 unsigned ShAmt = VTBits - EVTBits;
5175 SmallVector<SDValue, 8> Elts;
5176 unsigned NumElts = N0->getNumOperands();
5177 SDLoc DL(N);
5178
5179 for (unsigned i=0; i != NumElts; ++i) {
5180 SDValue Op = N0->getOperand(i);
5181 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005182 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005183 continue;
5184 }
5185
5186 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5187 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5188 if (Opcode == ISD::SIGN_EXTEND)
5189 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005190 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005191 else
5192 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005193 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005194 }
5195
Craig Topper48d114b2014-04-26 18:35:24 +00005196 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005197}
5198
Evan Chenge106e2f2007-10-29 19:58:20 +00005199// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00005200// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00005201// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00005202// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005203static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00005204 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00005205 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00005206 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005207 bool HasCopyToRegUses = false;
5208 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00005209 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5210 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00005211 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00005212 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00005213 if (User == N)
5214 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00005215 if (UI.getUse().getResNo() != N0.getResNo())
5216 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005217 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00005218 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005219 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5220 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5221 // Sign bits will be lost after a zext.
5222 return false;
5223 bool Add = false;
5224 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005225 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00005226 if (UseOp == N0)
5227 continue;
5228 if (!isa<ConstantSDNode>(UseOp))
5229 return false;
5230 Add = true;
5231 }
5232 if (Add)
5233 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005234 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005235 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00005236 // If truncates aren't free and there are users we can't
5237 // extend, it isn't worthwhile.
5238 if (!isTruncFree)
5239 return false;
5240 // Remember if this value is live-out.
5241 if (User->getOpcode() == ISD::CopyToReg)
5242 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00005243 }
5244
5245 if (HasCopyToRegUses) {
5246 bool BothLiveOut = false;
5247 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5248 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005249 SDUse &Use = UI.getUse();
5250 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5251 BothLiveOut = true;
5252 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00005253 }
5254 }
5255 if (BothLiveOut)
5256 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00005257 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00005258 return ExtendNodes.size();
5259 }
5260 return true;
5261}
5262
Craig Toppere0b71182013-07-13 07:43:40 +00005263void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005264 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005265 ISD::NodeType ExtType) {
5266 // Extend SetCC uses if necessary.
5267 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5268 SDNode *SetCC = SetCCs[i];
5269 SmallVector<SDValue, 4> Ops;
5270
5271 for (unsigned j = 0; j != 2; ++j) {
5272 SDValue SOp = SetCC->getOperand(j);
5273 if (SOp == Trunc)
5274 Ops.push_back(ExtLoad);
5275 else
5276 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5277 }
5278
5279 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005280 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005281 }
5282}
5283
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005284SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5285 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005286 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005287
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005288 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5289 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005290 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005291
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005292 // fold (sext (sext x)) -> (sext x)
5293 // fold (sext (aext x)) -> (sext x)
5294 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005295 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005296 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005297
Chris Lattnerfce448f2007-02-26 03:13:59 +00005298 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005299 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5300 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005301 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5302 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005303 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5304 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005305 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005306 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005307 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005308 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005309 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005310 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005311
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005312 // See if the value being truncated is already sign extended. If so, just
5313 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005314 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005315 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5316 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5317 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005318 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005319
Chris Lattnerfce448f2007-02-26 03:13:59 +00005320 if (OpBits == DestBits) {
5321 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5322 // bits, it is already ready.
5323 if (NumSignBits > DestBits-MidBits)
5324 return Op;
5325 } else if (OpBits < DestBits) {
5326 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5327 // bits, just sext from i32.
5328 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005329 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005330 } else {
5331 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5332 // bits, just truncate to i32.
5333 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005334 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005335 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005336
Chris Lattnerfce448f2007-02-26 03:13:59 +00005337 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005338 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5339 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005340 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005341 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005342 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005343 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5344 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005345 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005346 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005347 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005348
Evan Chengbce7c472005-12-14 02:19:23 +00005349 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005350 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005351 // on vectors in one instruction. We only perform this transformation on
5352 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005353 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005354 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005355 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005356 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005357 bool DoXform = true;
5358 SmallVector<SDNode*, 4> SetCCs;
5359 if (!N0.hasOneUse())
5360 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5361 if (DoXform) {
5362 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005363 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005364 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005365 LN0->getBasePtr(), N0.getValueType(),
5366 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005367 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005368 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005369 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005370 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005371 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005372 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005373 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005374 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005375 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005376
5377 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5378 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005379 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5380 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005381 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005382 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005383 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005384 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005385 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005386 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005387 LN0->getBasePtr(), MemVT,
5388 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005389 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005390 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005391 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005392 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005393 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005394 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005395 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005396 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005397
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005398 // fold (sext (and/or/xor (load x), cst)) ->
5399 // (and/or/xor (sextload x), (sext cst))
5400 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5401 N0.getOpcode() == ISD::XOR) &&
5402 isa<LoadSDNode>(N0.getOperand(0)) &&
5403 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005404 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005405 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5406 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005407 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005408 bool DoXform = true;
5409 SmallVector<SDNode*, 4> SetCCs;
5410 if (!N0.hasOneUse())
5411 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5412 SetCCs, TLI);
5413 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005414 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005415 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005416 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005417 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005418 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5419 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005420 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005421 ExtLoad, DAG.getConstant(Mask, VT));
5422 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005423 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005424 N0.getOperand(0).getValueType(), ExtLoad);
5425 CombineTo(N, And);
5426 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005427 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005428 ISD::SIGN_EXTEND);
5429 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5430 }
5431 }
5432 }
5433
Chris Lattner65786b02007-04-11 05:32:27 +00005434 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005435 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005436 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005437 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005438 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005439 TLI.getBooleanContents(N0VT) ==
5440 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005441 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5442 // of the same size as the compared operands. Only optimize sext(setcc())
5443 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005444 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005445
5446 // We know that the # elements of the results is the same as the
5447 // # elements of the compare (and the # elements of the compare result
5448 // for that matter). Check to see that they are the same size. If so,
5449 // we know that the element size of the sext'd result matches the
5450 // element size of the compare operands.
5451 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005452 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005453 N0.getOperand(1),
5454 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005455
Dan Gohmane82c25e2010-04-30 17:19:19 +00005456 // If the desired elements are smaller or larger than the source
5457 // elements we can use a matching integer vector type and then
5458 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005459 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005460 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005461 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005462 N0.getOperand(0), N0.getOperand(1),
5463 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005464 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005465 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005466 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005467
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005468 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005469 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005470 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005471 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005472 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005473 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005474 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005475 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005476 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005477
5478 if (!VT.isVector()) {
5479 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5480 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5481 SDLoc DL(N);
5482 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Hal Finkel98085952014-10-06 20:19:47 +00005483 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005484 N0.getOperand(0), N0.getOperand(1), CC);
Hal Finkel98085952014-10-06 20:19:47 +00005485 return DAG.getSelect(DL, VT, SetCC,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005486 NegOne, DAG.getConstant(0, VT));
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005487 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005488 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005489 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005490
Dan Gohman3eb10f72008-04-28 16:58:24 +00005491 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005492 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005493 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005494 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005495
Evan Chengf1005572010-04-28 07:10:39 +00005496 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005497}
5498
Rafael Espindola8f62b322012-04-09 16:06:03 +00005499// isTruncateOf - If N is a truncate of some other value, return true, record
5500// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5501// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005502// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005503static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5504 APInt &KnownZero) {
5505 APInt KnownOne;
5506 if (N->getOpcode() == ISD::TRUNCATE) {
5507 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005508 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005509 return true;
5510 }
5511
5512 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5513 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5514 return false;
5515
5516 SDValue Op0 = N->getOperand(0);
5517 SDValue Op1 = N->getOperand(1);
5518 assert(Op0.getValueType() == Op1.getValueType());
5519
5520 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5521 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005522 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005523 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005524 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005525 Op = Op0;
5526 else
5527 return false;
5528
Jay Foada0653a32014-05-14 21:14:37 +00005529 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005530
5531 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5532 return false;
5533
5534 return true;
5535}
5536
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005537SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5538 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005539 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005540
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005541 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5542 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005543 return SDValue(Res, 0);
5544
Nate Begeman21158fc2005-09-01 00:19:25 +00005545 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005546 // fold (zext (aext x)) -> (zext x)
5547 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005548 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005549 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005550
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005551 // fold (zext (truncate x)) -> (zext x) or
5552 // (zext (truncate x)) -> (truncate x)
5553 // This is valid when the truncated bits of x are already zero.
5554 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005555 SDValue Op;
5556 APInt KnownZero;
5557 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5558 APInt TruncatedBits =
5559 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5560 APInt(Op.getValueSizeInBits(), 0) :
5561 APInt::getBitsSet(Op.getValueSizeInBits(),
5562 N0.getValueSizeInBits(),
5563 std::min(Op.getValueSizeInBits(),
5564 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005565 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005566 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005567 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005568 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005569 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005570
5571 return Op;
5572 }
5573 }
5574
Evan Cheng464dc9b2007-03-22 01:54:19 +00005575 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5576 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005577 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005578 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5579 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005580 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5581 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005582 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005583 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005584 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005585 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005586 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005587 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005588 }
5589
Chris Lattnera31f0a62006-09-21 06:00:20 +00005590 // fold (zext (truncate x)) -> (and x, mask)
5591 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005592 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005593
5594 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5595 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5596 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5597 if (NarrowLoad.getNode()) {
5598 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5599 if (NarrowLoad.getNode() != N0.getNode()) {
5600 CombineTo(N0.getNode(), NarrowLoad);
5601 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005602 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005603 }
5604 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5605 }
5606
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005607 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005608 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005609 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005610 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005611 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005612 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005613 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005614 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005615 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005616 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005617 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005618
Dan Gohmanad3e5492009-04-08 00:15:30 +00005619 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5620 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005621 if (N0.getOpcode() == ISD::AND &&
5622 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005623 N0.getOperand(1).getOpcode() == ISD::Constant &&
5624 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5625 N0.getValueType()) ||
5626 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005627 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005628 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005629 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005630 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005631 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005632 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005633 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005634 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005635 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005636 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005637 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005638
Evan Chengbce7c472005-12-14 02:19:23 +00005639 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005640 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005641 // on vectors in one instruction. We only perform this transformation on
5642 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005643 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005644 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005645 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005646 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005647 bool DoXform = true;
5648 SmallVector<SDNode*, 4> SetCCs;
5649 if (!N0.hasOneUse())
5650 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5651 if (DoXform) {
5652 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005653 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005654 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005655 LN0->getBasePtr(), N0.getValueType(),
5656 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005657 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005658 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005659 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005660 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005661
Andrew Trickef9de2a2013-05-25 02:42:55 +00005662 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005663 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005664 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005665 }
Evan Chengbce7c472005-12-14 02:19:23 +00005666 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005667
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005668 // fold (zext (and/or/xor (load x), cst)) ->
5669 // (and/or/xor (zextload x), (zext cst))
5670 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5671 N0.getOpcode() == ISD::XOR) &&
5672 isa<LoadSDNode>(N0.getOperand(0)) &&
5673 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005674 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005675 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5676 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005677 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005678 bool DoXform = true;
5679 SmallVector<SDNode*, 4> SetCCs;
5680 if (!N0.hasOneUse())
5681 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5682 SetCCs, TLI);
5683 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005684 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005685 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005686 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005687 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005688 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5689 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005690 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005691 ExtLoad, DAG.getConstant(Mask, VT));
5692 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005693 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005694 N0.getOperand(0).getValueType(), ExtLoad);
5695 CombineTo(N, And);
5696 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005697 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005698 ISD::ZERO_EXTEND);
5699 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5700 }
5701 }
5702 }
5703
Chris Lattner7dac1082005-12-14 19:05:06 +00005704 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5705 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005706 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5707 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005708 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005709 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005710 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005711 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005712 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005713 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005714 LN0->getBasePtr(), MemVT,
5715 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005716 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005717 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005718 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005719 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005720 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005721 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005722 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005723 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005724
Chris Lattner65786b02007-04-11 05:32:27 +00005725 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005726 if (!LegalOperations && VT.isVector() &&
5727 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005728 EVT N0VT = N0.getOperand(0).getValueType();
5729 if (getSetCCResultType(N0VT) == N0.getValueType())
5730 return SDValue();
5731
Evan Chengabd0ad52010-05-19 01:08:17 +00005732 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5733 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005734 EVT EltVT = VT.getVectorElementType();
5735 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5736 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005737 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005738 // We know that the # elements of the results is the same as the
5739 // # elements of the compare (and the # elements of the compare result
5740 // for that matter). Check to see that they are the same size. If so,
5741 // we know that the element size of the sext'd result matches the
5742 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005743 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5744 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005745 N0.getOperand(1),
5746 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005747 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005748 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005749
5750 // If the desired elements are smaller or larger than the source
5751 // elements we can use a matching integer vector type and then
5752 // truncate/sign extend
5753 EVT MatchingElementType =
5754 EVT::getIntegerVT(*DAG.getContext(),
5755 N0VT.getScalarType().getSizeInBits());
5756 EVT MatchingVectorType =
5757 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5758 N0VT.getVectorNumElements());
5759 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005760 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005761 N0.getOperand(1),
5762 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005763 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5764 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005765 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005766 }
5767
5768 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005769 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005770 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005771 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005772 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005773 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005774 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005775
Evan Cheng852c4862009-12-15 03:00:32 +00005776 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005777 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005778 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005779 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5780 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005781 SDValue ShAmt = N0.getOperand(1);
5782 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005783 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005784 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005785 // If the original shl may be shifting out bits, do not perform this
5786 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005787 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5788 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5789 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005790 return SDValue();
5791 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005792
Andrew Trickef9de2a2013-05-25 02:42:55 +00005793 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005794
5795 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005796 if (VT.getSizeInBits() >= 256)
5797 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005798
Chris Lattnere95d1952011-02-13 19:09:16 +00005799 return DAG.getNode(N0.getOpcode(), DL, VT,
5800 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5801 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005802 }
5803
Evan Chengf1005572010-04-28 07:10:39 +00005804 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005805}
5806
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005807SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5808 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005809 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005810
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005811 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5812 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005813 return SDValue(Res, 0);
5814
Chris Lattner812646a2006-05-05 05:58:59 +00005815 // fold (aext (aext x)) -> (aext x)
5816 // fold (aext (zext x)) -> (zext x)
5817 // fold (aext (sext x)) -> (sext x)
5818 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5819 N0.getOpcode() == ISD::ZERO_EXTEND ||
5820 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005821 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005822
Evan Cheng464dc9b2007-03-22 01:54:19 +00005823 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5824 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5825 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005826 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5827 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005828 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5829 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005830 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005831 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005832 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005833 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005834 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005835 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005836 }
5837
Chris Lattner8746e2c2006-09-20 06:29:17 +00005838 // fold (aext (truncate x))
5839 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005840 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005841 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005842 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005843 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005844 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5845 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005846 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005847
Dan Gohmanad3e5492009-04-08 00:15:30 +00005848 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5849 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005850 if (N0.getOpcode() == ISD::AND &&
5851 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005852 N0.getOperand(1).getOpcode() == ISD::Constant &&
5853 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5854 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005855 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005856 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005857 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005858 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005859 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005860 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005861 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005862 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005863 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005864 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005865 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005866
Chris Lattner812646a2006-05-05 05:58:59 +00005867 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005868 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005869 // on vectors in one instruction. We only perform this transformation on
5870 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005871 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005872 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005873 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005874 bool DoXform = true;
5875 SmallVector<SDNode*, 4> SetCCs;
5876 if (!N0.hasOneUse())
5877 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5878 if (DoXform) {
5879 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005880 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005881 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005882 LN0->getBasePtr(), N0.getValueType(),
5883 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005884 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005885 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005886 N0.getValueType(), ExtLoad);
5887 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005888 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005889 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005890 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5891 }
Chris Lattner812646a2006-05-05 05:58:59 +00005892 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005893
Chris Lattner812646a2006-05-05 05:58:59 +00005894 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5895 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5896 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005897 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005898 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005899 N0.hasOneUse()) {
5900 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005901 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005902 EVT MemVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005903 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005904 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5905 VT, LN0->getChain(), LN0->getBasePtr(),
5906 MemVT, LN0->getMemOperand());
5907 CombineTo(N, ExtLoad);
5908 CombineTo(N0.getNode(),
5909 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5910 N0.getValueType(), ExtLoad),
5911 ExtLoad.getValue(1));
5912 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5913 }
Chris Lattner812646a2006-05-05 05:58:59 +00005914 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005915
Chris Lattner65786b02007-04-11 05:32:27 +00005916 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005917 // For vectors:
5918 // aext(setcc) -> vsetcc
5919 // aext(setcc) -> truncate(vsetcc)
5920 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005921 // Only do this before legalize for now.
5922 if (VT.isVector() && !LegalOperations) {
5923 EVT N0VT = N0.getOperand(0).getValueType();
5924 // We know that the # elements of the results is the same as the
5925 // # elements of the compare (and the # elements of the compare result
5926 // for that matter). Check to see that they are the same size. If so,
5927 // we know that the element size of the sext'd result matches the
5928 // element size of the compare operands.
5929 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005930 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005931 N0.getOperand(1),
5932 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005933 // If the desired elements are smaller or larger than the source
5934 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005935 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005936 else {
Hao Liuc636d152014-04-22 09:57:06 +00005937 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005938 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005939 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005940 N0.getOperand(1),
5941 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005942 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005943 }
5944 }
5945
5946 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005947 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005948 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005949 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005950 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005951 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005952 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005953 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005954
Evan Chengf1005572010-04-28 07:10:39 +00005955 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005956}
5957
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005958/// See if the specified operand can be simplified with the knowledge that only
5959/// the bits specified by Mask are used. If so, return the simpler operand,
5960/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005961SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005962 switch (V.getOpcode()) {
5963 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005964 case ISD::Constant: {
5965 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005966 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005967 const APInt &CVal = CV->getAPIntValue();
5968 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005969 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005970 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005971 break;
5972 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005973 case ISD::OR:
5974 case ISD::XOR:
5975 // If the LHS or RHS don't contribute bits to the or, drop them.
5976 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5977 return V.getOperand(1);
5978 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5979 return V.getOperand(0);
5980 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005981 case ISD::SRL:
5982 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005983 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005984 break;
5985 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5986 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005987 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005988
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005989 // Watch out for shift count overflow though.
5990 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005991 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005992 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005993 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005994 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005995 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005996 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005997 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005998 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005999}
6000
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006001/// If the result of a wider load is shifted to right of N bits and then
6002/// truncated to a narrower type and where N is a multiple of number of bits of
6003/// the narrower type, transform it to a narrower load from address + N / num of
6004/// bits of new type. If the result is to be extended, also fold the extension
6005/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006006SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006007 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00006008
Evan Cheng464dc9b2007-03-22 01:54:19 +00006009 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006010 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006011 EVT VT = N->getValueType(0);
6012 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006013
Dan Gohman550c9af2008-08-14 20:04:46 +00006014 // This transformation isn't valid for vector loads.
6015 if (VT.isVector())
6016 return SDValue();
6017
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006018 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00006019 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00006020 if (Opc == ISD::SIGN_EXTEND_INREG) {
6021 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006022 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00006023 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00006024 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00006025 ExtType = ISD::ZEXTLOAD;
6026 N0 = SDValue(N, 0);
6027 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6028 if (!N01) return SDValue();
6029 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6030 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00006031 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006032 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
Richard Osborne272e0842011-01-31 17:41:44 +00006033 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006034
Owen Anderson53aa7a92009-08-10 22:56:29 +00006035 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006036
Chris Lattner9a499e92010-12-22 08:01:44 +00006037 // Do not generate loads of non-round integer types since these can
6038 // be expensive (and would be wrong if the type is not byte sized).
6039 if (!ExtVT.isRound())
6040 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006041
Evan Cheng464dc9b2007-03-22 01:54:19 +00006042 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00006043 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006044 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00006045 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006046 // Is the shift amount a multiple of size of VT?
6047 if ((ShAmt & (EVTBits-1)) == 0) {
6048 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00006049 // Is the load width a multiple of size of VT?
6050 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006051 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006052 }
Wesley Peck527da1b2010-11-23 03:31:01 +00006053
Chris Lattnercafc1e62010-12-22 08:02:57 +00006054 // At this point, we must have a load or else we can't do the transform.
6055 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006056
Chandler Carruthb27041c2012-12-11 00:36:57 +00006057 // Because a SRL must be assumed to *need* to zero-extend the high bits
6058 // (as opposed to anyext the high bits), we can't combine the zextload
6059 // lowering of SRL and an sextload.
6060 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6061 return SDValue();
6062
Chris Lattnera2050552010-10-01 05:36:09 +00006063 // If the shift amount is larger than the input type then we're not
6064 // accessing any of the loaded bytes. If the load was a zextload/extload
6065 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00006066 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00006067 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006068 }
6069 }
6070
Dan Gohman68fb0042010-11-03 01:47:46 +00006071 // If the load is shifted left (and the result isn't shifted back right),
6072 // we can fold the truncate through the shift.
6073 unsigned ShLeftAmt = 0;
6074 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00006075 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006076 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6077 ShLeftAmt = N01->getZExtValue();
6078 N0 = N0.getOperand(0);
6079 }
6080 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00006081
Chris Lattner222374d2010-12-22 07:36:50 +00006082 // If we haven't found a load, we can't narrow it. Don't transform one with
6083 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00006084 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6085 return SDValue();
6086
6087 // Don't change the width of a volatile load.
6088 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6089 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00006090 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006091
Chris Lattner9a499e92010-12-22 08:01:44 +00006092 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00006093 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00006094 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006095
Bill Schmidtd006c692013-01-14 22:04:38 +00006096 // For the transform to be legal, the load must produce only two values
6097 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00006098 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00006099 // transformation is not equivalent, and the downstream logic to replace
6100 // uses gets things wrong.
6101 if (LN0->getNumValues() > 2)
6102 return SDValue();
6103
Benjamin Kramerc7332b22013-07-06 14:05:09 +00006104 // If the load that we're shrinking is an extload and we're not just
6105 // discarding the extension we can't simply shrink the load. Bail.
6106 // TODO: It would be possible to merge the extensions in some cases.
6107 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6108 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6109 return SDValue();
6110
Matt Arsenault810cb622014-12-12 00:00:24 +00006111 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6112 return SDValue();
6113
Chris Lattner222374d2010-12-22 07:36:50 +00006114 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006115
Evan Cheng4c6f9172012-06-26 01:19:33 +00006116 if (PtrType == MVT::Untyped || PtrType.isExtended())
6117 // It's not possible to generate a constant of extended or untyped type.
6118 return SDValue();
6119
Chris Lattner222374d2010-12-22 07:36:50 +00006120 // For big endian targets, we need to adjust the offset to the pointer to
6121 // load the correct bytes.
6122 if (TLI.isBigEndian()) {
6123 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6124 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6125 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006126 }
6127
Chris Lattner222374d2010-12-22 07:36:50 +00006128 uint64_t PtrOff = ShAmt / 8;
6129 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006130 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00006131 PtrType, LN0->getBasePtr(),
6132 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006133 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00006134
Chris Lattner9a499e92010-12-22 08:01:44 +00006135 SDValue Load;
6136 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006137 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006138 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006139 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00006140 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00006141 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006142 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006143 LN0->getPointerInfo().getWithOffset(PtrOff),
6144 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00006145 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00006146
6147 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006148 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00006149 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00006150
6151 // Shift the result left, if we've swallowed a left shift.
6152 SDValue Result = Load;
6153 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00006154 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00006155 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6156 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00006157 // If the shift amount is as large as the result size (but, presumably,
6158 // no larger than the source) then the useful bits of the result are
6159 // zero; we can't simply return the shortened shift, because the result
6160 // of that operation is undefined.
6161 if (ShLeftAmt >= VT.getSizeInBits())
6162 Result = DAG.getConstant(0, VT);
6163 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006164 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00006165 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00006166 }
6167
6168 // Return the new loaded value.
6169 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006170}
6171
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006172SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6173 SDValue N0 = N->getOperand(0);
6174 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006175 EVT VT = N->getValueType(0);
6176 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00006177 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006178 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006179
Nate Begeman21158fc2005-09-01 00:19:25 +00006180 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00006181 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006182 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006183
Chris Lattner2a4d7b82006-05-06 22:43:44 +00006184 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00006185 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00006186 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006187
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006188 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6189 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006190 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006191 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006192 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00006193
Dan Gohman345d63c2008-07-31 00:50:31 +00006194 // fold (sext_in_reg (sext x)) -> (sext x)
6195 // fold (sext_in_reg (aext x)) -> (sext x)
6196 // if x is small enough.
6197 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6198 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00006199 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6200 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006201 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00006202 }
6203
Chris Lattner9ad59152007-04-17 19:03:21 +00006204 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00006205 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006206 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006207
Chris Lattner9ad59152007-04-17 19:03:21 +00006208 // fold operands of sext_in_reg based on knowledge that the top bits are not
6209 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006210 if (SimplifyDemandedBits(SDValue(N, 0)))
6211 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006212
Evan Cheng464dc9b2007-03-22 01:54:19 +00006213 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6214 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006215 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006216 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00006217 return NarrowLoad;
6218
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006219 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006220 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00006221 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6222 if (N0.getOpcode() == ISD::SRL) {
6223 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00006224 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006225 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00006226 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00006227 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00006228 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006229 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006230 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00006231 }
6232 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006233
Nate Begeman02b23c62005-10-13 03:11:28 +00006234 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00006235 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006236 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006237 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006238 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006239 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006240 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006241 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006242 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006243 LN0->getBasePtr(), EVT,
6244 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006245 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006246 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006247 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006248 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006249 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006250 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00006251 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006252 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006253 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006254 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006255 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006256 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006257 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006258 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006259 LN0->getBasePtr(), EVT,
6260 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006261 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006262 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006263 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006264 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00006265
6266 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6267 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6268 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6269 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006270 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006271 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006272 BSwap, N1);
6273 }
6274
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006275 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6276 // into a build_vector.
6277 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6278 SmallVector<SDValue, 8> Elts;
6279 unsigned NumElts = N0->getNumOperands();
6280 unsigned ShAmt = VTBits - EVTBits;
6281
6282 for (unsigned i = 0; i != NumElts; ++i) {
6283 SDValue Op = N0->getOperand(i);
6284 if (Op->getOpcode() == ISD::UNDEF) {
6285 Elts.push_back(Op);
6286 continue;
6287 }
6288
6289 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006290 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6291 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006292 Op.getValueType()));
6293 }
6294
Craig Topper48d114b2014-04-26 18:35:24 +00006295 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006296 }
6297
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006298 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006299}
6300
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006301SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6302 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006303 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006304 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006305
6306 // noop truncate
6307 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006308 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006309 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006310 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006311 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006312 // fold (truncate (truncate x)) -> (truncate x)
6313 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006314 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006315 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006316 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6317 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006318 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006319 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006320 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006321 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006322 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006323 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006324 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006325 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006326 // if the source and dest are the same type, we can drop both the extend
6327 // and the truncate.
6328 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006329 }
Evan Chengd63baea2007-03-21 20:14:05 +00006330
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006331 // Fold extract-and-trunc into a narrow extract. For example:
6332 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6333 // i32 y = TRUNCATE(i64 x)
6334 // -- becomes --
6335 // v16i8 b = BITCAST (v2i64 val)
6336 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6337 //
6338 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006339 // creates this pattern) and before operation legalization after which
6340 // we need to be more careful about the vector instructions that we generate.
6341 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006342 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006343
6344 EVT VecTy = N0.getOperand(0).getValueType();
6345 EVT ExTy = N0.getValueType();
6346 EVT TrTy = N->getValueType(0);
6347
6348 unsigned NumElem = VecTy.getVectorNumElements();
6349 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6350
6351 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6352 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6353
6354 SDValue EltNo = N0->getOperand(1);
6355 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6356 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006357 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006358 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6359
Andrew Trickef9de2a2013-05-25 02:42:55 +00006360 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006361 NVT, N0.getOperand(0));
6362
6363 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006364 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006365 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006366 }
6367 }
6368
Matt Arsenault3332b702014-07-10 18:21:04 +00006369 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6370 if (N0.getOpcode() == ISD::SELECT) {
6371 EVT SrcVT = N0.getValueType();
6372 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6373 TLI.isTruncateFree(SrcVT, VT)) {
6374 SDLoc SL(N0);
6375 SDValue Cond = N0.getOperand(0);
6376 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6377 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6378 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6379 }
6380 }
6381
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006382 // Fold a series of buildvector, bitcast, and truncate if possible.
6383 // For example fold
6384 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6385 // (2xi32 (buildvector x, y)).
6386 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6387 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6388 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6389 N0.getOperand(0).hasOneUse()) {
6390
6391 SDValue BuildVect = N0.getOperand(0);
6392 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6393 EVT TruncVecEltTy = VT.getVectorElementType();
6394
6395 // Check that the element types match.
6396 if (BuildVectEltTy == TruncVecEltTy) {
6397 // Now we only need to compute the offset of the truncated elements.
6398 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6399 unsigned TruncVecNumElts = VT.getVectorNumElements();
6400 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6401
6402 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6403 "Invalid number of elements");
6404
6405 SmallVector<SDValue, 8> Opnds;
6406 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6407 Opnds.push_back(BuildVect.getOperand(i));
6408
Craig Topper48d114b2014-04-26 18:35:24 +00006409 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006410 }
6411 }
6412
Chris Lattner5e6fe052007-10-13 06:35:54 +00006413 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006414 // only the low bits are being used.
6415 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006416 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006417 // may have different active low bits.
6418 if (!VT.isVector()) {
6419 SDValue Shorter =
6420 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6421 VT.getSizeInBits()));
6422 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006423 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006424 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006425 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006426 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006427 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6428 SDValue Reduced = ReduceLoadWidth(N);
6429 if (Reduced.getNode())
6430 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006431 // Handle the case where the load remains an extending load even
6432 // after truncation.
6433 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6434 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6435 if (!LN0->isVolatile() &&
6436 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6437 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6438 VT, LN0->getChain(), LN0->getBasePtr(),
6439 LN0->getMemoryVT(),
6440 LN0->getMemOperand());
6441 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6442 return NewLoad;
6443 }
6444 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006445 }
Michael Liao3ac82012012-10-17 23:45:54 +00006446 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6447 // where ... are all 'undef'.
6448 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6449 SmallVector<EVT, 8> VTs;
6450 SDValue V;
6451 unsigned Idx = 0;
6452 unsigned NumDefs = 0;
6453
6454 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6455 SDValue X = N0.getOperand(i);
6456 if (X.getOpcode() != ISD::UNDEF) {
6457 V = X;
6458 Idx = i;
6459 NumDefs++;
6460 }
6461 // Stop if more than one members are non-undef.
6462 if (NumDefs > 1)
6463 break;
6464 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6465 VT.getVectorElementType(),
6466 X.getValueType().getVectorNumElements()));
6467 }
6468
6469 if (NumDefs == 0)
6470 return DAG.getUNDEF(VT);
6471
6472 if (NumDefs == 1) {
6473 assert(V.getNode() && "The single defined operand is empty!");
6474 SmallVector<SDValue, 8> Opnds;
6475 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6476 if (i != Idx) {
6477 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6478 continue;
6479 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006480 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006481 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006482 Opnds.push_back(NV);
6483 }
Craig Topper48d114b2014-04-26 18:35:24 +00006484 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006485 }
6486 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006487
6488 // Simplify the operands using demanded-bits information.
6489 if (!VT.isVector() &&
6490 SimplifyDemandedBits(SDValue(N, 0)))
6491 return SDValue(N, 0);
6492
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006493 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006494}
6495
Evan Chengb980f6f2008-05-12 23:04:07 +00006496static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006497 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006498 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006499 return Elt.getNode();
6500 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006501}
6502
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006503/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006504/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006505SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006506 assert(N->getOpcode() == ISD::BUILD_PAIR);
6507
Nate Begeman624690c2009-06-05 21:37:30 +00006508 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6509 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006510 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006511 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006512 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006513 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006514
Evan Chengb980f6f2008-05-12 23:04:07 +00006515 if (ISD::isNON_EXTLoad(LD2) &&
6516 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006517 // If both are volatile this would reduce the number of volatile loads.
6518 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006519 !LD1->isVolatile() &&
6520 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006521 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006522 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006523 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006524 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006525
Duncan Sands8651e9c2008-06-13 19:07:40 +00006526 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006527 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006528 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006529 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006530 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006531 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006532
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006533 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006534}
6535
Wesley Peck527da1b2010-11-23 03:31:01 +00006536SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006537 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006538 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006539
Dan Gohmana8665142007-06-25 16:23:39 +00006540 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6541 // Only do this before legalize, since afterward the target may be depending
6542 // on the bitconvert.
6543 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006544 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006545 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006546 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006547 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006548
Owen Anderson53aa7a92009-08-10 22:56:29 +00006549 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006550 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006551 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006552 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006553 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006554 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006555
Dan Gohman921ddd62008-09-05 01:58:21 +00006556 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006557 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006558 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006559 if (Res.getNode() != N) {
6560 if (!LegalOperations ||
6561 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6562 return Res;
6563
6564 // Folding it resulted in an illegal node, and it's too late to
6565 // do that. Clean up the old node and forego the transformation.
6566 // Ideally this won't happen very often, because instcombine
6567 // and the earlier dagcombine runs (where illegal nodes are
6568 // permitted) should have folded most of them already.
Chandler Carruth18066972014-08-02 10:02:07 +00006569 deleteAndRecombine(Res.getNode());
Dan Gohman733a64d2009-08-10 23:15:10 +00006570 }
Chris Lattnera1874602005-12-23 05:30:37 +00006571 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006572
Bill Wendling4e0a6152009-01-30 22:44:24 +00006573 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006574 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006575 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006576 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006577
Chris Lattner54560f62005-12-23 05:44:41 +00006578 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006579 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006580 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006581 // Do not change the width of a volatile load.
6582 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006583 // Do not remove the cast if the types differ in endian layout.
6584 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6585 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006586 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6587 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006588 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006589 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006590 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006591 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006592
Evan Chenga4cf58a2007-05-07 21:27:48 +00006593 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006594 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006595 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006596 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006597 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006598 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006599 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006600 return Load;
6601 }
Chris Lattner54560f62005-12-23 05:44:41 +00006602 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006603
Bill Wendling4e0a6152009-01-30 22:44:24 +00006604 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6605 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006606 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006607 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6608 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006609 N0.getNode()->hasOneUse() && VT.isInteger() &&
6610 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006611 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006612 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006613 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006614
Duncan Sands13237ac2008-06-06 12:08:01 +00006615 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006616 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006617 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006618 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006619 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006620 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006621 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006622 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006623
Bill Wendling4e0a6152009-01-30 22:44:24 +00006624 // fold (bitconvert (fcopysign cst, x)) ->
6625 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6626 // Note that we don't handle (copysign x, cst) because this can always be
6627 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006628 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006629 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006630 VT.isInteger() && !VT.isVector()) {
6631 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006632 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006633 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006634 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006635 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006636 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006637
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006638 // If X has a different width than the result/lhs, sext it or truncate it.
6639 unsigned VTWidth = VT.getSizeInBits();
6640 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006641 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006642 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006643 } else if (OrigXWidth > VTWidth) {
6644 // To get the sign bit in the right place, we have to shift it right
6645 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006646 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006647 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006648 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006649 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006650 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006651 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006652 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006653
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006654 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006655 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006656 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006657 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006658
Andrew Trickef9de2a2013-05-25 02:42:55 +00006659 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006660 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006661 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006662 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006663 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006664
Andrew Trickef9de2a2013-05-25 02:42:55 +00006665 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006666 }
Chris Lattner888560d2008-01-27 17:42:27 +00006667 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006668
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006669 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006670 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006671 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6672 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006673 return CombineLD;
6674 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006675
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006676 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006677}
6678
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006679SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006680 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006681 return CombineConsecutiveLoads(N, VT);
6682}
6683
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006684/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6685/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006686SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006687ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006688 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006689
Chris Lattnere4e64b62006-04-02 02:53:43 +00006690 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006691 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006692
Duncan Sands13237ac2008-06-06 12:08:01 +00006693 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6694 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006695
Chris Lattnere4e64b62006-04-02 02:53:43 +00006696 // If this is a conversion of N elements of one type to N elements of another
6697 // type, convert each element. This handles FP<->INT cases.
6698 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006699 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6700 BV->getValueType(0).getVectorNumElements());
6701
6702 // Due to the FP element handling below calling this routine recursively,
6703 // we can end up with a scalar-to-vector node here.
6704 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006705 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6706 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006707 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006708
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006709 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006710 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006711 SDValue Op = BV->getOperand(i);
6712 // If the vector element type is not legal, the BUILD_VECTOR operands
6713 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006714 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006715 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6716 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006717 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006718 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006719 }
Craig Topper48d114b2014-04-26 18:35:24 +00006720 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006721 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006722
Chris Lattnere4e64b62006-04-02 02:53:43 +00006723 // Otherwise, we're growing or shrinking the elements. To avoid having to
6724 // handle annoying details of growing/shrinking FP values, we convert them to
6725 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006726 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006727 // Convert the input float vector to a int vector where the elements are the
6728 // same sizes.
Owen Anderson117c9e82009-08-12 00:36:31 +00006729 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006730 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006731 SrcEltVT = IntVT;
6732 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006733
Chris Lattnere4e64b62006-04-02 02:53:43 +00006734 // Now we know the input is an integer vector. If the output is a FP type,
6735 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006736 if (DstEltVT.isFloatingPoint()) {
Owen Anderson117c9e82009-08-12 00:36:31 +00006737 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006738 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006739
Chris Lattnere4e64b62006-04-02 02:53:43 +00006740 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006741 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006742 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006743
Chris Lattnere4e64b62006-04-02 02:53:43 +00006744 // Okay, we know the src/dst types are both integers of differing types.
6745 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006746 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006747 if (SrcBitSize < DstBitSize) {
6748 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006749
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006750 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006751 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006752 i += NumInputsPerOutput) {
6753 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006754 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006755 bool EltIsUndef = true;
6756 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6757 // Shift the previously computed bits over.
6758 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006759 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006760 if (Op.getOpcode() == ISD::UNDEF) continue;
6761 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006762
Jay Foad583abbc2010-12-07 08:25:19 +00006763 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006764 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006765 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006766
Chris Lattnere4e64b62006-04-02 02:53:43 +00006767 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006768 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006769 else
6770 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6771 }
6772
Owen Anderson117c9e82009-08-12 00:36:31 +00006773 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006774 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006775 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006776
Chris Lattnere4e64b62006-04-02 02:53:43 +00006777 // Finally, this must be the case where we are shrinking elements: each input
6778 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006779 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006780 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006781 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6782 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006783 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006784
Dan Gohmana8665142007-06-25 16:23:39 +00006785 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006786 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6787 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006788 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006789 continue;
6790 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006791
Jay Foad583abbc2010-12-07 08:25:19 +00006792 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6793 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006794
Chris Lattnere4e64b62006-04-02 02:53:43 +00006795 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006796 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006797 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006798 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006799 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006800 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006801 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006802 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006803 }
6804
6805 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006806 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006807 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6808 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006809
Craig Topper48d114b2014-04-26 18:35:24 +00006810 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006811}
6812
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006813SDValue DAGCombiner::visitFADD(SDNode *N) {
6814 SDValue N0 = N->getOperand(0);
6815 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006816 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6817 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006818 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006819 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006820
Dan Gohmana8665142007-06-25 16:23:39 +00006821 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006822 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006823 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006824 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006825 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006826
Lang Hamesa33db652012-06-14 20:37:15 +00006827 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006828 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006829 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006830
Nate Begeman418c6e42005-10-18 00:28:13 +00006831 // canonicalize constant to RHS
6832 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006833 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006834
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006835 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006836 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006837 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006838 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006839 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006840
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006841 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006842 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006843 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006844 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006845 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006846
Sanjay Patel8170dea2014-09-08 17:32:19 +00006847 // If 'unsafe math' is enabled, fold lots of things.
6848 if (Options.UnsafeFPMath) {
6849 // No FP constant should be created after legalization as Instruction
6850 // Selection pass has a hard time dealing with FP constants.
6851 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006852
Sanjay Patel8170dea2014-09-08 17:32:19 +00006853 // fold (fadd A, 0) -> A
6854 if (N1CFP && N1CFP->getValueAPF().isZero())
6855 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006856
Sanjay Patel8170dea2014-09-08 17:32:19 +00006857 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6858 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6859 isa<ConstantFPSDNode>(N0.getOperand(1)))
6860 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6861 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6862 N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006863
Sanjay Patel8170dea2014-09-08 17:32:19 +00006864 // If allowed, fold (fadd (fneg x), x) -> 0.0
6865 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6866 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006867
Sanjay Patel8170dea2014-09-08 17:32:19 +00006868 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6869 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6870 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006871
Sanjay Patel8170dea2014-09-08 17:32:19 +00006872 // We can fold chains of FADD's of the same value into multiplications.
6873 // This transform is not safe in general because we are reducing the number
6874 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00006875 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6876 if (N0.getOpcode() == ISD::FMUL) {
6877 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6878 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006879
Sanjay Patel8170dea2014-09-08 17:32:19 +00006880 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6881 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6882 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6883 SDValue(CFP01, 0),
6884 DAG.getConstantFP(1.0, VT));
6885 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6886 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006887
Sanjay Patel8170dea2014-09-08 17:32:19 +00006888 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6889 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6890 N1.getOperand(0) == N1.getOperand(1) &&
6891 N0.getOperand(0) == N1.getOperand(0)) {
6892 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6893 SDValue(CFP01, 0),
6894 DAG.getConstantFP(2.0, VT));
6895 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6896 N0.getOperand(0), NewCFP);
6897 }
Owen Andersoncc61f872012-08-30 23:35:16 +00006898 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006899
Sanjay Patel8170dea2014-09-08 17:32:19 +00006900 if (N1.getOpcode() == ISD::FMUL) {
6901 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6902 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006903
Sanjay Patel8170dea2014-09-08 17:32:19 +00006904 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6905 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6906 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6907 SDValue(CFP11, 0),
6908 DAG.getConstantFP(1.0, VT));
6909 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6910 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00006911
Sanjay Patel8170dea2014-09-08 17:32:19 +00006912 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6913 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6914 N0.getOperand(0) == N0.getOperand(1) &&
6915 N1.getOperand(0) == N0.getOperand(0)) {
6916 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6917 SDValue(CFP11, 0),
6918 DAG.getConstantFP(2.0, VT));
6919 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6920 }
Owen Andersoncc61f872012-08-30 23:35:16 +00006921 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00006922
Sanjay Patel8170dea2014-09-08 17:32:19 +00006923 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6924 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6925 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6926 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6927 (N0.getOperand(0) == N1))
6928 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6929 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006930 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006931
Sanjay Patel8170dea2014-09-08 17:32:19 +00006932 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6933 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6934 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6935 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6936 N1.getOperand(0) == N0)
6937 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6938 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006939 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006940
Sanjay Patel8170dea2014-09-08 17:32:19 +00006941 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6942 if (AllowNewConst &&
6943 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00006944 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006945 N1.getOperand(0) == N1.getOperand(1) &&
6946 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006947 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00006948 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006949 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006950 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006951
Lang Hames39fb1d02012-06-19 22:51:23 +00006952 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006953 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00006954 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006955 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006956
6957 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Hal Finkel62ac7362014-09-19 11:42:56 +00006958 if (N0.getOpcode() == ISD::FMUL &&
6959 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006960 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006961 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006962
Michael Liaoec3850122012-09-01 04:09:16 +00006963 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006964 // Note: Commutes FADD operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00006965 if (N1.getOpcode() == ISD::FMUL &&
6966 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006967 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006968 N1.getOperand(0), N1.getOperand(1), N0);
Olivier Sallenave04515322015-01-07 20:54:17 +00006969
Olivier Sallenave32509692015-01-13 15:06:36 +00006970 // When FP_EXTEND nodes are free on the target, and there is an opportunity
6971 // to combine into FMA, arrange such nodes accordingly.
6972 if (TLI.isFPExtFree(VT)) {
6973
6974 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
6975 if (N0.getOpcode() == ISD::FP_EXTEND) {
6976 SDValue N00 = N0.getOperand(0);
6977 if (N00.getOpcode() == ISD::FMUL)
6978 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6979 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6980 N00.getOperand(0)),
6981 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6982 N00.getOperand(1)), N1);
6983 }
6984
6985 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
6986 // Note: Commutes FADD operands.
6987 if (N1.getOpcode() == ISD::FP_EXTEND) {
6988 SDValue N10 = N1.getOperand(0);
6989 if (N10.getOpcode() == ISD::FMUL)
6990 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6991 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6992 N10.getOperand(0)),
6993 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6994 N10.getOperand(1)), N0);
6995 }
6996 }
6997
Hal Finkel33ead6f2015-01-09 00:45:54 +00006998 // More folding opportunities when target permits.
6999 if (TLI.enableAggressiveFMAFusion(VT)) {
Olivier Sallenave32509692015-01-13 15:06:36 +00007000
Hal Finkel33ead6f2015-01-09 00:45:54 +00007001 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7002 if (N0.getOpcode() == ISD::FMA &&
7003 N0.getOperand(2).getOpcode() == ISD::FMUL)
Olivier Sallenave04515322015-01-07 20:54:17 +00007004 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Hal Finkel33ead6f2015-01-09 00:45:54 +00007005 N0.getOperand(0), N0.getOperand(1),
7006 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7007 N0.getOperand(2).getOperand(0),
7008 N0.getOperand(2).getOperand(1),
7009 N1));
Olivier Sallenave04515322015-01-07 20:54:17 +00007010
Hal Finkel33ead6f2015-01-09 00:45:54 +00007011 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7012 if (N1->getOpcode() == ISD::FMA &&
7013 N1.getOperand(2).getOpcode() == ISD::FMUL)
Olivier Sallenave04515322015-01-07 20:54:17 +00007014 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Hal Finkel33ead6f2015-01-09 00:45:54 +00007015 N1.getOperand(0), N1.getOperand(1),
7016 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7017 N1.getOperand(2).getOperand(0),
7018 N1.getOperand(2).getOperand(1),
7019 N0));
Olivier Sallenave04515322015-01-07 20:54:17 +00007020 }
7021 }
7022
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007023 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007024}
7025
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007026SDValue DAGCombiner::visitFSUB(SDNode *N) {
7027 SDValue N0 = N->getOperand(0);
7028 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00007029 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7030 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007031 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007032 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007033 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007034
Dan Gohmana8665142007-06-25 16:23:39 +00007035 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007036 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007037 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007038 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007039 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007040
Nate Begeman418c6e42005-10-18 00:28:13 +00007041 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007042 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007043 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00007044
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007045 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007046 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007047 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007048 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007049
Sanjay Patelae402a32014-08-27 20:57:52 +00007050 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007051 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00007052 // (fsub A, 0) -> A
7053 if (N1CFP && N1CFP->getValueAPF().isZero())
7054 return N0;
7055
7056 // (fsub 0, B) -> -B
7057 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00007058 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00007059 return GetNegatedExpression(N1, DAG, LegalOperations);
7060 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7061 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7062 }
7063
7064 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00007065 if (N0 == N1)
7066 return DAG.getConstantFP(0.0f, VT);
7067
Sanjay Patelae402a32014-08-27 20:57:52 +00007068 // (fsub x, (fadd x, y)) -> (fneg y)
7069 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00007070 if (N1.getOpcode() == ISD::FADD) {
7071 SDValue N10 = N1->getOperand(0);
7072 SDValue N11 = N1->getOperand(1);
7073
Sanjay Patel78614bf2014-08-28 15:53:16 +00007074 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007075 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00007076
Sanjay Patel78614bf2014-08-28 15:53:16 +00007077 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007078 return GetNegatedExpression(N10, DAG, LegalOperations);
7079 }
7080 }
7081
Lang Hames39fb1d02012-06-19 22:51:23 +00007082 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00007083 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00007084 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00007085 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00007086
7087 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Hal Finkel62ac7362014-09-19 11:42:56 +00007088 if (N0.getOpcode() == ISD::FMUL &&
7089 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007090 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00007091 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007092 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00007093
7094 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7095 // Note: Commutes FSUB operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00007096 if (N1.getOpcode() == ISD::FMUL &&
7097 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007098 return DAG.getNode(ISD::FMA, dl, VT,
7099 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00007100 N1.getOperand(0)),
7101 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007102
Stephen Lin8e8424e2013-07-09 00:44:49 +00007103 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00007104 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007105 N0.getOperand(0).getOpcode() == ISD::FMUL &&
Hal Finkel62ac7362014-09-19 11:42:56 +00007106 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7107 TLI.enableAggressiveFMAFusion(VT))) {
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007108 SDValue N00 = N0.getOperand(0).getOperand(0);
7109 SDValue N01 = N0.getOperand(0).getOperand(1);
7110 return DAG.getNode(ISD::FMA, dl, VT,
7111 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7112 DAG.getNode(ISD::FNEG, dl, VT, N1));
7113 }
Olivier Sallenave04515322015-01-07 20:54:17 +00007114
Olivier Sallenave32509692015-01-13 15:06:36 +00007115 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7116 // to combine into FMA, arrange such nodes accordingly.
7117 if (TLI.isFPExtFree(VT)) {
7118
7119 // fold (fsub (fpext (fmul x, y)), z)
7120 // -> (fma (fpext x), (fpext y), (fneg z))
7121 if (N0.getOpcode() == ISD::FP_EXTEND) {
7122 SDValue N00 = N0.getOperand(0);
7123 if (N00.getOpcode() == ISD::FMUL)
7124 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7125 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7126 N00.getOperand(0)),
7127 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7128 N00.getOperand(1)),
7129 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7130 }
7131
7132 // fold (fsub x, (fpext (fmul y, z)))
7133 // -> (fma (fneg (fpext y)), (fpext z), x)
7134 // Note: Commutes FSUB operands.
7135 if (N1.getOpcode() == ISD::FP_EXTEND) {
7136 SDValue N10 = N1.getOperand(0);
7137 if (N10.getOpcode() == ISD::FMUL)
7138 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7139 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7140 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7141 VT, N10.getOperand(0))),
7142 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7143 N10.getOperand(1)),
7144 N0);
7145 }
7146
7147 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7148 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7149 if (N0.getOpcode() == ISD::FP_EXTEND) {
7150 SDValue N00 = N0.getOperand(0);
7151 if (N00.getOpcode() == ISD::FNEG) {
7152 SDValue N000 = N00.getOperand(0);
7153 if (N000.getOpcode() == ISD::FMUL) {
7154 return DAG.getNode(ISD::FMA, dl, VT,
7155 DAG.getNode(ISD::FNEG, dl, VT,
7156 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7157 VT, N000.getOperand(0))),
7158 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7159 N000.getOperand(1)),
7160 DAG.getNode(ISD::FNEG, dl, VT, N1));
7161 }
7162 }
7163 }
7164
7165 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7166 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7167 if (N0.getOpcode() == ISD::FNEG) {
7168 SDValue N00 = N0.getOperand(0);
7169 if (N00.getOpcode() == ISD::FP_EXTEND) {
7170 SDValue N000 = N00.getOperand(0);
7171 if (N000.getOpcode() == ISD::FMUL) {
7172 return DAG.getNode(ISD::FMA, dl, VT,
7173 DAG.getNode(ISD::FNEG, dl, VT,
7174 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7175 VT, N000.getOperand(0))),
7176 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7177 N000.getOperand(1)),
7178 DAG.getNode(ISD::FNEG, dl, VT, N1));
7179 }
7180 }
7181 }
7182 }
7183
Olivier Sallenave04515322015-01-07 20:54:17 +00007184 // More folding opportunities when target permits.
7185 if (TLI.enableAggressiveFMAFusion(VT)) {
7186
7187 // fold (fsub (fma x, y, (fmul u, v)), z)
7188 // -> (fma x, y (fma u, v, (fneg z)))
7189 if (N0.getOpcode() == ISD::FMA &&
7190 N0.getOperand(2).getOpcode() == ISD::FMUL)
7191 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7192 N0.getOperand(0), N0.getOperand(1),
7193 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7194 N0.getOperand(2).getOperand(0),
7195 N0.getOperand(2).getOperand(1),
7196 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7197 N1)));
7198
7199 // fold (fsub x, (fma y, z, (fmul u, v)))
7200 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7201 if (N1.getOpcode() == ISD::FMA &&
7202 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7203 SDValue N20 = N1.getOperand(2).getOperand(0);
7204 SDValue N21 = N1.getOperand(2).getOperand(1);
7205 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7206 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7207 N1.getOperand(0)),
7208 N1.getOperand(1),
7209 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7210 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7211 N20),
7212 N21, N0));
7213 }
7214 }
Lang Hames39fb1d02012-06-19 22:51:23 +00007215 }
7216
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007217 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007218}
7219
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007220SDValue DAGCombiner::visitFMUL(SDNode *N) {
7221 SDValue N0 = N->getOperand(0);
7222 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00007223 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7224 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007225 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007226 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007227
Dan Gohmana8665142007-06-25 16:23:39 +00007228 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007229 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007230 // This just handles C1 * C2 for vectors. Other vector folds are below.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007231 SDValue FoldedVOp = SimplifyVBinOp(N);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007232 if (FoldedVOp.getNode())
7233 return FoldedVOp;
7234 // Canonicalize vector constant to RHS.
7235 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7236 N1.getOpcode() != ISD::BUILD_VECTOR)
7237 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7238 if (BV0->isConstant())
7239 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
Dan Gohman80f9f072007-07-13 20:03:40 +00007240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007241
Nate Begemanec48a1b2005-10-17 20:40:11 +00007242 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007243 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007244 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00007245
Nate Begemanec48a1b2005-10-17 20:40:11 +00007246 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00007247 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007248 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007249
Owen Andersonb5f167c2012-05-02 21:32:35 +00007250 // fold (fmul A, 1.0) -> A
7251 if (N1CFP && N1CFP->isExactlyValue(1.0))
7252 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00007253
Sanjay Patel394c3332014-09-08 20:16:42 +00007254 if (Options.UnsafeFPMath) {
7255 // fold (fmul A, 0) -> 0
7256 if (N1CFP && N1CFP->getValueAPF().isZero())
7257 return N1;
7258
7259 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007260 if (N0.getOpcode() == ISD::FMUL) {
7261 // Fold scalars or any vector constants (not just splats).
7262 // This fold is done in general by InstCombine, but extra fmul insts
7263 // may have been generated during lowering.
7264 SDValue N01 = N0.getOperand(1);
7265 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7266 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7267 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7268 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7269 SDLoc SL(N);
7270 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7271 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7272 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007273 }
7274
Sanjay Patel394c3332014-09-08 20:16:42 +00007275 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007276 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7277 // during an early run of DAGCombiner can prevent folding with fmuls
7278 // inserted during lowering.
7279 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7280 SDLoc SL(N);
7281 const SDValue Two = DAG.getConstantFP(2.0, VT);
7282 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7283 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7284 }
7285 }
7286
Nate Begemanec48a1b2005-10-17 20:40:11 +00007287 // fold (fmul X, 2.0) -> (fadd X, X)
7288 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007289 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007290
Dan Gohmanb7170912009-08-10 16:50:32 +00007291 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00007292 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00007293 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007294 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007295
Bill Wendling3dc5d242009-01-30 22:57:07 +00007296 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007297 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7298 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007299 // Both can be negated for free, check to see if at least one is cheaper
7300 // negated.
7301 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007302 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007303 GetNegatedExpression(N0, DAG, LegalOperations),
7304 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007305 }
7306 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007307
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007308 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007309}
7310
Owen Anderson41b06652012-05-02 22:17:40 +00007311SDValue DAGCombiner::visitFMA(SDNode *N) {
7312 SDValue N0 = N->getOperand(0);
7313 SDValue N1 = N->getOperand(1);
7314 SDValue N2 = N->getOperand(2);
7315 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7316 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7317 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007318 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007319 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007320
7321 // Constant fold FMA.
7322 if (isa<ConstantFPSDNode>(N0) &&
7323 isa<ConstantFPSDNode>(N1) &&
7324 isa<ConstantFPSDNode>(N2)) {
7325 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7326 }
7327
Sanjay Patel78614bf2014-08-28 15:53:16 +00007328 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00007329 if (N0CFP && N0CFP->isZero())
7330 return N2;
7331 if (N1CFP && N1CFP->isZero())
7332 return N2;
7333 }
Owen Anderson41b06652012-05-02 22:17:40 +00007334 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007335 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007336 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007337 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007338
Owen Andersonc7aaf522012-05-30 18:50:39 +00007339 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00007340 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007341 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00007342
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007343 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007344 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007345 N2.getOpcode() == ISD::FMUL &&
7346 N0 == N2.getOperand(0) &&
7347 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7348 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7349 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7350 }
7351
7352
7353 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007354 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007355 N0.getOpcode() == ISD::FMUL && N1CFP &&
7356 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7357 return DAG.getNode(ISD::FMA, dl, VT,
7358 N0.getOperand(0),
7359 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7360 N2);
7361 }
7362
7363 // (fma x, 1, y) -> (fadd x, y)
7364 // (fma x, -1, y) -> (fadd (fneg x), y)
7365 if (N1CFP) {
7366 if (N1CFP->isExactlyValue(1.0))
7367 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7368
7369 if (N1CFP->isExactlyValue(-1.0) &&
7370 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7371 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007372 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007373 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7374 }
7375 }
7376
7377 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007378 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00007379 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007380 DAG.getNode(ISD::FADD, dl, VT,
7381 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007382
7383 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007384 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00007385 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7386 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007387 DAG.getNode(ISD::FADD, dl, VT,
7388 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007389
7390
Owen Anderson41b06652012-05-02 22:17:40 +00007391 return SDValue();
7392}
7393
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007394SDValue DAGCombiner::visitFDIV(SDNode *N) {
7395 SDValue N0 = N->getOperand(0);
7396 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007397 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7398 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007399 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007400 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007401 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007402
Dan Gohmana8665142007-06-25 16:23:39 +00007403 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007404 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007405 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007406 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007407 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007408
Nate Begeman569c4392006-01-18 22:35:16 +00007409 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007410 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007411 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007412
Sanjay Patelb67bd262014-09-21 15:19:15 +00007413 if (Options.UnsafeFPMath) {
7414 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7415 if (N1CFP) {
7416 // Compute the reciprocal 1.0 / c2.
7417 APFloat N1APF = N1CFP->getValueAPF();
7418 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7419 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7420 // Only do the transform if the reciprocal is a legal fp immediate that
7421 // isn't too nasty (eg NaN, denormal, ...).
7422 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7423 (!LegalOperations ||
7424 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7425 // backend)... we should handle this gracefully after Legalize.
7426 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7427 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7428 TLI.isFPImmLegal(Recip, VT)))
7429 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7430 DAG.getConstantFP(Recip, VT));
7431 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007432
Sanjay Patelb67bd262014-09-21 15:19:15 +00007433 // If this FDIV is part of a reciprocal square root, it may be folded
7434 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007435 if (N1.getOpcode() == ISD::FSQRT) {
7436 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007437 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7438 }
7439 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7440 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7441 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007442 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7443 AddToWorklist(RV.getNode());
7444 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7445 }
7446 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7447 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7448 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007449 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7450 AddToWorklist(RV.getNode());
7451 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7452 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00007453 } else if (N1.getOpcode() == ISD::FMUL) {
7454 // Look through an FMUL. Even though this won't remove the FDIV directly,
7455 // it's still worthwhile to get rid of the FSQRT if possible.
7456 SDValue SqrtOp;
7457 SDValue OtherOp;
7458 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7459 SqrtOp = N1.getOperand(0);
7460 OtherOp = N1.getOperand(1);
7461 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7462 SqrtOp = N1.getOperand(1);
7463 OtherOp = N1.getOperand(0);
7464 }
7465 if (SqrtOp.getNode()) {
7466 // We found a FSQRT, so try to make this fold:
7467 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7468 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00007469 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7470 AddToWorklist(RV.getNode());
7471 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7472 }
7473 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007474 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007475
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007476 // Fold into a reciprocal estimate and multiply instead of a real divide.
7477 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7478 AddToWorklist(RV.getNode());
7479 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7480 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00007481 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007482
Bill Wendling3dc5d242009-01-30 22:57:07 +00007483 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007484 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7485 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007486 // Both can be negated for free, check to see if at least one is cheaper
7487 // negated.
7488 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007489 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007490 GetNegatedExpression(N0, DAG, LegalOperations),
7491 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007492 }
7493 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007494
Hao Liu44e5d7a2014-11-21 06:39:58 +00007495 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7496 // reciprocal.
7497 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7498 // Notice that this is not always beneficial. One reason is different target
7499 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7500 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7501 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7502 if (Options.UnsafeFPMath) {
7503 // Skip if current node is a reciprocal.
7504 if (N0CFP && N0CFP->isExactlyValue(1.0))
7505 return SDValue();
7506
7507 SmallVector<SDNode *, 4> Users;
7508 // Find all FDIV users of the same divisor.
7509 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7510 UE = N1.getNode()->use_end();
7511 UI != UE; ++UI) {
7512 SDNode *User = UI.getUse().getUser();
7513 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7514 Users.push_back(User);
7515 }
7516
7517 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7518 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7519 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7520
7521 // Dividend / Divisor -> Dividend * Reciprocal
7522 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7523 if ((*I)->getOperand(0) != FPOne) {
7524 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7525 (*I)->getOperand(0), Reciprocal);
7526 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7527 }
7528 }
7529 return SDValue();
7530 }
7531 }
7532
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007533 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007534}
7535
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007536SDValue DAGCombiner::visitFREM(SDNode *N) {
7537 SDValue N0 = N->getOperand(0);
7538 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007539 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7540 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007541 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007542
Nate Begeman569c4392006-01-18 22:35:16 +00007543 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007544 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007545 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007546
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007547 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007548}
7549
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007550SDValue DAGCombiner::visitFSQRT(SDNode *N) {
Matt Arsenaultbf0db912015-01-13 20:53:23 +00007551 if (DAG.getTarget().Options.UnsafeFPMath &&
7552 !TLI.isFsqrtCheap()) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007553 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007554 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007555 EVT VT = RV.getValueType();
7556 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7557 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007558
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007559 // Unfortunately, RV is now NaN if the input was exactly 0.
7560 // Select out this case and force the answer to 0.
7561 SDValue Zero = DAG.getConstantFP(0.0, VT);
7562 SDValue ZeroCmp =
7563 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7564 N->getOperand(0), Zero, ISD::SETEQ);
7565 AddToWorklist(ZeroCmp.getNode());
7566 AddToWorklist(RV.getNode());
7567
7568 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7569 SDLoc(N), VT, ZeroCmp, Zero, RV);
7570 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007571 }
7572 }
7573 return SDValue();
7574}
7575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007576SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7577 SDValue N0 = N->getOperand(0);
7578 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007579 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7580 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007581 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007582
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007583 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007584 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007585
Chris Lattner3bc40502006-03-05 05:30:57 +00007586 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007587 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007588 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7589 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007590 if (!V.isNegative()) {
7591 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007592 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007593 } else {
7594 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007595 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7596 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007597 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007598 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007599
Chris Lattner3bc40502006-03-05 05:30:57 +00007600 // copysign(fabs(x), y) -> copysign(x, y)
7601 // copysign(fneg(x), y) -> copysign(x, y)
7602 // copysign(copysign(x,z), y) -> copysign(x, y)
7603 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7604 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007605 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007606 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007607
7608 // copysign(x, abs(y)) -> abs(x)
7609 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007610 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007611
Chris Lattner3bc40502006-03-05 05:30:57 +00007612 // copysign(x, copysign(y,z)) -> copysign(x, z)
7613 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007614 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007615 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007616
Chris Lattner3bc40502006-03-05 05:30:57 +00007617 // copysign(x, fp_extend(y)) -> copysign(x, y)
7618 // copysign(x, fp_round(y)) -> copysign(x, y)
7619 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007620 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007621 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007622
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007623 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007624}
7625
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007626SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7627 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007628 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007629 EVT VT = N->getValueType(0);
7630 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007631
Nate Begeman21158fc2005-09-01 00:19:25 +00007632 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007633 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007634 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007635 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007636 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007637 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007638
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007639 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7640 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007641 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7642 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007643 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007644 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007645 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007646 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007647
Alp Tokercb402912014-01-24 17:20:08 +00007648 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007649 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007650 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7651 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7652 !VT.isVector() &&
7653 (!LegalOperations ||
7654 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7655 SDValue Ops[] =
7656 { N0.getOperand(0), N0.getOperand(1),
7657 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7658 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007659 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007660 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007661
Nadav Rotem90560762012-07-23 07:59:50 +00007662 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7663 // (select_cc x, y, 1.0, 0.0,, cc)
7664 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7665 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7666 (!LegalOperations ||
7667 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7668 SDValue Ops[] =
7669 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7670 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7671 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007672 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007673 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007674 }
7675
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007676 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007677}
7678
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007679SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7680 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007681 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007682 EVT VT = N->getValueType(0);
7683 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007684
Nate Begeman21158fc2005-09-01 00:19:25 +00007685 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007686 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007687 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007688 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007689 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007690 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007691
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007692 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7693 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007694 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7695 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007696 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007697 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007698 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007699 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007700
Alp Tokercb402912014-01-24 17:20:08 +00007701 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007702 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007703 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007704
Nadav Rotem90560762012-07-23 07:59:50 +00007705 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7706 (!LegalOperations ||
7707 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7708 SDValue Ops[] =
7709 { N0.getOperand(0), N0.getOperand(1),
7710 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7711 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007712 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007713 }
7714 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007715
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007716 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007717}
7718
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007719SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7720 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007721 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007722 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007723
Nate Begeman21158fc2005-09-01 00:19:25 +00007724 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007725 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007726 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007727
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007728 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007729}
7730
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007731SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7732 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007733 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007734 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007735
Nate Begeman21158fc2005-09-01 00:19:25 +00007736 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007737 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007738 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007739
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007740 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007741}
7742
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007743SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7744 SDValue N0 = N->getOperand(0);
7745 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007746 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007747 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007748
Nate Begeman21158fc2005-09-01 00:19:25 +00007749 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007750 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007751 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007752
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007753 // fold (fp_round (fp_extend x)) -> x
7754 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7755 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007756
Chris Lattner0feb1b02008-01-24 06:45:35 +00007757 // fold (fp_round (fp_round x)) -> (fp_round x)
7758 if (N0.getOpcode() == ISD::FP_ROUND) {
7759 // This is a value preserving truncation if both round's are.
7760 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007761 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007762 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007763 DAG.getIntPtrConstant(IsTrunc));
7764 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007765
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007766 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007767 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007768 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007769 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007770 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007771 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007772 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007773 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007774
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007775 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007776}
7777
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007778SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7779 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007780 EVT VT = N->getValueType(0);
7781 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007782 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007783
Nate Begeman21158fc2005-09-01 00:19:25 +00007784 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007785 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007786 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007787 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007788 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007789
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007790 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007791}
7792
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007793SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7794 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007795 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007796 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007797
Chris Lattner5919b482007-12-29 06:55:23 +00007798 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007799 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007800 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007801 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007802
Nate Begeman21158fc2005-09-01 00:19:25 +00007803 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007804 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007805 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007806
7807 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7808 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007809 if (N0.getOpcode() == ISD::FP_ROUND
7810 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007811 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007812 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007813 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007814 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007815 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007816 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007817 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007818
Chris Lattner72733e52008-01-17 07:00:52 +00007819 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007820 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00007821 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007822 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007823 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007824 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007825 LN0->getBasePtr(), N0.getValueType(),
7826 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007827 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007828 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007829 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007830 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007831 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007833 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007834
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007835 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007836}
7837
Sanjay Patelccd26762014-08-28 21:51:37 +00007838SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7839 SDValue N0 = N->getOperand(0);
7840 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7841 EVT VT = N->getValueType(0);
7842
7843 // fold (fceil c1) -> fceil(c1)
7844 if (N0CFP)
7845 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7846
7847 return SDValue();
7848}
7849
7850SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7851 SDValue N0 = N->getOperand(0);
7852 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7853 EVT VT = N->getValueType(0);
7854
7855 // fold (ftrunc c1) -> ftrunc(c1)
7856 if (N0CFP)
7857 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7858
7859 return SDValue();
7860}
7861
7862SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7863 SDValue N0 = N->getOperand(0);
7864 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7865 EVT VT = N->getValueType(0);
7866
7867 // fold (ffloor c1) -> ffloor(c1)
7868 if (N0CFP)
7869 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7870
7871 return SDValue();
7872}
7873
7874// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007875SDValue DAGCombiner::visitFNEG(SDNode *N) {
7876 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007877 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007878
Craig Topper82384612012-09-11 01:45:21 +00007879 if (VT.isVector()) {
7880 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7881 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007882 }
7883
Sanjay Patelccd26762014-08-28 21:51:37 +00007884 // Constant fold FNEG.
7885 if (isa<ConstantFPSDNode>(N0))
7886 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7887
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007888 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7889 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007890 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007891
Sanjay Patel35d31332014-08-14 15:15:28 +00007892 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007893 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00007894 if (!TLI.isFNegFree(VT) &&
7895 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00007896 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007897 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007898 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007899 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00007900 APInt SignMask;
7901 if (N0.getValueType().isVector()) {
7902 // For a vector, get a mask such as 0x80... per scalar element
7903 // and splat it.
7904 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7905 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7906 } else {
7907 // For a scalar, just generate 0x80...
7908 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7909 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007910 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00007911 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007912 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00007913 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007914 }
7915 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007916
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007917 // (fneg (fmul c, x)) -> (fmul -c, x)
7918 if (N0.getOpcode() == ISD::FMUL) {
7919 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007920 if (CFP1) {
7921 APFloat CVal = CFP1->getValueAPF();
7922 CVal.changeSign();
7923 if (Level >= AfterLegalizeDAG &&
7924 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7925 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7926 return DAG.getNode(
7927 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7928 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7929 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007930 }
7931
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007932 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007933}
7934
Matt Arsenault7c936902014-10-21 23:01:01 +00007935SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7936 SDValue N0 = N->getOperand(0);
7937 SDValue N1 = N->getOperand(1);
7938 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7939 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7940
7941 if (N0CFP && N1CFP) {
7942 const APFloat &C0 = N0CFP->getValueAPF();
7943 const APFloat &C1 = N1CFP->getValueAPF();
7944 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7945 }
7946
7947 if (N0CFP) {
7948 EVT VT = N->getValueType(0);
7949 // Canonicalize to constant on RHS.
7950 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7951 }
7952
7953 return SDValue();
7954}
7955
7956SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7957 SDValue N0 = N->getOperand(0);
7958 SDValue N1 = N->getOperand(1);
7959 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7960 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7961
7962 if (N0CFP && N1CFP) {
7963 const APFloat &C0 = N0CFP->getValueAPF();
7964 const APFloat &C1 = N1CFP->getValueAPF();
7965 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7966 }
7967
7968 if (N0CFP) {
7969 EVT VT = N->getValueType(0);
7970 // Canonicalize to constant on RHS.
7971 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7972 }
7973
7974 return SDValue();
7975}
7976
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007977SDValue DAGCombiner::visitFABS(SDNode *N) {
7978 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007979 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007980
Craig Topper82384612012-09-11 01:45:21 +00007981 if (VT.isVector()) {
7982 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7983 if (FoldedVOp.getNode()) return FoldedVOp;
7984 }
7985
Nate Begeman21158fc2005-09-01 00:19:25 +00007986 // fold (fabs c1) -> fabs(c1)
Sanjay Patelccd26762014-08-28 21:51:37 +00007987 if (isa<ConstantFPSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007988 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007989
Nate Begeman21158fc2005-09-01 00:19:25 +00007990 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007991 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007992 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007993
Nate Begeman21158fc2005-09-01 00:19:25 +00007994 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007995 // fold (fabs (fcopysign x, y)) -> (fabs x)
7996 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007997 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007998
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007999 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008000 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00008001 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008002 N0.getOpcode() == ISD::BITCAST &&
8003 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008004 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008005 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008006 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008007 APInt SignMask;
8008 if (N0.getValueType().isVector()) {
8009 // For a vector, get a mask such as 0x7f... per scalar element
8010 // and splat it.
8011 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8012 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8013 } else {
8014 // For a scalar, just generate 0x7f...
8015 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8016 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008017 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008018 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008019 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008020 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008021 }
8022 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008023
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008024 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008025}
8026
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008027SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8028 SDValue Chain = N->getOperand(0);
8029 SDValue N1 = N->getOperand(1);
8030 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008031
Dan Gohman82e80012009-11-17 00:47:23 +00008032 // If N is a constant we could fold this into a fallthrough or unconditional
8033 // branch. However that doesn't happen very often in normal code, because
8034 // Instcombine/SimplifyCFG should have handled the available opportunities.
8035 // If we did this folding here, it would be necessary to update the
8036 // MachineBasicBlock CFG, which is awkward.
8037
Nate Begeman7e7f4392006-02-01 07:19:44 +00008038 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8039 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008040 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00008041 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8042 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008043 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008044 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00008045 N1.getOperand(0), N1.getOperand(1), N2);
8046 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008047
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008048 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8049 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8050 (N1.getOperand(0).hasOneUse() &&
8051 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00008052 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008053 if (N1.getOpcode() == ISD::TRUNCATE) {
8054 // Look pass the truncate.
8055 Trunc = N1.getNode();
8056 N1 = N1.getOperand(0);
8057 }
Evan Cheng166a4e62010-01-06 19:38:29 +00008058
Bill Wendlingaa28be62009-03-26 06:14:09 +00008059 // Match this pattern so that we can generate simpler code:
8060 //
8061 // %a = ...
8062 // %b = and i32 %a, 2
8063 // %c = srl i32 %b, 1
8064 // brcond i32 %c ...
8065 //
8066 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00008067 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00008068 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00008069 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00008070 // %c = setcc eq %b, 0
8071 // brcond %c ...
8072 //
8073 // This applies only when the AND constant value has one bit set and the
8074 // SRL constant is equal to the log2 of the AND constant. The back-end is
8075 // smart enough to convert the result into a TEST/JMP sequence.
8076 SDValue Op0 = N1.getOperand(0);
8077 SDValue Op1 = N1.getOperand(1);
8078
8079 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00008080 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00008081 SDValue AndOp1 = Op0.getOperand(1);
8082
8083 if (AndOp1.getOpcode() == ISD::Constant) {
8084 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8085
8086 if (AndConst.isPowerOf2() &&
8087 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8088 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008089 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00008090 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00008091 Op0, DAG.getConstant(0, Op0.getValueType()),
8092 ISD::SETNE);
8093
Andrew Trickef9de2a2013-05-25 02:42:55 +00008094 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00008095 MVT::Other, Chain, SetCC, N2);
8096 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8097 // will convert it back to (X & C1) >> C2.
8098 CombineTo(N, NewBRCond, false);
8099 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00008100 if (Trunc)
8101 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008102 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008103 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008104 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008105 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00008106 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00008107 }
8108 }
8109 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008110
8111 if (Trunc)
8112 // Restore N1 if the above transformation doesn't match.
8113 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008114 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008115
Evan Cheng228c31f2010-02-27 07:36:59 +00008116 // Transform br(xor(x, y)) -> br(x != y)
8117 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8118 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8119 SDNode *TheXor = N1.getNode();
8120 SDValue Op0 = TheXor->getOperand(0);
8121 SDValue Op1 = TheXor->getOperand(1);
8122 if (Op0.getOpcode() == Op1.getOpcode()) {
8123 // Avoid missing important xor optimizations.
8124 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008125 if (Tmp.getNode()) {
8126 if (Tmp.getNode() != TheXor) {
8127 DEBUG(dbgs() << "\nReplacing.8 ";
8128 TheXor->dump(&DAG);
8129 dbgs() << "\nWith: ";
8130 Tmp.getNode()->dump(&DAG);
8131 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008132 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008133 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00008134 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008135 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00008136 MVT::Other, Chain, Tmp, N2);
8137 }
8138
Benjamin Kramer93354432013-03-30 21:28:18 +00008139 // visitXOR has changed XOR's operands or replaced the XOR completely,
8140 // bail out.
8141 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00008142 }
8143 }
8144
8145 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8146 bool Equal = false;
8147 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8148 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8149 Op0.getOpcode() == ISD::XOR) {
8150 TheXor = Op0.getNode();
8151 Equal = true;
8152 }
8153
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008154 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00008155 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00008156 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008157 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00008158 SetCCVT,
8159 Op0, Op1,
8160 Equal ? ISD::SETEQ : ISD::SETNE);
8161 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008162 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008163 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008164 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008165 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00008166 MVT::Other, Chain, SetCC, N2);
8167 }
8168 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00008169
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008170 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008171}
8172
Chris Lattnera49e16f2005-10-05 06:47:48 +00008173// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8174//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008175SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00008176 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008177 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008178
Dan Gohman82e80012009-11-17 00:47:23 +00008179 // If N is a constant we could fold this into a fallthrough or unconditional
8180 // branch. However that doesn't happen very often in normal code, because
8181 // Instcombine/SimplifyCFG should have handled the available opportunities.
8182 // If we did this folding here, it would be necessary to update the
8183 // MachineBasicBlock CFG, which is awkward.
8184
Duncan Sands93b66092008-06-09 11:32:28 +00008185 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00008186 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008187 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00008188 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008189 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00008190
Nate Begemanbd7df032005-10-05 21:43:42 +00008191 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00008192 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008193 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008194 N->getOperand(0), Simp.getOperand(2),
8195 Simp.getOperand(0), Simp.getOperand(1),
8196 N->getOperand(4));
8197
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008198 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008199}
8200
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008201/// Return true if 'Use' is a load or a store that uses N as its base pointer
8202/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00008203static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8204 SelectionDAG &DAG,
8205 const TargetLowering &TLI) {
8206 EVT VT;
8207 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8208 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8209 return false;
8210 VT = Use->getValueType(0);
8211 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8212 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8213 return false;
8214 VT = ST->getValue().getValueType();
8215 } else
8216 return false;
8217
Chandler Carruth95f83e02013-01-07 15:14:13 +00008218 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00008219 if (N->getOpcode() == ISD::ADD) {
8220 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8221 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008222 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008223 AM.BaseOffs = Offset->getSExtValue();
8224 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008225 // [reg +/- reg]
8226 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008227 } else if (N->getOpcode() == ISD::SUB) {
8228 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8229 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008230 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008231 AM.BaseOffs = -Offset->getSExtValue();
8232 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008233 // [reg +/- reg]
8234 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008235 } else
8236 return false;
8237
8238 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8239}
8240
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008241/// Try turning a load/store into a pre-indexed load/store when the base
8242/// pointer is an add or subtract and it has other uses besides the load/store.
8243/// After the transformation, the new indexed load/store has effectively folded
8244/// the add/subtract in and all of its other uses are redirected to the
8245/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008246bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008247 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008248 return false;
8249
8250 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008251 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008252 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008253 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008254 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008255 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008256 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00008257 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00008258 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8259 return false;
8260 Ptr = LD->getBasePtr();
8261 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008262 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008263 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008264 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008265 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8266 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8267 return false;
8268 Ptr = ST->getBasePtr();
8269 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008270 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008271 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008272 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008273
Chris Lattnereabc15c2006-11-11 00:56:29 +00008274 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8275 // out. There is no reason to make this a preinc/predec.
8276 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00008277 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008278 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008279
Chris Lattnereabc15c2006-11-11 00:56:29 +00008280 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008281 SDValue BasePtr;
8282 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008283 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8284 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8285 return false;
Hal Finkel25819052013-02-08 21:35:47 +00008286
8287 // Backends without true r+i pre-indexed forms may need to pass a
8288 // constant base with a variable offset so that constant coercion
8289 // will work with the patterns in canonical form.
8290 bool Swapped = false;
8291 if (isa<ConstantSDNode>(BasePtr)) {
8292 std::swap(BasePtr, Offset);
8293 Swapped = true;
8294 }
8295
Evan Cheng044a0a82007-05-03 23:52:19 +00008296 // Don't create a indexed load / store with zero offset.
8297 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008298 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008299 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008300
Chris Lattnera0a80032006-11-11 01:00:15 +00008301 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00008302 // 1) The new base ptr is a frame index.
8303 // 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 +00008304 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00008305 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00008306 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00008307 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00008308
Chris Lattnera0a80032006-11-11 01:00:15 +00008309 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8310 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00008311 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00008312 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008313
Chris Lattnera0a80032006-11-11 01:00:15 +00008314 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008315 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008316 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00008317 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008318 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008319 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008320
Hal Finkel25819052013-02-08 21:35:47 +00008321 // If the offset is a constant, there may be other adds of constants that
8322 // can be folded with this one. We should do this to avoid having to keep
8323 // a copy of the original base pointer.
8324 SmallVector<SDNode *, 16> OtherUses;
8325 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00008326 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00008327 if (Use == Ptr.getNode())
8328 continue;
8329
8330 if (Use->isPredecessorOf(N))
8331 continue;
8332
8333 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8334 OtherUses.clear();
8335 break;
8336 }
8337
8338 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8339 if (Op1.getNode() == BasePtr.getNode())
8340 std::swap(Op0, Op1);
8341 assert(Op0.getNode() == BasePtr.getNode() &&
8342 "Use of ADD/SUB but not an operand");
8343
8344 if (!isa<ConstantSDNode>(Op1)) {
8345 OtherUses.clear();
8346 break;
8347 }
8348
8349 // FIXME: In some cases, we can be smarter about this.
8350 if (Op1.getValueType() != Offset.getValueType()) {
8351 OtherUses.clear();
8352 break;
8353 }
8354
8355 OtherUses.push_back(Use);
8356 }
8357
8358 if (Swapped)
8359 std::swap(BasePtr, Offset);
8360
Evan Chenga4d187b2007-05-24 02:35:39 +00008361 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008362 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00008363
8364 // Caches for hasPredecessorHelper
8365 SmallPtrSet<const SDNode *, 32> Visited;
8366 SmallVector<const SDNode *, 16> Worklist;
8367
Jim Grosbache8160032014-04-11 01:13:13 +00008368 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008369 if (Use == N)
8370 continue;
Lang Hames5a004992011-07-07 04:31:51 +00008371 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008372 return false;
8373
Evan Chengfa832632012-01-13 01:37:24 +00008374 // If Ptr may be folded in addressing mode of other use, then it's
8375 // not profitable to do this transformation.
8376 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008377 RealUse = true;
8378 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008379
Chris Lattnereabc15c2006-11-11 00:56:29 +00008380 if (!RealUse)
8381 return false;
8382
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008383 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008384 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008385 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008386 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008387 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00008388 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008389 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008390 ++PreIndexedNodes;
8391 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008392 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008393 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008394 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008395 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008396 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008397 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008398 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008399 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8400 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008401 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008402 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008403 }
8404
Chris Lattnereabc15c2006-11-11 00:56:29 +00008405 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008406 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008407
Hal Finkel25819052013-02-08 21:35:47 +00008408 if (Swapped)
8409 std::swap(BasePtr, Offset);
8410
8411 // Replace other uses of BasePtr that can be updated to use Ptr
8412 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8413 unsigned OffsetIdx = 1;
8414 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8415 OffsetIdx = 0;
8416 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8417 BasePtr.getNode() && "Expected BasePtr operand");
8418
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008419 // We need to replace ptr0 in the following expression:
8420 // x0 * offset0 + y0 * ptr0 = t0
8421 // knowing that
8422 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00008423 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008424 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8425 // indexed load/store and the expresion that needs to be re-written.
8426 //
8427 // Therefore, we have:
8428 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00008429
8430 ConstantSDNode *CN =
8431 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008432 int X0, X1, Y0, Y1;
8433 APInt Offset0 = CN->getAPIntValue();
8434 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00008435
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008436 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8437 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8438 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8439 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00008440
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008441 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8442
8443 APInt CNV = Offset0;
8444 if (X0 < 0) CNV = -CNV;
8445 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8446 else CNV = CNV - Offset1;
8447
8448 // We can now generate the new expression.
8449 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8450 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8451
8452 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00008453 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00008454 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8455 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00008456 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00008457 }
8458
Chris Lattnereabc15c2006-11-11 00:56:29 +00008459 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008460 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008461 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00008462
8463 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008464}
8465
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008466/// Try to combine a load/store with a add/sub of the base pointer node into a
8467/// post-indexed load/store. The transformation folded the add/subtract into the
8468/// new indexed load/store effectively and all of its uses are redirected to the
8469/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008470bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008471 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008472 return false;
8473
8474 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008475 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008476 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008477 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008478 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008479 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008480 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008481 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8482 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8483 return false;
8484 Ptr = LD->getBasePtr();
8485 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008486 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008487 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008488 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008489 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8490 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8491 return false;
8492 Ptr = ST->getBasePtr();
8493 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008494 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008495 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008496 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008497
Gabor Greiff304a7a2008-08-28 21:40:38 +00008498 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008499 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008500
Jim Grosbache8160032014-04-11 01:13:13 +00008501 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008502 if (Op == N ||
8503 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8504 continue;
8505
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008506 SDValue BasePtr;
8507 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008508 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8509 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00008510 // Don't create a indexed load / store with zero offset.
8511 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008512 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008513 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008514
Chris Lattnereabc15c2006-11-11 00:56:29 +00008515 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00008516 // 1) All uses are load / store ops that use it as base ptr (and
8517 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00008518 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8519 // nor a successor of N. Otherwise, if Op is folded that would
8520 // create a cycle.
8521
Evan Chengcfc05132009-05-06 18:25:01 +00008522 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8523 continue;
8524
Chris Lattnereabc15c2006-11-11 00:56:29 +00008525 // Check for #1.
8526 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008527 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008528 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00008529 continue;
8530
Chris Lattnereabc15c2006-11-11 00:56:29 +00008531 // If all the uses are load / store addresses, then don't do the
8532 // transformation.
8533 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8534 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008535 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00008536 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008537 RealUse = true;
8538 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008539
Chris Lattnereabc15c2006-11-11 00:56:29 +00008540 if (!RealUse) {
8541 TryNext = true;
8542 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00008543 }
8544 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008545 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008546
Chris Lattnereabc15c2006-11-11 00:56:29 +00008547 if (TryNext)
8548 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008549
Chris Lattnereabc15c2006-11-11 00:56:29 +00008550 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00008551 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008552 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00008553 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008554 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008555 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008556 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008557 ++PostIndexedNodes;
8558 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008559 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008560 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008561 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008562 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008563 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008564 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008565 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008566 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008568 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008569 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008570 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008571
Chris Lattnereabc15c2006-11-11 00:56:29 +00008572 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008573 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008574
8575 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008576 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008577 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008578 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008579 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008580 }
8581 }
8582 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008583
Chris Lattnerffad2162006-11-11 00:39:41 +00008584 return false;
8585}
8586
Hal Finkel51e6fa22014-09-02 06:24:04 +00008587/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8588SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8589 ISD::MemIndexedMode AM = LD->getAddressingMode();
8590 assert(AM != ISD::UNINDEXED);
8591 SDValue BP = LD->getOperand(1);
8592 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008593
8594 // Some backends use TargetConstants for load offsets, but don't expect
8595 // TargetConstants in general ADD nodes. We can convert these constants into
8596 // regular Constants (if the constant is not opaque).
8597 assert((Inc.getOpcode() != ISD::TargetConstant ||
8598 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8599 "Cannot split out indexing using opaque target constants");
8600 if (Inc.getOpcode() == ISD::TargetConstant) {
8601 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8602 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8603 ConstInc->getValueType(0));
8604 }
8605
Hal Finkel51e6fa22014-09-02 06:24:04 +00008606 unsigned Opc =
8607 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8608 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8609}
8610
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008611SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008612 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008613 SDValue Chain = LD->getChain();
8614 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008615
Evan Chenga684cd22007-05-01 00:38:21 +00008616 // If load is not volatile and there are no uses of the loaded value (and
8617 // the updated indexed value in case of indexed loads), change uses of the
8618 // chain value into uses of the chain input (i.e. delete the dead load).
8619 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008620 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008621 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008622 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008623 // It's not safe to use the two value CombineTo variant here. e.g.
8624 // v1, chain2 = load chain1, loc
8625 // v2, chain3 = load chain2, loc
8626 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008627 // Now we replace use of chain2 with chain1. This makes the second load
8628 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008629 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008630 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008631 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008632 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008633 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008634 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008635 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008636
Chandler Carruth18066972014-08-02 10:02:07 +00008637 if (N->use_empty())
8638 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008639
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008640 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008641 }
Evan Chengb68343c2007-05-01 08:53:39 +00008642 } else {
8643 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008644 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008645
Hal Finkele19006e2014-09-02 16:05:23 +00008646 // If this load has an opaque TargetConstant offset, then we cannot split
8647 // the indexing into an add/sub directly (that TargetConstant may not be
8648 // valid for a different type of node, and we cannot convert an opaque
8649 // target constant into a regular constant).
8650 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8651 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00008652
8653 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00008654 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00008655 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00008656 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00008657 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00008658 Index = SplitIndexingFromLoad(LD);
8659 // Try to fold the base pointer arithmetic into subsequent loads and
8660 // stores.
8661 AddUsersToWorklist(N);
8662 } else
8663 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00008664 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008665 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008666 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008667 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008668 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008669 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008670 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00008671 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008672 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008673 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008674 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008675 }
Evan Chenga684cd22007-05-01 00:38:21 +00008676 }
8677 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008678
Chris Lattnere260ed82005-10-10 22:04:48 +00008679 // If this load is directly stored, replace the load value with the stored
8680 // value.
8681 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008682 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008683 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008684 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008685 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8686 if (PrevST->getBasePtr() == Ptr &&
8687 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008688 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008689 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008690 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008691
Evan Cheng43cd9e32010-04-01 06:04:33 +00008692 // Try to infer better alignment information than the load already has.
8693 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008694 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008695 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8696 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008697 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008698 LD->getValueType(0),
8699 Chain, Ptr, LD->getPointerInfo(),
8700 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008701 LD->isVolatile(), LD->isNonTemporal(),
8702 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008703 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8704 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008705 }
8706 }
8707
Eric Christopherf55d4712014-10-08 23:38:39 +00008708 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8709 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008710#ifndef NDEBUG
8711 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8712 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8713 UseAA = false;
8714#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008715 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008716 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008717 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008718
Jim Laskey708d0db2006-10-04 16:53:27 +00008719 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008720 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008721 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008722
Jim Laskeyd07be232006-09-25 16:29:54 +00008723 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008724 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008725 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008726 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008727 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008728 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008729 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008730 BetterChain, Ptr, LD->getMemoryVT(),
8731 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008732 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008733
Jim Laskey708d0db2006-10-04 16:53:27 +00008734 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008735 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008736 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008737
Nate Begeman879d8f12009-09-15 00:18:30 +00008738 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008739 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008740
Jim Laskeydcf983c2006-10-13 23:32:28 +00008741 // Replace uses with load result and token factor. Don't add users
8742 // to work list.
8743 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008744 }
8745 }
8746
Evan Cheng357017f2006-11-03 03:06:21 +00008747 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008748 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008749 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008750
Quentin Colombetde0e0622013-10-11 18:29:42 +00008751 // Try to slice up N to more direct loads if the slices are mapped to
8752 // different register banks or pairing can take place.
8753 if (SliceUpLoad(N))
8754 return SDValue(N, 0);
8755
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008756 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008757}
8758
Quentin Colombetde0e0622013-10-11 18:29:42 +00008759namespace {
8760/// \brief Helper structure used to slice a load in smaller loads.
8761/// Basically a slice is obtained from the following sequence:
8762/// Origin = load Ty1, Base
8763/// Shift = srl Ty1 Origin, CstTy Amount
8764/// Inst = trunc Shift to Ty2
8765///
8766/// Then, it will be rewriten into:
8767/// Slice = load SliceTy, Base + SliceOffset
8768/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8769///
8770/// SliceTy is deduced from the number of bits that are actually used to
8771/// build Inst.
8772struct LoadedSlice {
8773 /// \brief Helper structure used to compute the cost of a slice.
8774 struct Cost {
8775 /// Are we optimizing for code size.
8776 bool ForCodeSize;
8777 /// Various cost.
8778 unsigned Loads;
8779 unsigned Truncates;
8780 unsigned CrossRegisterBanksCopies;
8781 unsigned ZExts;
8782 unsigned Shift;
8783
8784 Cost(bool ForCodeSize = false)
8785 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8786 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8787
8788 /// \brief Get the cost of one isolated slice.
8789 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8790 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8791 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8792 EVT TruncType = LS.Inst->getValueType(0);
8793 EVT LoadedType = LS.getLoadedType();
8794 if (TruncType != LoadedType &&
8795 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8796 ZExts = 1;
8797 }
8798
8799 /// \brief Account for slicing gain in the current cost.
8800 /// Slicing provide a few gains like removing a shift or a
8801 /// truncate. This method allows to grow the cost of the original
8802 /// load with the gain from this slice.
8803 void addSliceGain(const LoadedSlice &LS) {
8804 // Each slice saves a truncate.
8805 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8806 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8807 LS.Inst->getOperand(0).getValueType()))
8808 ++Truncates;
8809 // If there is a shift amount, this slice gets rid of it.
8810 if (LS.Shift)
8811 ++Shift;
8812 // If this slice can merge a cross register bank copy, account for it.
8813 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8814 ++CrossRegisterBanksCopies;
8815 }
8816
8817 Cost &operator+=(const Cost &RHS) {
8818 Loads += RHS.Loads;
8819 Truncates += RHS.Truncates;
8820 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8821 ZExts += RHS.ZExts;
8822 Shift += RHS.Shift;
8823 return *this;
8824 }
8825
8826 bool operator==(const Cost &RHS) const {
8827 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8828 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8829 ZExts == RHS.ZExts && Shift == RHS.Shift;
8830 }
8831
8832 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8833
8834 bool operator<(const Cost &RHS) const {
8835 // Assume cross register banks copies are as expensive as loads.
8836 // FIXME: Do we want some more target hooks?
8837 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8838 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8839 // Unless we are optimizing for code size, consider the
8840 // expensive operation first.
8841 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8842 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8843 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8844 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8845 }
8846
8847 bool operator>(const Cost &RHS) const { return RHS < *this; }
8848
8849 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8850
8851 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8852 };
8853 // The last instruction that represent the slice. This should be a
8854 // truncate instruction.
8855 SDNode *Inst;
8856 // The original load instruction.
8857 LoadSDNode *Origin;
8858 // The right shift amount in bits from the original load.
8859 unsigned Shift;
8860 // The DAG from which Origin came from.
8861 // This is used to get some contextual information about legal types, etc.
8862 SelectionDAG *DAG;
8863
Craig Topperc0196b12014-04-14 00:51:57 +00008864 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8865 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008866 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8867
8868 LoadedSlice(const LoadedSlice &LS)
8869 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8870
8871 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8872 /// \return Result is \p BitWidth and has used bits set to 1 and
8873 /// not used bits set to 0.
8874 APInt getUsedBits() const {
8875 // Reproduce the trunc(lshr) sequence:
8876 // - Start from the truncated value.
8877 // - Zero extend to the desired bit width.
8878 // - Shift left.
8879 assert(Origin && "No original load to compare against.");
8880 unsigned BitWidth = Origin->getValueSizeInBits(0);
8881 assert(Inst && "This slice is not bound to an instruction");
8882 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8883 "Extracted slice is bigger than the whole type!");
8884 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8885 UsedBits.setAllBits();
8886 UsedBits = UsedBits.zext(BitWidth);
8887 UsedBits <<= Shift;
8888 return UsedBits;
8889 }
8890
8891 /// \brief Get the size of the slice to be loaded in bytes.
8892 unsigned getLoadedSize() const {
8893 unsigned SliceSize = getUsedBits().countPopulation();
8894 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8895 return SliceSize / 8;
8896 }
8897
8898 /// \brief Get the type that will be loaded for this slice.
8899 /// Note: This may not be the final type for the slice.
8900 EVT getLoadedType() const {
8901 assert(DAG && "Missing context");
8902 LLVMContext &Ctxt = *DAG->getContext();
8903 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8904 }
8905
8906 /// \brief Get the alignment of the load used for this slice.
8907 unsigned getAlignment() const {
8908 unsigned Alignment = Origin->getAlignment();
8909 unsigned Offset = getOffsetFromBase();
8910 if (Offset != 0)
8911 Alignment = MinAlign(Alignment, Alignment + Offset);
8912 return Alignment;
8913 }
8914
8915 /// \brief Check if this slice can be rewritten with legal operations.
8916 bool isLegal() const {
8917 // An invalid slice is not legal.
8918 if (!Origin || !Inst || !DAG)
8919 return false;
8920
8921 // Offsets are for indexed load only, we do not handle that.
8922 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8923 return false;
8924
8925 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8926
8927 // Check that the type is legal.
8928 EVT SliceType = getLoadedType();
8929 if (!TLI.isTypeLegal(SliceType))
8930 return false;
8931
8932 // Check that the load is legal for this type.
8933 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8934 return false;
8935
8936 // Check that the offset can be computed.
8937 // 1. Check its type.
8938 EVT PtrType = Origin->getBasePtr().getValueType();
8939 if (PtrType == MVT::Untyped || PtrType.isExtended())
8940 return false;
8941
8942 // 2. Check that it fits in the immediate.
8943 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8944 return false;
8945
8946 // 3. Check that the computation is legal.
8947 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8948 return false;
8949
8950 // Check that the zext is legal if it needs one.
8951 EVT TruncateType = Inst->getValueType(0);
8952 if (TruncateType != SliceType &&
8953 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8954 return false;
8955
8956 return true;
8957 }
8958
8959 /// \brief Get the offset in bytes of this slice in the original chunk of
8960 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008961 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008962 uint64_t getOffsetFromBase() const {
8963 assert(DAG && "Missing context.");
8964 bool IsBigEndian =
8965 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8966 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8967 uint64_t Offset = Shift / 8;
8968 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8969 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8970 "The size of the original loaded type is not a multiple of a"
8971 " byte.");
8972 // If Offset is bigger than TySizeInBytes, it means we are loading all
8973 // zeros. This should have been optimized before in the process.
8974 assert(TySizeInBytes > Offset &&
8975 "Invalid shift amount for given loaded size");
8976 if (IsBigEndian)
8977 Offset = TySizeInBytes - Offset - getLoadedSize();
8978 return Offset;
8979 }
8980
8981 /// \brief Generate the sequence of instructions to load the slice
8982 /// represented by this object and redirect the uses of this slice to
8983 /// this new sequence of instructions.
8984 /// \pre this->Inst && this->Origin are valid Instructions and this
8985 /// object passed the legal check: LoadedSlice::isLegal returned true.
8986 /// \return The last instruction of the sequence used to load the slice.
8987 SDValue loadSlice() const {
8988 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8989 const SDValue &OldBaseAddr = Origin->getBasePtr();
8990 SDValue BaseAddr = OldBaseAddr;
8991 // Get the offset in that chunk of bytes w.r.t. the endianess.
8992 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8993 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8994 if (Offset) {
8995 // BaseAddr = BaseAddr + Offset.
8996 EVT ArithType = BaseAddr.getValueType();
8997 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8998 DAG->getConstant(Offset, ArithType));
8999 }
9000
9001 // Create the type of the loaded slice according to its size.
9002 EVT SliceType = getLoadedType();
9003
9004 // Create the load for the slice.
9005 SDValue LastInst = DAG->getLoad(
9006 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9007 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9008 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9009 // If the final type is not the same as the loaded type, this means that
9010 // we have to pad with zero. Create a zero extend for that.
9011 EVT FinalType = Inst->getValueType(0);
9012 if (SliceType != FinalType)
9013 LastInst =
9014 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9015 return LastInst;
9016 }
9017
9018 /// \brief Check if this slice can be merged with an expensive cross register
9019 /// bank copy. E.g.,
9020 /// i = load i32
9021 /// f = bitcast i32 i to float
9022 bool canMergeExpensiveCrossRegisterBankCopy() const {
9023 if (!Inst || !Inst->hasOneUse())
9024 return false;
9025 SDNode *Use = *Inst->use_begin();
9026 if (Use->getOpcode() != ISD::BITCAST)
9027 return false;
9028 assert(DAG && "Missing context");
9029 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9030 EVT ResVT = Use->getValueType(0);
9031 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9032 const TargetRegisterClass *ArgRC =
9033 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9034 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9035 return false;
9036
9037 // At this point, we know that we perform a cross-register-bank copy.
9038 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00009039 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00009040 // Assume bitcasts are cheap, unless both register classes do not
9041 // explicitly share a common sub class.
9042 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9043 return false;
9044
9045 // Check if it will be merged with the load.
9046 // 1. Check the alignment constraint.
9047 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9048 ResVT.getTypeForEVT(*DAG->getContext()));
9049
9050 if (RequiredAlignment > getAlignment())
9051 return false;
9052
9053 // 2. Check that the load is a legal operation for that type.
9054 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9055 return false;
9056
9057 // 3. Check that we do not have a zext in the way.
9058 if (Inst->getValueType(0) != getLoadedType())
9059 return false;
9060
9061 return true;
9062 }
9063};
9064}
9065
Quentin Colombetde0e0622013-10-11 18:29:42 +00009066/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9067/// \p UsedBits looks like 0..0 1..1 0..0.
9068static bool areUsedBitsDense(const APInt &UsedBits) {
9069 // If all the bits are one, this is dense!
9070 if (UsedBits.isAllOnesValue())
9071 return true;
9072
9073 // Get rid of the unused bits on the right.
9074 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9075 // Get rid of the unused bits on the left.
9076 if (NarrowedUsedBits.countLeadingZeros())
9077 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9078 // Check that the chunk of bits is completely used.
9079 return NarrowedUsedBits.isAllOnesValue();
9080}
9081
9082/// \brief Check whether or not \p First and \p Second are next to each other
9083/// in memory. This means that there is no hole between the bits loaded
9084/// by \p First and the bits loaded by \p Second.
9085static bool areSlicesNextToEachOther(const LoadedSlice &First,
9086 const LoadedSlice &Second) {
9087 assert(First.Origin == Second.Origin && First.Origin &&
9088 "Unable to match different memory origins.");
9089 APInt UsedBits = First.getUsedBits();
9090 assert((UsedBits & Second.getUsedBits()) == 0 &&
9091 "Slices are not supposed to overlap.");
9092 UsedBits |= Second.getUsedBits();
9093 return areUsedBitsDense(UsedBits);
9094}
9095
9096/// \brief Adjust the \p GlobalLSCost according to the target
9097/// paring capabilities and the layout of the slices.
9098/// \pre \p GlobalLSCost should account for at least as many loads as
9099/// there is in the slices in \p LoadedSlices.
9100static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9101 LoadedSlice::Cost &GlobalLSCost) {
9102 unsigned NumberOfSlices = LoadedSlices.size();
9103 // If there is less than 2 elements, no pairing is possible.
9104 if (NumberOfSlices < 2)
9105 return;
9106
9107 // Sort the slices so that elements that are likely to be next to each
9108 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009109 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9110 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9111 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9112 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9113 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00009114 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9115 // First (resp. Second) is the first (resp. Second) potentially candidate
9116 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00009117 const LoadedSlice *First = nullptr;
9118 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009119 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9120 // Set the beginning of the pair.
9121 First = Second) {
9122
9123 Second = &LoadedSlices[CurrSlice];
9124
9125 // If First is NULL, it means we start a new pair.
9126 // Get to the next slice.
9127 if (!First)
9128 continue;
9129
9130 EVT LoadedType = First->getLoadedType();
9131
9132 // If the types of the slices are different, we cannot pair them.
9133 if (LoadedType != Second->getLoadedType())
9134 continue;
9135
9136 // Check if the target supplies paired loads for this type.
9137 unsigned RequiredAlignment = 0;
9138 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9139 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00009140 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009141 continue;
9142 }
9143 // Check if we meet the alignment requirement.
9144 if (RequiredAlignment > First->getAlignment())
9145 continue;
9146
9147 // Check that both loads are next to each other in memory.
9148 if (!areSlicesNextToEachOther(*First, *Second))
9149 continue;
9150
9151 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9152 --GlobalLSCost.Loads;
9153 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00009154 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009155 }
9156}
9157
9158/// \brief Check the profitability of all involved LoadedSlice.
9159/// Currently, it is considered profitable if there is exactly two
9160/// involved slices (1) which are (2) next to each other in memory, and
9161/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9162///
9163/// Note: The order of the elements in \p LoadedSlices may be modified, but not
9164/// the elements themselves.
9165///
9166/// FIXME: When the cost model will be mature enough, we can relax
9167/// constraints (1) and (2).
9168static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9169 const APInt &UsedBits, bool ForCodeSize) {
9170 unsigned NumberOfSlices = LoadedSlices.size();
9171 if (StressLoadSlicing)
9172 return NumberOfSlices > 1;
9173
9174 // Check (1).
9175 if (NumberOfSlices != 2)
9176 return false;
9177
9178 // Check (2).
9179 if (!areUsedBitsDense(UsedBits))
9180 return false;
9181
9182 // Check (3).
9183 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9184 // The original code has one big load.
9185 OrigCost.Loads = 1;
9186 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9187 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9188 // Accumulate the cost of all the slices.
9189 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9190 GlobalSlicingCost += SliceCost;
9191
9192 // Account as cost in the original configuration the gain obtained
9193 // with the current slices.
9194 OrigCost.addSliceGain(LS);
9195 }
9196
9197 // If the target supports paired load, adjust the cost accordingly.
9198 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9199 return OrigCost > GlobalSlicingCost;
9200}
9201
9202/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9203/// operations, split it in the various pieces being extracted.
9204///
9205/// This sort of thing is introduced by SROA.
9206/// This slicing takes care not to insert overlapping loads.
9207/// \pre LI is a simple load (i.e., not an atomic or volatile load).
9208bool DAGCombiner::SliceUpLoad(SDNode *N) {
9209 if (Level < AfterLegalizeDAG)
9210 return false;
9211
9212 LoadSDNode *LD = cast<LoadSDNode>(N);
9213 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9214 !LD->getValueType(0).isInteger())
9215 return false;
9216
9217 // Keep track of already used bits to detect overlapping values.
9218 // In that case, we will just abort the transformation.
9219 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9220
9221 SmallVector<LoadedSlice, 4> LoadedSlices;
9222
9223 // Check if this load is used as several smaller chunks of bits.
9224 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9225 // of computation for each trunc.
9226 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9227 UI != UIEnd; ++UI) {
9228 // Skip the uses of the chain.
9229 if (UI.getUse().getResNo() != 0)
9230 continue;
9231
9232 SDNode *User = *UI;
9233 unsigned Shift = 0;
9234
9235 // Check if this is a trunc(lshr).
9236 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9237 isa<ConstantSDNode>(User->getOperand(1))) {
9238 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9239 User = *User->use_begin();
9240 }
9241
9242 // At this point, User is a Truncate, iff we encountered, trunc or
9243 // trunc(lshr).
9244 if (User->getOpcode() != ISD::TRUNCATE)
9245 return false;
9246
9247 // The width of the type must be a power of 2 and greater than 8-bits.
9248 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00009249 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00009250 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009251 unsigned Width = User->getValueSizeInBits(0);
9252 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9253 return 0;
9254
9255 // Build the slice for this chain of computations.
9256 LoadedSlice LS(User, LD, Shift, &DAG);
9257 APInt CurrentUsedBits = LS.getUsedBits();
9258
9259 // Check if this slice overlaps with another.
9260 if ((CurrentUsedBits & UsedBits) != 0)
9261 return false;
9262 // Update the bits used globally.
9263 UsedBits |= CurrentUsedBits;
9264
9265 // Check if the new slice would be legal.
9266 if (!LS.isLegal())
9267 return false;
9268
9269 // Record the slice.
9270 LoadedSlices.push_back(LS);
9271 }
9272
9273 // Abort slicing if it does not seem to be profitable.
9274 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9275 return false;
9276
9277 ++SlicedLoads;
9278
9279 // Rewrite each chain to use an independent load.
9280 // By construction, each chain can be represented by a unique load.
9281
9282 // Prepare the argument for the new token factor for all the slices.
9283 SmallVector<SDValue, 8> ArgChains;
9284 for (SmallVectorImpl<LoadedSlice>::const_iterator
9285 LSIt = LoadedSlices.begin(),
9286 LSItEnd = LoadedSlices.end();
9287 LSIt != LSItEnd; ++LSIt) {
9288 SDValue SliceInst = LSIt->loadSlice();
9289 CombineTo(LSIt->Inst, SliceInst, true);
9290 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9291 SliceInst = SliceInst.getOperand(0);
9292 assert(SliceInst->getOpcode() == ISD::LOAD &&
9293 "It takes more than a zext to get to the loaded slice!!");
9294 ArgChains.push_back(SliceInst.getValue(1));
9295 }
9296
9297 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00009298 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00009299 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9300 return true;
9301}
9302
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009303/// Check to see if V is (and load (ptr), imm), where the load is having
9304/// specific bytes cleared out. If so, return the byte size being masked out
9305/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00009306static std::pair<unsigned, unsigned>
9307CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9308 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009309
Chris Lattner4041ab62010-04-15 04:48:01 +00009310 // Check for the structure we're looking for.
9311 if (V->getOpcode() != ISD::AND ||
9312 !isa<ConstantSDNode>(V->getOperand(1)) ||
9313 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9314 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009315
Chris Lattner3245afd2010-04-15 06:10:49 +00009316 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00009317 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00009318 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00009319
Chris Lattner3245afd2010-04-15 06:10:49 +00009320 // The store should be chained directly to the load or be an operand of a
9321 // tokenfactor.
9322 if (LD == Chain.getNode())
9323 ; // ok.
9324 else if (Chain->getOpcode() != ISD::TokenFactor)
9325 return Result; // Fail.
9326 else {
9327 bool isOk = false;
9328 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9329 if (Chain->getOperand(i).getNode() == LD) {
9330 isOk = true;
9331 break;
9332 }
9333 if (!isOk) return Result;
9334 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009335
Chris Lattner4041ab62010-04-15 04:48:01 +00009336 // This only handles simple types.
9337 if (V.getValueType() != MVT::i16 &&
9338 V.getValueType() != MVT::i32 &&
9339 V.getValueType() != MVT::i64)
9340 return Result;
9341
9342 // Check the constant mask. Invert it so that the bits being masked out are
9343 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9344 // follow the sign bit for uniformity.
9345 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009346 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009347 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009348 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009349 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9350 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00009351
Chris Lattner4041ab62010-04-15 04:48:01 +00009352 // See if we have a continuous run of bits. If so, we have 0*1+0*
9353 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9354 return Result;
9355
9356 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9357 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9358 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00009359
Chris Lattner4041ab62010-04-15 04:48:01 +00009360 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9361 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00009362 case 1:
9363 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00009364 case 4: break;
9365 default: return Result; // All one mask, or 5-byte mask.
9366 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009367
Chris Lattner4041ab62010-04-15 04:48:01 +00009368 // Verify that the first bit starts at a multiple of mask so that the access
9369 // is aligned the same as the access width.
9370 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009371
Chris Lattner4041ab62010-04-15 04:48:01 +00009372 Result.first = MaskedBytes;
9373 Result.second = NotMaskTZ/8;
9374 return Result;
9375}
9376
9377
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009378/// Check to see if IVal is something that provides a value as specified by
9379/// MaskInfo. If so, replace the specified store with a narrower store of
9380/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00009381static SDNode *
9382ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9383 SDValue IVal, StoreSDNode *St,
9384 DAGCombiner *DC) {
9385 unsigned NumBytes = MaskInfo.first;
9386 unsigned ByteShift = MaskInfo.second;
9387 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00009388
Chris Lattner4041ab62010-04-15 04:48:01 +00009389 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9390 // that uses this. If not, this is not a replacement.
9391 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9392 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00009393 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009394
Chris Lattner4041ab62010-04-15 04:48:01 +00009395 // Check that it is legal on the target to do this. It is legal if the new
9396 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9397 // legalization.
9398 MVT VT = MVT::getIntegerVT(NumBytes*8);
9399 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00009400 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009401
Chris Lattner4041ab62010-04-15 04:48:01 +00009402 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9403 // shifted by ByteShift and truncated down to NumBytes.
9404 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009405 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00009406 DAG.getConstant(ByteShift*8,
9407 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00009408
9409 // Figure out the offset for the store and the alignment of the access.
9410 unsigned StOffset;
9411 unsigned NewAlign = St->getAlignment();
9412
9413 if (DAG.getTargetLoweringInfo().isLittleEndian())
9414 StOffset = ByteShift;
9415 else
9416 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00009417
Chris Lattner4041ab62010-04-15 04:48:01 +00009418 SDValue Ptr = St->getBasePtr();
9419 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009420 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00009421 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9422 NewAlign = MinAlign(NewAlign, StOffset);
9423 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009424
Chris Lattner4041ab62010-04-15 04:48:01 +00009425 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009426 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00009427
Chris Lattner4041ab62010-04-15 04:48:01 +00009428 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009429 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00009430 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00009431 false, false, NewAlign).getNode();
9432}
9433
Evan Chenga9cda8a2009-05-28 00:35:15 +00009434
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009435/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9436/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9437/// narrowing the load and store if it would end up being a win for performance
9438/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009439SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9440 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00009441 if (ST->isVolatile())
9442 return SDValue();
9443
Evan Chenga9cda8a2009-05-28 00:35:15 +00009444 SDValue Chain = ST->getChain();
9445 SDValue Value = ST->getValue();
9446 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009447 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009448
9449 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00009450 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009451
9452 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00009453
Chris Lattner4041ab62010-04-15 04:48:01 +00009454 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9455 // is a byte mask indicating a consecutive number of bytes, check to see if
9456 // Y is known to provide just those bytes. If so, we try to replace the
9457 // load + replace + store sequence with a single (narrower) store, which makes
9458 // the load dead.
9459 if (Opc == ISD::OR) {
9460 std::pair<unsigned, unsigned> MaskedLoad;
9461 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9462 if (MaskedLoad.first)
9463 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9464 Value.getOperand(1), ST,this))
9465 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009466
Chris Lattner4041ab62010-04-15 04:48:01 +00009467 // Or is commutative, so try swapping X and Y.
9468 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9469 if (MaskedLoad.first)
9470 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9471 Value.getOperand(0), ST,this))
9472 return SDValue(NewST, 0);
9473 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009474
Evan Chenga9cda8a2009-05-28 00:35:15 +00009475 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9476 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00009477 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009478
9479 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00009480 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9481 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00009482 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009483 if (LD->getBasePtr() != Ptr ||
9484 LD->getPointerInfo().getAddrSpace() !=
9485 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00009486 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009487
9488 // Find the type to narrow it the load / op / store to.
9489 SDValue N1 = Value.getOperand(1);
9490 unsigned BitWidth = N1.getValueSizeInBits();
9491 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9492 if (Opc == ISD::AND)
9493 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00009494 if (Imm == 0 || Imm.isAllOnesValue())
9495 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009496 unsigned ShAmt = Imm.countTrailingZeros();
9497 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9498 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00009499 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009500 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00009501 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00009502 TLI.isNarrowingProfitable(VT, NewVT))) {
9503 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00009504 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009505 }
Evan Cheng6673ff02009-05-28 18:41:02 +00009506 if (NewBW >= BitWidth)
9507 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009508
9509 // If the lsb changed does not start at the type bitwidth boundary,
9510 // start at the previous one.
9511 if (ShAmt % NewBW)
9512 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00009513 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9514 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009515 if ((Imm & Mask) == Imm) {
9516 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9517 if (Opc == ISD::AND)
9518 NewImm ^= APInt::getAllOnesValue(NewBW);
9519 uint64_t PtrOff = ShAmt / 8;
9520 // For big endian targets, we need to adjust the offset to the pointer to
9521 // load the correct bytes.
9522 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00009523 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00009524
9525 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00009526 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009527 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00009528 return SDValue();
9529
Andrew Trickef9de2a2013-05-25 02:42:55 +00009530 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009531 Ptr.getValueType(), Ptr,
9532 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009533 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009534 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009535 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009536 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009537 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009538 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009539 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00009540 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009541 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009542 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009543 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009544 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009545
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009546 AddToWorklist(NewPtr.getNode());
9547 AddToWorklist(NewLD.getNode());
9548 AddToWorklist(NewVal.getNode());
9549 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009550 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009551 ++OpsNarrowed;
9552 return NewST;
9553 }
9554 }
9555
Evan Cheng6673ff02009-05-28 18:41:02 +00009556 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009557}
9558
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009559/// For a given floating point load / store pair, if the load value isn't used
9560/// by any other operations, then consider transforming the pair to integer
9561/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00009562SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9563 StoreSDNode *ST = cast<StoreSDNode>(N);
9564 SDValue Chain = ST->getChain();
9565 SDValue Value = ST->getValue();
9566 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9567 Value.hasOneUse() &&
9568 Chain == SDValue(Value.getNode(), 1)) {
9569 LoadSDNode *LD = cast<LoadSDNode>(Value);
9570 EVT VT = LD->getMemoryVT();
9571 if (!VT.isFloatingPoint() ||
9572 VT != ST->getMemoryVT() ||
9573 LD->isNonTemporal() ||
9574 ST->isNonTemporal() ||
9575 LD->getPointerInfo().getAddrSpace() != 0 ||
9576 ST->getPointerInfo().getAddrSpace() != 0)
9577 return SDValue();
9578
9579 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9580 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9581 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9582 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9583 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9584 return SDValue();
9585
9586 unsigned LDAlign = LD->getAlignment();
9587 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009588 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009589 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009590 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9591 return SDValue();
9592
Andrew Trickef9de2a2013-05-25 02:42:55 +00009593 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009594 LD->getChain(), LD->getBasePtr(),
9595 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009596 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009597
Andrew Trickef9de2a2013-05-25 02:42:55 +00009598 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009599 NewLD, ST->getBasePtr(),
9600 ST->getPointerInfo(),
9601 false, false, STAlign);
9602
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009603 AddToWorklist(NewLD.getNode());
9604 AddToWorklist(NewST.getNode());
9605 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009606 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009607 ++LdStFP2Int;
9608 return NewST;
9609 }
9610
9611 return SDValue();
9612}
9613
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009614/// Helper struct to parse and store a memory address as base + index + offset.
9615/// We ignore sign extensions when it is safe to do so.
9616/// The following two expressions are not equivalent. To differentiate we need
9617/// to store whether there was a sign extension involved in the index
9618/// computation.
9619/// (load (i64 add (i64 copyfromreg %c)
9620/// (i64 signextend (add (i8 load %index)
9621/// (i8 1))))
9622/// vs
9623///
9624/// (load (i64 add (i64 copyfromreg %c)
9625/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9626/// (i32 1)))))
9627struct BaseIndexOffset {
9628 SDValue Base;
9629 SDValue Index;
9630 int64_t Offset;
9631 bool IsIndexSignExt;
9632
9633 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9634
9635 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9636 bool IsIndexSignExt) :
9637 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9638
9639 bool equalBaseIndex(const BaseIndexOffset &Other) {
9640 return Other.Base == Base && Other.Index == Index &&
9641 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009642 }
9643
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009644 /// Parses tree in Ptr for base, index, offset addresses.
9645 static BaseIndexOffset match(SDValue Ptr) {
9646 bool IsIndexSignExt = false;
9647
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009648 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9649 // instruction, then it could be just the BASE or everything else we don't
9650 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009651 if (Ptr->getOpcode() != ISD::ADD)
9652 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9653
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009654 // We know that we have at least an ADD instruction. Try to pattern match
9655 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009656 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9657 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9658 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9659 IsIndexSignExt);
9660 }
9661
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009662 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009663 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009664 // (i64 add (i64 %array_ptr)
9665 // (i64 mul (i64 %induction_var)
9666 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009667 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009668 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009669
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009670 // Look at Base + Index + Offset cases.
9671 SDValue Base = Ptr->getOperand(0);
9672 SDValue IndexOffset = Ptr->getOperand(1);
9673
9674 // Skip signextends.
9675 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9676 IndexOffset = IndexOffset->getOperand(0);
9677 IsIndexSignExt = true;
9678 }
9679
9680 // Either the case of Base + Index (no offset) or something else.
9681 if (IndexOffset->getOpcode() != ISD::ADD)
9682 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9683
9684 // Now we have the case of Base + Index + offset.
9685 SDValue Index = IndexOffset->getOperand(0);
9686 SDValue Offset = IndexOffset->getOperand(1);
9687
9688 if (!isa<ConstantSDNode>(Offset))
9689 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9690
9691 // Ignore signextends.
9692 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9693 Index = Index->getOperand(0);
9694 IsIndexSignExt = true;
9695 } else IsIndexSignExt = false;
9696
9697 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9698 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9699 }
9700};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009701
9702/// Holds a pointer to an LSBaseSDNode as well as information on where it
9703/// is located in a sequence of memory operations connected by a chain.
9704struct MemOpLink {
9705 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9706 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9707 // Ptr to the mem node.
9708 LSBaseSDNode *MemNode;
9709 // Offset from the base ptr.
9710 int64_t OffsetFromBase;
9711 // What is the sequence number of this mem node.
9712 // Lowest mem operand in the DAG starts at zero.
9713 unsigned SequenceNum;
9714};
9715
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009716bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9717 EVT MemVT = St->getMemoryVT();
9718 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009719 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9720 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009721
9722 // Don't merge vectors into wider inputs.
9723 if (MemVT.isVector() || !MemVT.isSimple())
9724 return false;
9725
9726 // Perform an early exit check. Do not bother looking at stored values that
Alexey Samsonov553185e2014-12-31 00:40:28 +00009727 // are not constants or loads.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009728 SDValue StoredVal = St->getValue();
9729 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
Alexey Samsonov553185e2014-12-31 00:40:28 +00009730 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9731 !IsLoadSrc)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009732 return false;
9733
9734 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +00009735 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009736 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9737 return false;
9738
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009739 // This holds the base pointer, index, and the offset in bytes from the base
9740 // pointer.
9741 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009742
9743 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009744 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009745 return false;
9746
9747 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009748 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009749 return false;
9750
Nadav Rotem307d7672012-11-29 00:00:08 +00009751 // Save the LoadSDNodes that we find in the chain.
9752 // We need to make sure that these nodes do not interfere with
9753 // any of the store nodes.
9754 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9755
9756 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009757 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009758
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009759 // Walk up the chain and look for nodes with offsets from the same
9760 // base pointer. Stop when reaching an instruction with a different kind
9761 // or instruction which has a different base pointer.
9762 unsigned Seq = 0;
9763 StoreSDNode *Index = St;
9764 while (Index) {
9765 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +00009766 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009767 break;
9768
9769 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009770 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009771
9772 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009773 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009774 break;
9775
9776 // Check that the alignment is the same.
9777 if (Index->getAlignment() != St->getAlignment())
9778 break;
9779
9780 // The memory operands must not be volatile.
9781 if (Index->isVolatile() || Index->isIndexed())
9782 break;
9783
9784 // No truncation.
9785 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9786 if (St->isTruncatingStore())
9787 break;
9788
9789 // The stored memory type must be the same.
9790 if (Index->getMemoryVT() != MemVT)
9791 break;
9792
9793 // We do not allow unaligned stores because we want to prevent overriding
9794 // stores.
9795 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9796 break;
9797
9798 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009799 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009800
Nadav Rotem307d7672012-11-29 00:00:08 +00009801 // Find the next memory operand in the chain. If the next operand in the
9802 // chain is a store then move up and continue the scan with the next
9803 // memory operand. If the next operand is a load save it and use alias
9804 // information to check if it interferes with anything.
9805 SDNode *NextInChain = Index->getChain().getNode();
9806 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009807 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009808 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009809 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009810 break;
9811 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009812 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009813 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009814 break;
9815 }
9816
Nadav Rotem307d7672012-11-29 00:00:08 +00009817 // Save the load node for later. Continue the scan.
9818 AliasLoadNodes.push_back(Ldn);
9819 NextInChain = Ldn->getChain().getNode();
9820 continue;
9821 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009822 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009823 break;
9824 }
9825 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009826 }
9827
9828 // Check if there is anything to merge.
9829 if (StoreNodes.size() < 2)
9830 return false;
9831
9832 // Sort the memory operands according to their distance from the base pointer.
9833 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009834 [](MemOpLink LHS, MemOpLink RHS) {
9835 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9836 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9837 LHS.SequenceNum > RHS.SequenceNum);
9838 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009839
9840 // Scan the memory operations on the chain and find the first non-consecutive
9841 // store memory address.
9842 unsigned LastConsecutiveStore = 0;
9843 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009844 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9845
9846 // Check that the addresses are consecutive starting from the second
9847 // element in the list of stores.
9848 if (i > 0) {
9849 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9850 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9851 break;
9852 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009853
Nadav Rotem307d7672012-11-29 00:00:08 +00009854 bool Alias = false;
9855 // Check if this store interferes with any of the loads that we found.
9856 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9857 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9858 Alias = true;
9859 break;
9860 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009861 // We found a load that alias with this store. Stop the sequence.
9862 if (Alias)
9863 break;
9864
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009865 // Mark this node as useful.
9866 LastConsecutiveStore = i;
9867 }
9868
9869 // The node with the lowest store address.
9870 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9871
9872 // Store the constants into memory as one consecutive store.
Alexey Samsonov553185e2014-12-31 00:40:28 +00009873 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009874 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009875 unsigned LastLegalVectorType = 0;
9876 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009877 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9878 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9879 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009880
9881 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009882 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009883 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009884 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009885 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009886 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009887 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009888 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009889
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009890 // Find a legal type for the constant store.
9891 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9892 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9893 if (TLI.isTypeLegal(StoreTy))
9894 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009895 // Or check whether a truncstore is legal.
9896 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9897 TargetLowering::TypePromoteInteger) {
9898 EVT LegalizedStoredValueTy =
9899 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9900 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9901 LastLegalType = i+1;
9902 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009903
9904 // Find a legal type for the vector store.
9905 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9906 if (TLI.isTypeLegal(Ty))
9907 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009908 }
9909
Bob Wilson3365b802012-12-20 01:36:20 +00009910 // We only use vectors if the constant is known to be zero and the
9911 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009912 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009913 LastLegalVectorType = 0;
9914
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009915 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009916 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009917 return false;
9918
Nadav Rotem495b1a42013-02-14 18:28:52 +00009919 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009920 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9921
9922 // Make sure we have something to merge.
9923 if (NumElem < 2)
9924 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009925
9926 unsigned EarliestNodeUsed = 0;
9927 for (unsigned i=0; i < NumElem; ++i) {
9928 // Find a chain for the new wide-store operand. Notice that some
9929 // of the store nodes that we found may not be selected for inclusion
9930 // in the wide store. The chain we use needs to be the chain of the
9931 // earliest store node which is *used* and replaced by the wide store.
9932 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9933 EarliestNodeUsed = i;
9934 }
9935
9936 // The earliest Node in the DAG.
9937 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009938 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009939
Nadav Rotemb27777f2012-10-04 22:35:15 +00009940 SDValue StoredVal;
9941 if (UseVector) {
9942 // Find a legal type for the vector store.
9943 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9944 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9945 StoredVal = DAG.getConstant(0, Ty);
9946 } else {
9947 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9948 APInt StoreInt(StoreBW, 0);
9949
9950 // Construct a single integer constant which is made of the smaller
9951 // constant inputs.
9952 bool IsLE = TLI.isLittleEndian();
9953 for (unsigned i = 0; i < NumElem ; ++i) {
9954 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9955 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9956 SDValue Val = St->getValue();
9957 StoreInt<<=ElementSizeBytes*8;
9958 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9959 StoreInt|=C->getAPIntValue().zext(StoreBW);
9960 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9961 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9962 } else {
Craig Topperd3c02f12015-01-05 10:15:49 +00009963 llvm_unreachable("Invalid constant element type");
Nadav Rotemb27777f2012-10-04 22:35:15 +00009964 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009965 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009966
9967 // Create the new Load and Store operations.
9968 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9969 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009970 }
9971
Nadav Rotemb27777f2012-10-04 22:35:15 +00009972 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009973 FirstInChain->getBasePtr(),
9974 FirstInChain->getPointerInfo(),
9975 false, false,
9976 FirstInChain->getAlignment());
9977
9978 // Replace the first store with the new store
9979 CombineTo(EarliestOp, NewStore);
9980 // Erase all other stores.
9981 for (unsigned i = 0; i < NumElem ; ++i) {
9982 if (StoreNodes[i].MemNode == EarliestOp)
9983 continue;
9984 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009985 // ReplaceAllUsesWith will replace all uses that existed when it was
9986 // called, but graph optimizations may cause new ones to appear. For
9987 // example, the case in pr14333 looks like
9988 //
9989 // St's chain -> St -> another store -> X
9990 //
9991 // And the only difference from St to the other store is the chain.
9992 // When we change it's chain to be St's chain they become identical,
9993 // get CSEed and the net result is that X is now a use of St.
9994 // Since we know that St is redundant, just iterate.
9995 while (!St->use_empty())
9996 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009997 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009998 }
9999
10000 return true;
10001 }
10002
10003 // Below we handle the case of multiple consecutive stores that
10004 // come from multiple consecutive loads. We merge them into a single
10005 // wide load and a single wide store.
10006
10007 // Look for load nodes which are used by the stored values.
10008 SmallVector<MemOpLink, 8> LoadNodes;
10009
10010 // Find acceptable loads. Loads need to have the same chain (token factor),
10011 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010012 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010013 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10014 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10015 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10016 if (!Ld) break;
10017
10018 // Loads must only have one use.
10019 if (!Ld->hasNUsesOfValue(1, 0))
10020 break;
10021
10022 // Check that the alignment is the same as the stores.
10023 if (Ld->getAlignment() != St->getAlignment())
10024 break;
10025
10026 // The memory operands must not be volatile.
10027 if (Ld->isVolatile() || Ld->isIndexed())
10028 break;
10029
10030 // We do not accept ext loads.
10031 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10032 break;
10033
10034 // The stored memory type must be the same.
10035 if (Ld->getMemoryVT() != MemVT)
10036 break;
10037
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010038 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010039 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010040 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010041 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010042 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010043 break;
10044 } else {
10045 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010046 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010047 }
10048
10049 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010050 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010051 }
10052
10053 if (LoadNodes.size() < 2)
10054 return false;
10055
James Molloyce45be02014-08-02 14:51:24 +000010056 // If we have load/store pair instructions and we only have two values,
10057 // don't bother.
10058 unsigned RequiredAlignment;
10059 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10060 St->getAlignment() >= RequiredAlignment)
10061 return false;
10062
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010063 // Scan the memory operations on the chain and find the first non-consecutive
10064 // load memory address. These variables hold the index in the store node
10065 // array.
10066 unsigned LastConsecutiveLoad = 0;
10067 // This variable refers to the size and not index in the array.
10068 unsigned LastLegalVectorType = 0;
10069 unsigned LastLegalIntegerType = 0;
10070 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +000010071 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10072 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10073 // All loads much share the same chain.
10074 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10075 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +000010076
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010077 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10078 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10079 break;
10080 LastConsecutiveLoad = i;
10081
10082 // Find a legal type for the vector store.
10083 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10084 if (TLI.isTypeLegal(StoreTy))
10085 LastLegalVectorType = i + 1;
10086
10087 // Find a legal type for the integer store.
10088 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10089 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10090 if (TLI.isTypeLegal(StoreTy))
10091 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010092 // Or check whether a truncstore and extload is legal.
10093 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10094 TargetLowering::TypePromoteInteger) {
10095 EVT LegalizedStoredValueTy =
10096 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10097 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010098 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10099 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10100 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010101 LastLegalIntegerType = i+1;
10102 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010103 }
10104
10105 // Only use vector types if the vector type is larger than the integer type.
10106 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010107 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010108 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10109
10110 // We add +1 here because the LastXXX variables refer to location while
10111 // the NumElem refers to array/index size.
10112 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10113 NumElem = std::min(LastLegalType, NumElem);
10114
10115 if (NumElem < 2)
10116 return false;
10117
10118 // The earliest Node in the DAG.
10119 unsigned EarliestNodeUsed = 0;
10120 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10121 for (unsigned i=1; i<NumElem; ++i) {
10122 // Find a chain for the new wide-store operand. Notice that some
10123 // of the store nodes that we found may not be selected for inclusion
10124 // in the wide store. The chain we use needs to be the chain of the
10125 // earliest store node which is *used* and replaced by the wide store.
10126 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10127 EarliestNodeUsed = i;
10128 }
10129
10130 // Find if it is better to use vectors or integers to load and store
10131 // to memory.
10132 EVT JointMemOpVT;
10133 if (UseVectorTy) {
10134 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10135 } else {
10136 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10137 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10138 }
10139
Andrew Trickef9de2a2013-05-25 02:42:55 +000010140 SDLoc LoadDL(LoadNodes[0].MemNode);
10141 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010142
10143 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10144 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10145 FirstLoad->getChain(),
10146 FirstLoad->getBasePtr(),
10147 FirstLoad->getPointerInfo(),
10148 false, false, false,
10149 FirstLoad->getAlignment());
10150
10151 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10152 FirstInChain->getBasePtr(),
10153 FirstInChain->getPointerInfo(), false, false,
10154 FirstInChain->getAlignment());
10155
Nadav Rotemac920662012-10-03 19:30:31 +000010156 // Replace one of the loads with the new load.
10157 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10158 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10159 SDValue(NewLoad.getNode(), 1));
10160
10161 // Remove the rest of the load chains.
10162 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010163 // Replace all chain users of the old load nodes with the chain of the new
10164 // load node.
10165 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +000010166 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10167 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010168
Nadav Rotemac920662012-10-03 19:30:31 +000010169 // Replace the first store with the new store.
10170 CombineTo(EarliestOp, NewStore);
10171 // Erase all other stores.
10172 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010173 // Remove all Store nodes.
10174 if (StoreNodes[i].MemNode == EarliestOp)
10175 continue;
10176 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10177 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +000010178 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010179 }
10180
10181 return true;
10182}
10183
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010184SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +000010185 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010186 SDValue Chain = ST->getChain();
10187 SDValue Value = ST->getValue();
10188 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010189
Evan Chenga4cf58a2007-05-07 21:27:48 +000010190 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +000010191 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +000010192 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010193 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +000010194 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010195 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010196 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +000010197 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +000010198 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010199 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +000010200 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010201 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +000010202 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010203 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010204 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +000010205 }
Owen Andersona5192842011-04-14 17:30:49 +000010206
Chris Lattner41c80e82011-04-09 02:32:02 +000010207 // Turn 'store undef, Ptr' -> nothing.
10208 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10209 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +000010210
Nate Begeman8e20c762006-12-11 02:23:46 +000010211 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +000010212 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +000010213 // NOTE: If the original store is volatile, this transform must not increase
10214 // the number of stores. For example, on x86-32 an f64 can be stored in one
10215 // processor operation but an i64 (which is not legal) requires two. So the
10216 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +000010217 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010218 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +000010219 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +000010220 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +000010221 case MVT::f16: // We don't do this for these yet.
10222 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +000010223 case MVT::f128:
10224 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +000010225 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010226 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +000010227 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010228 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +000010229 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +000010230 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010231 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010232 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000010233 }
10234 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010235 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000010236 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000010237 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010238 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +000010239 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +000010240 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010241 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010242 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000010243 }
Owen Andersona5192842011-04-14 17:30:49 +000010244
Chris Lattner41c80e82011-04-09 02:32:02 +000010245 if (!ST->isVolatile() &&
10246 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000010247 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000010248 // argument passing. Since this is so common, custom legalize the
10249 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000010250 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +000010251 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10252 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000010253 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010254
Dan Gohman2af30632007-07-09 22:18:38 +000010255 unsigned Alignment = ST->getAlignment();
10256 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000010257 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000010258 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000010259
Andrew Trickef9de2a2013-05-25 02:42:55 +000010260 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000010261 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000010262 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010263 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010264 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +000010265 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000010266 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010267 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000010268 Ptr, ST->getPointerInfo().getWithOffset(4),
10269 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010270 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010271 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000010272 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010273 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010274
Chris Lattnerb7524b62006-12-12 04:16:14 +000010275 break;
Evan Cheng21836982006-12-11 17:25:19 +000010276 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010277 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010278 }
10279
Evan Cheng43cd9e32010-04-01 06:04:33 +000010280 // Try to infer better alignment information than the store already has.
10281 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000010282 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10283 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010284 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000010285 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010286 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000010287 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +000010288 }
10289 }
10290
Evan Chengd42641c2011-02-02 01:06:55 +000010291 // Try transforming a pair floating point load / store ops to integer
10292 // load / store ops.
10293 SDValue NewST = TransformFPLoadStorePair(N);
10294 if (NewST.getNode())
10295 return NewST;
10296
Eric Christopherf55d4712014-10-08 23:38:39 +000010297 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10298 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000010299#ifndef NDEBUG
10300 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10301 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10302 UseAA = false;
10303#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000010304 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000010305 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010306 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010307
Jim Laskey708d0db2006-10-04 16:53:27 +000010308 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000010309 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010310 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000010311
10312 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010313 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010314 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010315 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010316 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010317 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010318 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010319 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010320
Jim Laskeyd07be232006-09-25 16:29:54 +000010321 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010322 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000010323 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010324
Nate Begeman879d8f12009-09-15 00:18:30 +000010325 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010326 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000010327
Jim Laskeydcf983c2006-10-13 23:32:28 +000010328 // Don't add users to work list.
10329 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000010330 }
Jim Laskey5d19d592006-09-21 16:28:59 +000010331 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010332
Evan Cheng33157702006-11-05 09:31:14 +000010333 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000010334 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010335 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000010336
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010337 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010338 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010339 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000010340 // See if we can simplify the input to this truncstore with knowledge that
10341 // only the low bits are being used. For example:
10342 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000010343 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000010344 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010345 APInt::getLowBitsSet(
10346 Value.getValueType().getScalarType().getSizeInBits(),
10347 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010348 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000010349 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010350 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010351 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000010352
Chris Lattnerf47e3062007-10-13 06:58:48 +000010353 // Otherwise, see if we can simplify the operation with
10354 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000010355 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000010356 APInt::getLowBitsSet(
10357 Value.getValueType().getScalarType().getSizeInBits(),
10358 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010359 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000010360 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010361
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010362 // If this is a load followed by a store to the same location, then the store
10363 // is dead/noop.
10364 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010365 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010366 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000010367 // There can't be any side effects between the load and store, such as
10368 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010369 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010370 // The store is dead, remove it.
10371 return Chain;
10372 }
10373 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010374
James Molloy463db9a2014-09-27 17:02:54 +000010375 // If this is a store followed by a store with the same value to the same
10376 // location, then the store is dead/noop.
10377 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10378 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10379 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10380 ST1->isUnindexed() && !ST1->isVolatile()) {
10381 // The store is dead, remove it.
10382 return Chain;
10383 }
10384 }
10385
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010386 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10387 // truncating store. We can do this even if this is already a truncstore.
10388 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010389 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010390 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010391 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010392 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010393 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010394 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010395
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010396 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000010397 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000010398 if (!LegalTypes) {
10399 bool EverChanged = false;
10400
10401 do {
10402 // There can be multiple store sequences on the same chain.
10403 // Keep trying to merge store sequences until we are unable to do so
10404 // or until we merge the last store on the chain.
10405 bool Changed = MergeConsecutiveStores(ST);
10406 EverChanged |= Changed;
10407 if (!Changed) break;
10408 } while (ST->getOpcode() != ISD::DELETED_NODE);
10409
10410 if (EverChanged)
10411 return SDValue(N, 0);
10412 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010413
Evan Chenga9cda8a2009-05-28 00:35:15 +000010414 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000010415}
10416
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010417SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10418 SDValue InVec = N->getOperand(0);
10419 SDValue InVal = N->getOperand(1);
10420 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010421 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010422
Bob Wilson42603952010-05-19 23:42:58 +000010423 // If the inserted element is an UNDEF, just use the input vector.
10424 if (InVal.getOpcode() == ISD::UNDEF)
10425 return InVec;
10426
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010427 EVT VT = InVec.getValueType();
10428
Owen Andersonb2c80da2011-02-25 21:41:48 +000010429 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010430 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10431 return SDValue();
10432
Eli Friedmanb7910b72011-09-09 21:04:06 +000010433 // Check that we know which element is being inserted
10434 if (!isa<ConstantSDNode>(EltNo))
10435 return SDValue();
10436 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010437
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010438 // Canonicalize insert_vector_elt dag nodes.
10439 // Example:
10440 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10441 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10442 //
10443 // Do this only if the child insert_vector node has one use; also
10444 // do this only if indices are both constants and Idx1 < Idx0.
10445 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10446 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10447 unsigned OtherElt =
10448 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10449 if (Elt < OtherElt) {
10450 // Swap nodes.
10451 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10452 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010453 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010454 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10455 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10456 }
10457 }
10458
Eli Friedmanb7910b72011-09-09 21:04:06 +000010459 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10460 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10461 // vector elements.
10462 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000010463 // Do not combine these two vectors if the output vector will not replace
10464 // the input vector.
10465 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000010466 Ops.append(InVec.getNode()->op_begin(),
10467 InVec.getNode()->op_end());
10468 } else if (InVec.getOpcode() == ISD::UNDEF) {
10469 unsigned NElts = VT.getVectorNumElements();
10470 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10471 } else {
10472 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010473 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000010474
10475 // Insert the element
10476 if (Elt < Ops.size()) {
10477 // All the operands of BUILD_VECTOR must have the same type;
10478 // we enforce that here.
10479 EVT OpVT = Ops[0].getValueType();
10480 if (InVal.getValueType() != OpVT)
10481 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10482 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10483 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10484 Ops[Elt] = InVal;
10485 }
10486
10487 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000010488 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000010489}
10490
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010491SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10492 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10493 EVT ResultVT = EVE->getValueType(0);
10494 EVT VecEltVT = InVecVT.getVectorElementType();
10495 unsigned Align = OriginalLoad->getAlignment();
10496 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10497 VecEltVT.getTypeForEVT(*DAG.getContext()));
10498
10499 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10500 return SDValue();
10501
10502 Align = NewAlign;
10503
10504 SDValue NewPtr = OriginalLoad->getBasePtr();
10505 SDValue Offset;
10506 EVT PtrType = NewPtr.getValueType();
10507 MachinePointerInfo MPI;
10508 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10509 int Elt = ConstEltNo->getZExtValue();
10510 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10511 if (TLI.isBigEndian())
10512 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10513 Offset = DAG.getConstant(PtrOff, PtrType);
10514 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10515 } else {
10516 Offset = DAG.getNode(
10517 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10518 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10519 if (TLI.isBigEndian())
10520 Offset = DAG.getNode(
10521 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10522 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10523 MPI = OriginalLoad->getPointerInfo();
10524 }
10525 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10526
10527 // The replacement we need to do here is a little tricky: we need to
10528 // replace an extractelement of a load with a load.
10529 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10530 // Note that this replacement assumes that the extractvalue is the only
10531 // use of the load; that's okay because we don't want to perform this
10532 // transformation in other cases anyway.
10533 SDValue Load;
10534 SDValue Chain;
10535 if (ResultVT.bitsGT(VecEltVT)) {
10536 // If the result type of vextract is wider than the load, then issue an
10537 // extending load instead.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010538 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10539 VecEltVT)
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010540 ? ISD::ZEXTLOAD
10541 : ISD::EXTLOAD;
10542 Load = DAG.getExtLoad(
10543 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10544 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10545 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10546 Chain = Load.getValue(1);
10547 } else {
10548 Load = DAG.getLoad(
10549 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10550 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10551 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10552 Chain = Load.getValue(1);
10553 if (ResultVT.bitsLT(VecEltVT))
10554 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10555 else
10556 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10557 }
10558 WorklistRemover DeadNodes(*this);
10559 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10560 SDValue To[] = { Load, Chain };
10561 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10562 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10563 // worklist explicitly as well.
10564 AddToWorklist(Load.getNode());
10565 AddUsersToWorklist(Load.getNode()); // Add users too
10566 // Make sure to revisit this node to clean it up; it will usually be dead.
10567 AddToWorklist(EVE);
10568 ++OpsNarrowed;
10569 return SDValue(EVE, 0);
10570}
10571
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010572SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000010573 // (vextract (scalar_to_vector val, 0) -> val
10574 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010575 EVT VT = InVec.getValueType();
10576 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010577
Duncan Sands6be291a2011-05-09 08:03:33 +000010578 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10579 // Check if the result type doesn't match the inserted element type. A
10580 // SCALAR_TO_VECTOR may truncate the inserted element and the
10581 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10582 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010583 if (InOp.getValueType() != NVT) {
10584 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010585 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010586 }
10587 return InOp;
10588 }
Evan Cheng1120279a2008-05-13 08:35:03 +000010589
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010590 SDValue EltNo = N->getOperand(1);
10591 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10592
10593 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10594 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000010595 // we may introduce new vector instructions which are not backed by TD
10596 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000010597 // without using extract_subvector. However, if we can find an underlying
10598 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010599 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000010600 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010601 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10602 int NumElem = VT.getVectorNumElements();
10603 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10604 // Find the new index to extract from.
10605 int OrigElt = SVOp->getMaskElt(Elt);
10606
10607 // Extracting an undef index is undef.
10608 if (OrigElt == -1)
10609 return DAG.getUNDEF(NVT);
10610
10611 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000010612 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010613 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000010614 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010615 } else {
Hal Finkel02807592014-03-31 11:43:19 +000010616 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010617 OrigElt -= NumElem;
10618 }
10619
Hal Finkel02807592014-03-31 11:43:19 +000010620 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10621 SDValue InOp = SVInVec.getOperand(OrigElt);
10622 if (InOp.getValueType() != NVT) {
10623 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10624 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10625 }
10626
10627 return InOp;
10628 }
10629
10630 // FIXME: We should handle recursing on other vector shuffles and
10631 // scalar_to_vector here as well.
10632
10633 if (!LegalOperations) {
10634 EVT IndexTy = TLI.getVectorIdxTy();
10635 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10636 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10637 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010638 }
10639
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010640 bool BCNumEltsChanged = false;
10641 EVT ExtVT = VT.getVectorElementType();
10642 EVT LVT = ExtVT;
10643
10644 // If the result of load has to be truncated, then it's not necessarily
10645 // profitable.
10646 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10647 return SDValue();
10648
10649 if (InVec.getOpcode() == ISD::BITCAST) {
10650 // Don't duplicate a load with other uses.
10651 if (!InVec.hasOneUse())
10652 return SDValue();
10653
10654 EVT BCVT = InVec.getOperand(0).getValueType();
10655 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10656 return SDValue();
10657 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10658 BCNumEltsChanged = true;
10659 InVec = InVec.getOperand(0);
10660 ExtVT = BCVT.getVectorElementType();
10661 }
10662
10663 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10664 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10665 ISD::isNormalLoad(InVec.getNode()) &&
10666 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10667 SDValue Index = N->getOperand(1);
10668 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10669 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10670 OrigLoad);
10671 }
10672
Evan Cheng1120279a2008-05-13 08:35:03 +000010673 // Perform only after legalization to ensure build_vector / vector_shuffle
10674 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010675 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010676
Mon P Wangca6d6de2009-01-17 00:07:25 +000010677 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10678 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10679 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000010680
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010681 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000010682 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010683
Craig Topperc0196b12014-04-14 00:51:57 +000010684 LoadSDNode *LN0 = nullptr;
10685 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000010686 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010687 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010688 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000010689 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000010690 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000010691 // Don't duplicate a load with other uses.
10692 if (!InVec.hasOneUse())
10693 return SDValue();
10694
Evan Cheng1120279a2008-05-13 08:35:03 +000010695 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000010696 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010697 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10698 // =>
10699 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000010700
Eli Friedmane96286c2011-12-26 22:49:32 +000010701 // Don't duplicate a load with other uses.
10702 if (!InVec.hasOneUse())
10703 return SDValue();
10704
Mon P Wangb5eb7202008-12-11 00:26:16 +000010705 // If the bit convert changed the number of elements, it is unsafe
10706 // to examine the mask.
10707 if (BCNumEltsChanged)
10708 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010709
10710 // Select the input vector, guarding against out of range extract vector.
10711 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010712 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010713 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10714
Eli Friedmane96286c2011-12-26 22:49:32 +000010715 if (InVec.getOpcode() == ISD::BITCAST) {
10716 // Don't duplicate a load with other uses.
10717 if (!InVec.hasOneUse())
10718 return SDValue();
10719
Evan Cheng1120279a2008-05-13 08:35:03 +000010720 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010721 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010722 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010723 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010724 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010725 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010726 }
10727 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010728
Eli Friedmane96286c2011-12-26 22:49:32 +000010729 // Make sure we found a non-volatile load and the extractelement is
10730 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010731 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010732 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010733
Eric Christopherc6418b12010-11-03 20:44:42 +000010734 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10735 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010736 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010737
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010738 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010739 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010740
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010741 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010742}
Evan Cheng0de312d2007-10-06 08:19:55 +000010743
Michael Liao6d106b72012-10-23 23:06:52 +000010744// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10745SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10746 // We perform this optimization post type-legalization because
10747 // the type-legalizer often scalarizes integer-promoted vectors.
10748 // Performing this optimization before may create bit-casts which
10749 // will be type-legalized to complex code sequences.
10750 // We perform this optimization only before the operation legalizer because we
10751 // may introduce illegal operations.
10752 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10753 return SDValue();
10754
Dan Gohmana8665142007-06-25 16:23:39 +000010755 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010756 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010757 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010758
Nadav Rotembf6568b2011-10-29 21:23:04 +000010759 // Check to see if this is a BUILD_VECTOR of a bunch of values
10760 // which come from any_extend or zero_extend nodes. If so, we can create
10761 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010762 // optimizations. We do not handle sign-extend because we can't fill the sign
10763 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010764 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010765 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010766
Craig Topper02cb0fb2012-01-17 09:09:48 +000010767 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010768 SDValue In = N->getOperand(i);
10769 // Ignore undef inputs.
10770 if (In.getOpcode() == ISD::UNDEF) continue;
10771
10772 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10773 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10774
Nadav Rotemf3103612011-10-31 20:08:25 +000010775 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010776 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010777 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010778 break;
10779 }
10780
10781 // The input is a ZeroExt or AnyExt. Check the original type.
10782 EVT InTy = In.getOperand(0).getValueType();
10783
10784 // Check that all of the widened source types are the same.
10785 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010786 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010787 SourceType = InTy;
10788 else if (InTy != SourceType) {
10789 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010790 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010791 break;
10792 }
10793
10794 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010795 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010796 }
10797
Nadav Rotemf3103612011-10-31 20:08:25 +000010798 // In order to have valid types, all of the inputs must be extended from the
10799 // same source type and all of the inputs must be any or zero extend.
10800 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010801 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010802 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010803 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10804 isPowerOf2_32(SourceType.getSizeInBits());
10805
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010806 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10807 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010808 if (!ValidTypes)
10809 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010810
Michael Liao6d106b72012-10-23 23:06:52 +000010811 bool isLE = TLI.isLittleEndian();
10812 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10813 assert(ElemRatio > 1 && "Invalid element size ratio");
10814 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10815 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010816
Michael Liao6d106b72012-10-23 23:06:52 +000010817 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10818 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010819
Michael Liao6d106b72012-10-23 23:06:52 +000010820 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010821 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010822 SDValue Cast = N->getOperand(i);
10823 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10824 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10825 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10826 SDValue In;
10827 if (Cast.getOpcode() == ISD::UNDEF)
10828 In = DAG.getUNDEF(SourceType);
10829 else
10830 In = Cast->getOperand(0);
10831 unsigned Index = isLE ? (i * ElemRatio) :
10832 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010833
Michael Liao6d106b72012-10-23 23:06:52 +000010834 assert(Index < Ops.size() && "Invalid index");
10835 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010836 }
Chris Lattner5336a592006-03-19 01:27:56 +000010837
Michael Liao6d106b72012-10-23 23:06:52 +000010838 // The type of the new BUILD_VECTOR node.
10839 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10840 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10841 "Invalid vector size");
10842 // Check if the new vector type is legal.
10843 if (!isTypeLegal(VecVT)) return SDValue();
10844
10845 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010846 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010847
10848 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010849 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010850 // Bitcast to the desired type.
10851 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10852}
10853
Michael Liao59229792012-10-24 04:14:18 +000010854SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10855 EVT VT = N->getValueType(0);
10856
10857 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010858 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010859
10860 EVT SrcVT = MVT::Other;
10861 unsigned Opcode = ISD::DELETED_NODE;
10862 unsigned NumDefs = 0;
10863
10864 for (unsigned i = 0; i != NumInScalars; ++i) {
10865 SDValue In = N->getOperand(i);
10866 unsigned Opc = In.getOpcode();
10867
10868 if (Opc == ISD::UNDEF)
10869 continue;
10870
10871 // If all scalar values are floats and converted from integers.
10872 if (Opcode == ISD::DELETED_NODE &&
10873 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10874 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010875 }
Tom Stellard567f8862013-01-02 22:13:01 +000010876
Michael Liao59229792012-10-24 04:14:18 +000010877 if (Opc != Opcode)
10878 return SDValue();
10879
10880 EVT InVT = In.getOperand(0).getValueType();
10881
10882 // If all scalar values are typed differently, bail out. It's chosen to
10883 // simplify BUILD_VECTOR of integer types.
10884 if (SrcVT == MVT::Other)
10885 SrcVT = InVT;
10886 if (SrcVT != InVT)
10887 return SDValue();
10888 NumDefs++;
10889 }
10890
10891 // If the vector has just one element defined, it's not worth to fold it into
10892 // a vectorized one.
10893 if (NumDefs < 2)
10894 return SDValue();
10895
10896 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10897 && "Should only handle conversion from integer to float.");
10898 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10899
10900 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010901
10902 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10903 return SDValue();
10904
Michael Liao59229792012-10-24 04:14:18 +000010905 SmallVector<SDValue, 8> Opnds;
10906 for (unsigned i = 0; i != NumInScalars; ++i) {
10907 SDValue In = N->getOperand(i);
10908
10909 if (In.getOpcode() == ISD::UNDEF)
10910 Opnds.push_back(DAG.getUNDEF(SrcVT));
10911 else
10912 Opnds.push_back(In.getOperand(0));
10913 }
Craig Topper48d114b2014-04-26 18:35:24 +000010914 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010915 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010916
10917 return DAG.getNode(Opcode, dl, VT, BV);
10918}
10919
Michael Liao6d106b72012-10-23 23:06:52 +000010920SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10921 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010922 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010923 EVT VT = N->getValueType(0);
10924
10925 // A vector built entirely of undefs is undef.
10926 if (ISD::allOperandsUndef(N))
10927 return DAG.getUNDEF(VT);
10928
10929 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10930 if (V.getNode())
10931 return V;
10932
Michael Liao59229792012-10-24 04:14:18 +000010933 V = reduceBuildVecConvertToConvertBuildVec(N);
10934 if (V.getNode())
10935 return V;
10936
Dan Gohmana8665142007-06-25 16:23:39 +000010937 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10938 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10939 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010940
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000010941 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10942 if (!isTypeLegal(VT))
10943 return SDValue();
10944
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010945 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000010946 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010947 return SDValue();
10948
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010949 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010950 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000010951 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010952 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000010953 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010954 if (Op.getOpcode() == ISD::UNDEF) continue;
10955
10956 // See if we can combine this build_vector into a blend with a zero vector.
10957 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10958 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10959 (Op.getOpcode() == ISD::ConstantFP &&
10960 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10961 UsesZeroVector = true;
10962 continue;
10963 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010964
Dan Gohmana8665142007-06-25 16:23:39 +000010965 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010966 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010967 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10968 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010969 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010970 break;
10971 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010972
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010973 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010974 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010975 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10976 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010977
Craig Topperc0196b12014-04-14 00:51:57 +000010978 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010979 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010980 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010981 VecIn2 = ExtractedFromVec;
10982 } else {
10983 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010984 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010985 break;
10986 }
10987 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010988
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010989 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010990 if (VecIn1.getNode()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000010991 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010992 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010993 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010994 unsigned Opcode = N->getOperand(i).getOpcode();
10995 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010996 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010997 continue;
10998 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010999
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011000 // Operands can also be zero.
11001 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11002 assert(UsesZeroVector &&
11003 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11004 "Unexpected node found!");
11005 Mask.push_back(NumInScalars+i);
11006 continue;
11007 }
11008
Rafael Espindolab93db662009-04-24 12:40:33 +000011009 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011010 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000011011 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011012 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011013 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000011014 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011015 continue;
11016 }
11017
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011018 // Otherwise, use InIdx + InputVecSize
11019 Mask.push_back(InNumElements + ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011020 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011021
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011022 // Avoid introducing illegal shuffles with zero.
11023 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11024 return SDValue();
11025
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011026 // We can't generate a shuffle node with mismatched input and output types.
11027 // Attempt to transform a single input vector to the correct type.
11028 if ((VT != VecIn1.getValueType())) {
James Molloy1e5c6112012-09-10 14:01:21 +000011029 // If the input vector type has a different base type to the output
11030 // vector type, bail out.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011031 EVT VTElemType = VT.getVectorElementType();
11032 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11033 (VecIn2.getNode() &&
11034 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
James Molloy1e5c6112012-09-10 14:01:21 +000011035 return SDValue();
11036
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011037 // If the input vector is too small, widen it.
11038 // We only support widening of vectors which are half the size of the
11039 // output registers. For example XMM->YMM widening on X86 with AVX.
11040 EVT VecInT = VecIn1.getValueType();
11041 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011042 // If we only have one small input, widen it by adding undef values.
11043 if (!VecIn2.getNode())
11044 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11045 DAG.getUNDEF(VecIn1.getValueType()));
11046 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11047 // If we have two small inputs of the same type, try to concat them.
11048 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11049 VecIn2 = SDValue(nullptr, 0);
11050 } else
11051 return SDValue();
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011052 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11053 // If the input vector is too large, try to split it.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011054 // We don't support having two input vectors that are too large.
11055 if (VecIn2.getNode())
11056 return SDValue();
11057
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011058 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11059 return SDValue();
11060
11061 // Try to replace VecIn1 with two extract_subvectors
11062 // No need to update the masks, they should still be correct.
11063 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11064 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11065 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11066 DAG.getConstant(0, TLI.getVectorIdxTy()));
11067 UsesZeroVector = false;
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011068 } else
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011069 return SDValue();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011070 }
11071
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011072 if (UsesZeroVector)
11073 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11074 DAG.getConstantFP(0.0, VT);
11075 else
11076 // If VecIn2 is unused then change it to undef.
11077 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011078
Nadav Rotem841c9a82012-09-20 08:53:31 +000011079 // Check that we were able to transform all incoming values to the same
11080 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000011081 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11082 VecIn1.getValueType() != VT)
11083 return SDValue();
11084
Dan Gohmana8665142007-06-25 16:23:39 +000011085 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011086 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000011087 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011088 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000011089 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000011090 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011091
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011092 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011093}
11094
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011095SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000011096 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11097 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11098 // inputs come from at most two distinct vectors, turn this into a shuffle
11099 // node.
11100
11101 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000011102 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000011103 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011104
Nadav Rotem01892102012-07-14 21:30:27 +000011105 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011106 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011107 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011108 return DAG.getUNDEF(VT);
11109
11110 // Optimize concat_vectors where one of the vectors is undef.
11111 if (N->getNumOperands() == 2 &&
11112 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11113 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000011114 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011115
11116 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11117 if (In->getOpcode() == ISD::BITCAST &&
11118 !In->getOperand(0)->getValueType(0).isVector()) {
11119 SDValue Scalar = In->getOperand(0);
11120 EVT SclTy = Scalar->getValueType(0);
11121
11122 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11123 return SDValue();
11124
11125 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11126 VT.getSizeInBits() / SclTy.getSizeInBits());
11127 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11128 return SDValue();
11129
11130 SDLoc dl = SDLoc(N);
11131 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11132 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11133 }
11134 }
Nadav Rotem01892102012-07-14 21:30:27 +000011135
Robert Lougher7d9084f2014-02-11 15:42:46 +000011136 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11137 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11138 if (N->getNumOperands() == 2 &&
11139 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11140 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11141 EVT VT = N->getValueType(0);
11142 SDValue N0 = N->getOperand(0);
11143 SDValue N1 = N->getOperand(1);
11144 SmallVector<SDValue, 8> Opnds;
11145 unsigned BuildVecNumElts = N0.getNumOperands();
11146
Hao Liu71224b02014-07-10 03:41:50 +000011147 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11148 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11149 if (SclTy0.isFloatingPoint()) {
11150 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11151 Opnds.push_back(N0.getOperand(i));
11152 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11153 Opnds.push_back(N1.getOperand(i));
11154 } else {
11155 // If BUILD_VECTOR are from built from integer, they may have different
11156 // operand types. Get the smaller type and truncate all operands to it.
11157 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11158 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11159 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11160 N0.getOperand(i)));
11161 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11162 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11163 N1.getOperand(i)));
11164 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000011165
Craig Topper48d114b2014-04-26 18:35:24 +000011166 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000011167 }
11168
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011169 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11170 // nodes often generate nop CONCAT_VECTOR nodes.
11171 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11172 // place the incoming vectors at the exact same location.
11173 SDValue SingleSource = SDValue();
11174 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11175
11176 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11177 SDValue Op = N->getOperand(i);
11178
11179 if (Op.getOpcode() == ISD::UNDEF)
11180 continue;
11181
11182 // Check if this is the identity extract:
11183 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11184 return SDValue();
11185
11186 // Find the single incoming vector for the extract_subvector.
11187 if (SingleSource.getNode()) {
11188 if (Op.getOperand(0) != SingleSource)
11189 return SDValue();
11190 } else {
11191 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000011192
11193 // Check the source type is the same as the type of the result.
11194 // If not, this concat may extend the vector, so we can not
11195 // optimize it away.
11196 if (SingleSource.getValueType() != N->getValueType(0))
11197 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011198 }
11199
11200 unsigned IdentityIndex = i * PartNumElem;
11201 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11202 // The extract index must be constant.
11203 if (!CS)
11204 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000011205
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011206 // Check that we are reading from the identity index.
11207 if (CS->getZExtValue() != IdentityIndex)
11208 return SDValue();
11209 }
11210
11211 if (SingleSource.getNode())
11212 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000011213
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011214 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000011215}
11216
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011217SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11218 EVT NVT = N->getValueType(0);
11219 SDValue V = N->getOperand(0);
11220
Michael Liao7a442c802012-10-17 20:48:33 +000011221 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11222 // Combine:
11223 // (extract_subvec (concat V1, V2, ...), i)
11224 // Into:
11225 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000011226 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11227 // type.
Michael Liao2c235802012-10-19 03:17:00 +000011228 if (V->getOperand(0).getValueType() != NVT)
11229 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000011230 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11231 unsigned NumElems = NVT.getVectorNumElements();
11232 assert((Idx % NumElems) == 0 &&
11233 "IDX in concat is not a multiple of the result vector length.");
11234 return V->getOperand(Idx / NumElems);
11235 }
11236
Michael Liaobb05a1d2013-03-25 23:47:35 +000011237 // Skip bitcasting
11238 if (V->getOpcode() == ISD::BITCAST)
11239 V = V.getOperand(0);
11240
11241 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011242 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000011243 // Handle only simple case where vector being inserted and vector
11244 // being extracted are of same type, and are half size of larger vectors.
11245 EVT BigVT = V->getOperand(0).getValueType();
11246 EVT SmallVT = V->getOperand(1).getValueType();
11247 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11248 return SDValue();
11249
11250 // Only handle cases where both indexes are constants with the same type.
11251 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11252 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11253
11254 if (InsIdx && ExtIdx &&
11255 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11256 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11257 // Combine:
11258 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11259 // Into:
11260 // indices are equal or bit offsets are equal => V1
11261 // otherwise => (extract_subvec V1, ExtIdx)
11262 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11263 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11264 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11265 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11266 DAG.getNode(ISD::BITCAST, dl,
11267 N->getOperand(0).getValueType(),
11268 V->getOperand(0)), N->getOperand(1));
11269 }
11270 }
11271
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011272 return SDValue();
11273}
11274
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011275static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11276 SDValue V, SelectionDAG &DAG) {
11277 SDLoc DL(V);
11278 EVT VT = V.getValueType();
11279
11280 switch (V.getOpcode()) {
11281 default:
11282 return V;
11283
11284 case ISD::CONCAT_VECTORS: {
11285 EVT OpVT = V->getOperand(0).getValueType();
11286 int OpSize = OpVT.getVectorNumElements();
11287 SmallBitVector OpUsedElements(OpSize, false);
11288 bool FoundSimplification = false;
11289 SmallVector<SDValue, 4> NewOps;
11290 NewOps.reserve(V->getNumOperands());
11291 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11292 SDValue Op = V->getOperand(i);
11293 bool OpUsed = false;
11294 for (int j = 0; j < OpSize; ++j)
11295 if (UsedElements[i * OpSize + j]) {
11296 OpUsedElements[j] = true;
11297 OpUsed = true;
11298 }
11299 NewOps.push_back(
11300 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11301 : DAG.getUNDEF(OpVT));
11302 FoundSimplification |= Op == NewOps.back();
11303 OpUsedElements.reset();
11304 }
11305 if (FoundSimplification)
11306 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11307 return V;
11308 }
11309
11310 case ISD::INSERT_SUBVECTOR: {
11311 SDValue BaseV = V->getOperand(0);
11312 SDValue SubV = V->getOperand(1);
11313 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11314 if (!IdxN)
11315 return V;
11316
11317 int SubSize = SubV.getValueType().getVectorNumElements();
11318 int Idx = IdxN->getZExtValue();
11319 bool SubVectorUsed = false;
11320 SmallBitVector SubUsedElements(SubSize, false);
11321 for (int i = 0; i < SubSize; ++i)
11322 if (UsedElements[i + Idx]) {
11323 SubVectorUsed = true;
11324 SubUsedElements[i] = true;
11325 UsedElements[i + Idx] = false;
11326 }
11327
11328 // Now recurse on both the base and sub vectors.
11329 SDValue SimplifiedSubV =
11330 SubVectorUsed
11331 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11332 : DAG.getUNDEF(SubV.getValueType());
11333 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11334 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11335 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11336 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11337 return V;
11338 }
11339 }
11340}
11341
11342static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11343 SDValue N1, SelectionDAG &DAG) {
11344 EVT VT = SVN->getValueType(0);
11345 int NumElts = VT.getVectorNumElements();
11346 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11347 for (int M : SVN->getMask())
11348 if (M >= 0 && M < NumElts)
11349 N0UsedElements[M] = true;
11350 else if (M >= NumElts)
11351 N1UsedElements[M - NumElts] = true;
11352
11353 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11354 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11355 if (S0 == N0 && S1 == N1)
11356 return SDValue();
11357
11358 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11359}
11360
Mehdi Amini37f316a2015-01-17 01:35:56 +000011361// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11362// or turn a shuffle of a single concat into simpler shuffle then concat.
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011363static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11364 EVT VT = N->getValueType(0);
11365 unsigned NumElts = VT.getVectorNumElements();
11366
11367 SDValue N0 = N->getOperand(0);
11368 SDValue N1 = N->getOperand(1);
11369 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11370
11371 SmallVector<SDValue, 4> Ops;
11372 EVT ConcatVT = N0.getOperand(0).getValueType();
11373 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11374 unsigned NumConcats = NumElts / NumElemsPerConcat;
11375
Mehdi Amini37f316a2015-01-17 01:35:56 +000011376 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11377 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11378 // half vector elements.
11379 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11380 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11381 SVN->getMask().end(), [](int i) { return i == -1; })) {
11382 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11383 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11384 N1 = DAG.getUNDEF(ConcatVT);
11385 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11386 }
11387
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011388 // Look at every vector that's inserted. We're looking for exact
11389 // subvector-sized copies from a concatenated vector
11390 for (unsigned I = 0; I != NumConcats; ++I) {
11391 // Make sure we're dealing with a copy.
11392 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000011393 bool AllUndef = true, NoUndef = true;
11394 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11395 if (SVN->getMaskElt(J) >= 0)
11396 AllUndef = false;
11397 else
11398 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011399 }
11400
Hao Liubc601962013-05-13 02:07:05 +000011401 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000011402 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11403 return SDValue();
11404
11405 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11406 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11407 return SDValue();
11408
11409 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11410 if (FirstElt < N0.getNumOperands())
11411 Ops.push_back(N0.getOperand(FirstElt));
11412 else
11413 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11414
11415 } else if (AllUndef) {
11416 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11417 } else { // Mixed with general masks and undefs, can't do optimization.
11418 return SDValue();
11419 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011420 }
11421
Craig Topper48d114b2014-04-26 18:35:24 +000011422 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011423}
11424
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011425SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011426 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011427 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011428
Mon P Wang25f01062008-11-10 04:46:22 +000011429 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000011430 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000011431
Craig Topper5894fe42012-04-09 05:16:56 +000011432 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000011433
Craig Topper279c77b2012-01-04 08:07:43 +000011434 // Canonicalize shuffle undef, undef -> undef
11435 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11436 return DAG.getUNDEF(VT);
11437
11438 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11439
11440 // Canonicalize shuffle v, v -> v, undef
11441 if (N0 == N1) {
11442 SmallVector<int, 8> NewMask;
11443 for (unsigned i = 0; i != NumElts; ++i) {
11444 int Idx = SVN->getMaskElt(i);
11445 if (Idx >= (int)NumElts) Idx -= NumElts;
11446 NewMask.push_back(Idx);
11447 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011448 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011449 &NewMask[0]);
11450 }
11451
11452 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11453 if (N0.getOpcode() == ISD::UNDEF) {
11454 SmallVector<int, 8> NewMask;
11455 for (unsigned i = 0; i != NumElts; ++i) {
11456 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000011457 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000011458 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000011459 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000011460 else
11461 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000011462 }
11463 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000011464 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011465 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011466 &NewMask[0]);
11467 }
11468
11469 // Remove references to rhs if it is undef
11470 if (N1.getOpcode() == ISD::UNDEF) {
11471 bool Changed = false;
11472 SmallVector<int, 8> NewMask;
11473 for (unsigned i = 0; i != NumElts; ++i) {
11474 int Idx = SVN->getMaskElt(i);
11475 if (Idx >= (int)NumElts) {
11476 Idx = -1;
11477 Changed = true;
11478 }
11479 NewMask.push_back(Idx);
11480 }
11481 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000011482 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000011483 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000011484
Bob Wilsonf63da122010-10-28 17:06:14 +000011485 // If it is a splat, check if the argument vector is another splat or a
11486 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000011487 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000011488 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000011489
Dan Gohmana8665142007-06-25 16:23:39 +000011490 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000011491 // not the number of vector elements, look through it. Be careful not to
11492 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000011493 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011494 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000011495 if (ConvInput.getValueType().isVector() &&
11496 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011497 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000011498 }
11499
Dan Gohmana8665142007-06-25 16:23:39 +000011500 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000011501 assert(V->getNumOperands() == NumElts &&
11502 "BUILD_VECTOR has wrong number of operands");
11503 SDValue Base;
11504 bool AllSame = true;
11505 for (unsigned i = 0; i != NumElts; ++i) {
11506 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11507 Base = V->getOperand(i);
11508 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000011509 }
Evan Cheng7c970b92006-07-21 08:25:53 +000011510 }
Bob Wilsonf63da122010-10-28 17:06:14 +000011511 // Splat of <u, u, u, u>, return <u, u, u, u>
11512 if (!Base.getNode())
11513 return N0;
11514 for (unsigned i = 0; i != NumElts; ++i) {
11515 if (V->getOperand(i) != Base) {
11516 AllSame = false;
11517 break;
11518 }
11519 }
11520 // Splat of <x, x, x, x>, return <x, x, x, x>
11521 if (AllSame)
11522 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000011523 }
11524 }
Nadav Rotemb0783502012-04-01 19:31:22 +000011525
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011526 // There are various patterns used to build up a vector from smaller vectors,
11527 // subvectors, or elements. Scan chains of these and replace unused insertions
11528 // or components with undef.
11529 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11530 return S;
11531
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011532 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11533 Level < AfterLegalizeVectorOps &&
11534 (N1.getOpcode() == ISD::UNDEF ||
11535 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11536 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11537 SDValue V = partitionShuffleOfConcats(N, DAG);
11538
11539 if (V.getNode())
11540 return V;
11541 }
11542
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000011543 // Canonicalize shuffles according to rules:
11544 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11545 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11546 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011547 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000011548 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11549 TLI.isTypeLegal(VT)) {
11550 // The incoming shuffle must be of the same type as the result of the
11551 // current shuffle.
11552 assert(N1->getOperand(0).getValueType() == VT &&
11553 "Shuffle types don't match");
11554
11555 SDValue SV0 = N1->getOperand(0);
11556 SDValue SV1 = N1->getOperand(1);
11557 bool HasSameOp0 = N0 == SV0;
11558 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11559 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11560 // Commute the operands of this shuffle so that next rule
11561 // will trigger.
11562 return DAG.getCommutedVectorShuffle(*SVN);
11563 }
11564
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011565 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011566 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11567 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11568 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011569 // Don't try to fold shuffles with illegal type.
11570 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011571 TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011572 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11573
11574 // The incoming shuffle must be of the same type as the result of the
11575 // current shuffle.
11576 assert(OtherSV->getOperand(0).getValueType() == VT &&
11577 "Shuffle types don't match");
11578
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011579 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011580 SmallVector<int, 4> Mask;
11581 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11582 // operand, and SV1 as the second operand.
11583 for (unsigned i = 0; i != NumElts; ++i) {
11584 int Idx = SVN->getMaskElt(i);
11585 if (Idx < 0) {
11586 // Propagate Undef.
11587 Mask.push_back(Idx);
11588 continue;
11589 }
11590
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011591 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011592 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011593 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11594 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011595 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011596 if (Idx < 0) {
11597 // Propagate Undef.
11598 Mask.push_back(Idx);
11599 continue;
11600 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011601
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011602 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11603 : OtherSV->getOperand(1);
11604 } else {
11605 // This shuffle index references an element within N1.
11606 CurrentVec = N1;
11607 }
11608
11609 // Simple case where 'CurrentVec' is UNDEF.
11610 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11611 Mask.push_back(-1);
11612 continue;
11613 }
11614
11615 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11616 // will be the first or second operand of the combined shuffle.
11617 Idx = Idx % NumElts;
11618 if (!SV0.getNode() || SV0 == CurrentVec) {
11619 // Ok. CurrentVec is the left hand side.
11620 // Update the mask accordingly.
11621 SV0 = CurrentVec;
11622 Mask.push_back(Idx);
11623 continue;
11624 }
11625
11626 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11627 if (SV1.getNode() && SV1 != CurrentVec)
11628 return SDValue();
11629
11630 // Ok. CurrentVec is the right hand side.
11631 // Update the mask accordingly.
11632 SV1 = CurrentVec;
11633 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011634 }
11635
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000011636 // Check if all indices in Mask are Undef. In case, propagate Undef.
11637 bool isUndefMask = true;
11638 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11639 isUndefMask &= Mask[i] < 0;
11640
11641 if (isUndefMask)
11642 return DAG.getUNDEF(VT);
11643
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011644 if (!SV0.getNode())
11645 SV0 = DAG.getUNDEF(VT);
11646 if (!SV1.getNode())
11647 SV1 = DAG.getUNDEF(VT);
11648
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011649 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011650 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11651 // Compute the commuted shuffle mask and test again.
11652 for (unsigned i = 0; i != NumElts; ++i) {
11653 int idx = Mask[i];
11654 if (idx < 0)
11655 continue;
11656 else if (idx < (int)NumElts)
11657 Mask[i] = idx + NumElts;
11658 else
11659 Mask[i] = idx - NumElts;
11660 }
11661
11662 if (!TLI.isShuffleMaskLegal(Mask, VT))
11663 return SDValue();
11664
11665 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11666 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11667 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11668 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011669 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000011670
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011671 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11672 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11673 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11674 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011675 }
11676
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011677 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011678}
11679
Manman Ren413a6cb2014-01-31 01:10:35 +000011680SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11681 SDValue N0 = N->getOperand(0);
11682 SDValue N2 = N->getOperand(2);
11683
11684 // If the input vector is a concatenation, and the insert replaces
11685 // one of the halves, we can optimize into a single concat_vectors.
11686 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11687 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11688 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11689 EVT VT = N->getValueType(0);
11690
11691 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11692 // (concat_vectors Z, Y)
11693 if (InsIdx == 0)
11694 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11695 N->getOperand(1), N0.getOperand(1));
11696
11697 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11698 // (concat_vectors X, Z)
11699 if (InsIdx == VT.getVectorNumElements()/2)
11700 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11701 N0.getOperand(0), N->getOperand(1));
11702 }
11703
11704 return SDValue();
11705}
11706
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011707/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11708/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000011709/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000011710/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011711SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011712 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011713 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011714 SDValue LHS = N->getOperand(0);
11715 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000011716 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000011717 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000011718 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011719 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011720 SmallVector<int, 8> Indices;
11721 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000011722 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011723 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011724 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011725 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000011726
11727 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011728 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011729 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Andrea Di Biagioce46b972014-11-05 13:04:14 +000011730 Indices.push_back(NumElts+i);
Evan Chenga320abc2006-04-20 08:56:16 +000011731 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011732 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011733 }
11734
11735 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011736 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011737 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011738 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011739
Dan Gohmana8665142007-06-25 16:23:39 +000011740 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000011741 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011742 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000011743 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000011744 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000011745 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011746 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000011747 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000011748 }
11749 }
Bill Wendling31b50992009-01-30 23:59:18 +000011750
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011751 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011752}
11753
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011754/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011755SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000011756 assert(N->getValueType(0).isVector() &&
11757 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000011758
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011759 SDValue LHS = N->getOperand(0);
11760 SDValue RHS = N->getOperand(1);
11761 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011762 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000011763
Dan Gohmana8665142007-06-25 16:23:39 +000011764 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000011765 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011766 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000011767 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000011768 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000011769 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11770 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000011771 return SDValue();
11772
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011773 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000011774 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011775 SDValue LHSOp = LHS.getOperand(i);
11776 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000011777
Evan Cheng64d28462006-05-31 06:08:35 +000011778 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000011779 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11780 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000011781 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011782 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000011783 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011784 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000011785 break;
11786 }
Bill Wendling31b50992009-01-30 23:59:18 +000011787
Bob Wilson54081442010-12-17 23:06:49 +000011788 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000011789 EVT RVT = RHSOp.getValueType();
11790 if (RVT != VT) {
11791 // Integer BUILD_VECTOR operands may have types larger than the element
11792 // size (e.g., when the element type is not legal). Prior to type
11793 // legalization, the types may not match between the two BUILD_VECTORS.
11794 // Truncate one of the operands to make them match.
11795 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011796 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011797 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011798 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011799 VT = RVT;
11800 }
11801 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011802 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000011803 LHSOp, RHSOp);
11804 if (FoldOp.getOpcode() != ISD::UNDEF &&
11805 FoldOp.getOpcode() != ISD::Constant &&
11806 FoldOp.getOpcode() != ISD::ConstantFP)
11807 break;
11808 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011809 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000011810 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011811
Bob Wilson54081442010-12-17 23:06:49 +000011812 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000011813 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000011814 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011815
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011816 // Type legalization might introduce new shuffles in the DAG.
11817 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11818 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11819 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11820 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11821 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11822 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11823 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11824 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11825
11826 if (SVN0->getMask().equals(SVN1->getMask())) {
11827 EVT VT = N->getValueType(0);
11828 SDValue UndefVector = LHS.getOperand(1);
11829 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11830 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011831 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011832 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11833 &SVN0->getMask()[0]);
11834 }
11835 }
11836
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011837 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011838}
11839
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011840/// Visit a binary vector operation, like FABS/FNEG.
Craig Topper82384612012-09-11 01:45:21 +000011841SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011842 assert(N->getValueType(0).isVector() &&
11843 "SimplifyVUnaryOp only works on vectors!");
11844
11845 SDValue N0 = N->getOperand(0);
11846
11847 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11848 return SDValue();
11849
11850 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11851 SmallVector<SDValue, 8> Ops;
11852 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11853 SDValue Op = N0.getOperand(i);
11854 if (Op.getOpcode() != ISD::UNDEF &&
11855 Op.getOpcode() != ISD::ConstantFP)
11856 break;
11857 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011858 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011859 if (FoldOp.getOpcode() != ISD::UNDEF &&
11860 FoldOp.getOpcode() != ISD::ConstantFP)
11861 break;
11862 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011863 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011864 }
11865
11866 if (Ops.size() != N0.getNumOperands())
11867 return SDValue();
11868
Craig Topper48d114b2014-04-26 18:35:24 +000011869 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011870}
11871
Andrew Trickef9de2a2013-05-25 02:42:55 +000011872SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011873 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011874 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011875
Bill Wendling31b50992009-01-30 23:59:18 +000011876 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011877 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011878
Nate Begeman2042aa52005-10-08 00:29:44 +000011879 // If we got a simplified select_cc node back from SimplifySelectCC, then
11880 // break it down into a new SETCC node, and a new SELECT node, and then return
11881 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011882 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011883 // Check to see if we got a select_cc back (to turn into setcc/select).
11884 // Otherwise, just return whatever node we got back, like fabs.
11885 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011886 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011887 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011888 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011889 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011890 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000011891 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11892 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000011893 }
Bill Wendling31b50992009-01-30 23:59:18 +000011894
Nate Begeman2042aa52005-10-08 00:29:44 +000011895 return SCC;
11896 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011897 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011898}
11899
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011900/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11901/// being selected between, see if we can simplify the select. Callers of this
11902/// should assume that TheSelect is deleted if this returns true. As such, they
11903/// should return the appropriate thing (e.g. the node) back to the top-level of
11904/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011905bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011906 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011907
Nadav Rotema49a02a2011-02-11 19:57:47 +000011908 // Cannot simplify select with vector condition
11909 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11910
Chris Lattner6c14c352005-10-18 06:04:22 +000011911 // If this is a select from two identical things, try to pull the operation
11912 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011913 if (LHS.getOpcode() != RHS.getOpcode() ||
11914 !LHS.hasOneUse() || !RHS.hasOneUse())
11915 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011916
Chris Lattner254c4452010-09-21 15:46:59 +000011917 // If this is a load and the token chain is identical, replace the select
11918 // of two loads with a load through a select of the address to load from.
11919 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11920 // constants have been dropped into the constant pool.
11921 if (LHS.getOpcode() == ISD::LOAD) {
11922 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11923 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011924
Chris Lattner254c4452010-09-21 15:46:59 +000011925 // Token chains must be identical.
11926 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011927 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011928 LLD->isVolatile() || RLD->isVolatile() ||
11929 // If this is an EXTLOAD, the VT's must match.
11930 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011931 // If this is an EXTLOAD, the kind of extension must match.
11932 (LLD->getExtensionType() != RLD->getExtensionType() &&
11933 // The only exception is if one of the extensions is anyext.
11934 LLD->getExtensionType() != ISD::EXTLOAD &&
11935 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011936 // FIXME: this discards src value information. This is
11937 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011938 // both potential memory locations. Since we are discarding
11939 // src value info, don't do the transformation if the memory
11940 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011941 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011942 RLD->getPointerInfo().getAddrSpace() != 0 ||
11943 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11944 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011945 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011946
Chris Lattnere3267522010-09-21 15:58:55 +000011947 // Check that the select condition doesn't reach either load. If so,
11948 // folding this will induce a cycle into the DAG. If not, this is safe to
11949 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011950 SDValue Addr;
11951 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011952 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11953 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11954 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11955 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011956 // The loads must not depend on one another.
11957 if (LLD->isPredecessorOf(RLD) ||
11958 RLD->isPredecessorOf(LLD))
11959 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011960 Addr = DAG.getSelect(SDLoc(TheSelect),
11961 LLD->getBasePtr().getValueType(),
11962 TheSelect->getOperand(0), LLD->getBasePtr(),
11963 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011964 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011965 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11966 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11967
11968 if ((LLD->hasAnyUseOfValue(1) &&
11969 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011970 (RLD->hasAnyUseOfValue(1) &&
11971 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011972 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011973
Andrew Trickef9de2a2013-05-25 02:42:55 +000011974 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011975 LLD->getBasePtr().getValueType(),
11976 TheSelect->getOperand(0),
11977 TheSelect->getOperand(1),
11978 LLD->getBasePtr(), RLD->getBasePtr(),
11979 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011980 }
11981
Chris Lattnere3267522010-09-21 15:58:55 +000011982 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000011983 // It is safe to replace the two loads if they have different alignments,
11984 // but the new load must be the minimum (most restrictive) alignment of the
11985 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000011986 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000011987 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011988 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11989 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011990 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000011991 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011992 LLD->getChain(), Addr, MachinePointerInfo(),
11993 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011994 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000011995 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011996 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11997 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011998 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011999 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000012000 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012001 LLD->getChain(), Addr, MachinePointerInfo(),
12002 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012003 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000012004 }
Chris Lattnere3267522010-09-21 15:58:55 +000012005
12006 // Users of the select now use the result of the load.
12007 CombineTo(TheSelect, Load);
12008
12009 // Users of the old loads now use the new load's chain. We know the
12010 // old-load value is dead now.
12011 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12012 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12013 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000012014 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012015
Chris Lattner6c14c352005-10-18 06:04:22 +000012016 return false;
12017}
12018
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012019/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000012020/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000012021SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012022 SDValue N2, SDValue N3,
12023 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000012024 // (x ? y : y) -> y.
12025 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000012026
Owen Anderson53aa7a92009-08-10 22:56:29 +000012027 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000012028 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12029 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12030 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012031
12032 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000012033 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000012034 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012035 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000012036 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012037
12038 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000012039 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012040 return N2;
12041 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000012042 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012043 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012044
Nate Begeman2042aa52005-10-08 00:29:44 +000012045 // Check to see if we can simplify the select into an fabs node
12046 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12047 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000012048 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012049 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12050 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12051 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12052 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000012053 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012054
Nate Begeman2042aa52005-10-08 00:29:44 +000012055 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12056 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12057 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12058 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000012059 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000012060 }
12061 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012062
Chris Lattner43d63772009-03-11 05:08:08 +000012063 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12064 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12065 // in it. This is a win when the constant is not otherwise available because
12066 // it replaces two constant pool loads with one. We only do this if the FP
12067 // type is known to be legal, because if it isn't, then we are before legalize
12068 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000012069 // messing with soft float) and if the ConstantFP is not legal, because if
12070 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000012071 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12072 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12073 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000012074 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000012075 TargetLowering::Legal &&
12076 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12077 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000012078 // If both constants have multiple uses, then we won't need to do an
12079 // extra load, they are likely around in registers for other users.
12080 (TV->hasOneUse() || FV->hasOneUse())) {
12081 Constant *Elts[] = {
12082 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12083 const_cast<ConstantFP*>(TV->getConstantFPValue())
12084 };
Chris Lattner229907c2011-07-18 04:54:35 +000012085 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000012086 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000012087
Chris Lattner43d63772009-03-11 05:08:08 +000012088 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000012089 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000012090 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12091 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000012092 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000012093
12094 // Get the offsets to the 0 and 1 element of the array so that we can
12095 // select between them.
12096 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000012097 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000012098 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000012099
Chris Lattner43d63772009-03-11 05:08:08 +000012100 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000012101 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000012102 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012103 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012104 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12105 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012106 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000012107 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000012108 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012109 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000012110 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000012111 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000012112 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000012113
12114 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012115 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012116
Nate Begeman2042aa52005-10-08 00:29:44 +000012117 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000012118 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000012119 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000012120 (N1C->isNullValue() || // (a < 0) ? b : 0
12121 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000012122 EVT XType = N0.getValueType();
12123 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000012124 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000012125 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000012126 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012127 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12128 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000012129 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000012130 SDValue ShCt = DAG.getConstant(ShCtV,
12131 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012132 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012133 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012134 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000012135
Duncan Sands11dd4242008-06-08 20:54:56 +000012136 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000012137 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012138 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012139 }
Bill Wendling31b50992009-01-30 23:59:18 +000012140
12141 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000012142 }
Bill Wendling31b50992009-01-30 23:59:18 +000012143
Andrew Trickef9de2a2013-05-25 02:42:55 +000012144 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012145 XType, N0,
12146 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012147 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012148 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000012149
Duncan Sands11dd4242008-06-08 20:54:56 +000012150 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000012151 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012152 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012153 }
Bill Wendling31b50992009-01-30 23:59:18 +000012154
12155 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000012156 }
12157 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012158
Owen Anderson3231d132010-09-22 22:58:22 +000012159 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12160 // where y is has a single bit set.
12161 // A plaintext description would be, we can turn the SELECT_CC into an AND
12162 // when the condition can be materialized as an all-ones register. Any
12163 // single bit-test can be materialized as an all-ones register with
12164 // shift-left and shift-right-arith.
12165 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12166 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000012167 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000012168 N2C && N2C->isNullValue()) {
12169 SDValue AndLHS = N0->getOperand(0);
12170 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12171 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12172 // Shift the tested bit over the sign bit.
12173 APInt AndMask = ConstAndRHS->getAPIntValue();
12174 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000012175 DAG.getConstant(AndMask.countLeadingZeros(),
12176 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012177 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000012178
Owen Anderson3231d132010-09-22 22:58:22 +000012179 // Now arithmetic right shift it all the way over, so the result is either
12180 // all-ones, or zero.
12181 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000012182 DAG.getConstant(AndMask.getBitWidth()-1,
12183 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012184 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000012185
Owen Anderson3231d132010-09-22 22:58:22 +000012186 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12187 }
12188 }
12189
Nate Begeman6828ed92005-10-10 21:26:48 +000012190 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000012191 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000012192 TLI.getBooleanContents(N0.getValueType()) ==
12193 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012194
Chris Lattnera083ffc2007-04-11 06:50:51 +000012195 // If the caller doesn't want us to simplify this into a zext of a compare,
12196 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012197 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012198 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012199
Nate Begeman6828ed92005-10-10 21:26:48 +000012200 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012201 // NOTE: Don't create a SETCC if it's not legal on this target.
12202 if (!LegalOperations ||
12203 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000012204 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012205 SDValue Temp, SCC;
12206 // cast from setcc result type to select result type
12207 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000012208 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012209 N0, N1, CC);
12210 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000012211 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012212 N2.getValueType());
12213 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000012214 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012215 N2.getValueType(), SCC);
12216 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012217 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12218 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000012219 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012220 }
12221
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012222 AddToWorklist(SCC.getNode());
12223 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012224
12225 if (N2C->getAPIntValue() == 1)
12226 return Temp;
12227
12228 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000012229 return DAG.getNode(
12230 ISD::SHL, DL, N2.getValueType(), Temp,
12231 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12232 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000012233 }
Nate Begeman6828ed92005-10-10 21:26:48 +000012234 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012235
Nate Begeman2042aa52005-10-08 00:29:44 +000012236 // Check to see if this is the equivalent of setcc
12237 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12238 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012239 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012240 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000012241 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000012242 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12243 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000012244 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000012245 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000012246 return Res;
12247 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012248
Bill Wendling31b50992009-01-30 23:59:18 +000012249 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000012250 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000012251 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000012252 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012253 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012254 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000012255 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000012256 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000012257 }
Bill Wendling31b50992009-01-30 23:59:18 +000012258 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000012259 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012260 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012261 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000012262 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000012263 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000012264 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000012265 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012266 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000012267 }
Bill Wendling31b50992009-01-30 23:59:18 +000012268 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000012269 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012270 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012271 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012272 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000012273 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000012274 }
12275 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012276
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012277 // Check to see if this is an integer abs.
12278 // select_cc setg[te] X, 0, X, -X ->
12279 // select_cc setgt X, -1, X, -X ->
12280 // select_cc setl[te] X, 0, -X, X ->
12281 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000012282 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012283 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000012284 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012285 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12286 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12287 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12288 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12289 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12290 (N1C->isOne() && CC == ISD::SETLT)) &&
12291 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12292 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12293
Owen Anderson53aa7a92009-08-10 22:56:29 +000012294 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012295 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012296 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012297 N0,
12298 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012299 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012300 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012301 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012302 AddToWorklist(Shift.getNode());
12303 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012304 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000012305 }
12306 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012307
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012308 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012309}
12310
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012311/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000012312SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012313 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000012314 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012315 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000012316 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000012317 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000012318}
12319
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012320/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000012321/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000012322/// by a magic number.
12323/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012324SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012325 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12326 if (!C)
12327 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012328
12329 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012330 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012331 return SDValue();
12332
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012333 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012334 SDValue S =
12335 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012336
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012337 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012338 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012339 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012340}
12341
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012342/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12343/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000012344SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12345 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12346 if (!C)
12347 return SDValue();
12348
12349 // Avoid division by zero.
12350 if (!C->getAPIntValue())
12351 return SDValue();
12352
12353 std::vector<SDNode *> Built;
12354 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12355
12356 for (SDNode *N : Built)
12357 AddToWorklist(N);
12358 return S;
12359}
12360
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012361/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12362/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000012363/// number.
12364/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012365SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012366 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12367 if (!C)
12368 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012369
12370 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012371 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012372 return SDValue();
12373
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012374 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012375 SDValue S =
12376 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000012377
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012378 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012379 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012380 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012381}
12382
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012383SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12384 if (Level >= AfterLegalizeDAG)
12385 return SDValue();
12386
Sanjay Patelb67bd262014-09-21 15:19:15 +000012387 // Expose the DAG combiner to the target combiner implementations.
12388 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000012389
Sanjay Patelab7f4602014-09-30 20:44:23 +000012390 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000012391 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000012392 if (Iterations) {
12393 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12394 // For the reciprocal, we need to find the zero of the function:
12395 // F(X) = A X - 1 [which has a zero at X = 1/A]
12396 // =>
12397 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12398 // does not require additional intermediate precision]
12399 EVT VT = Op.getValueType();
12400 SDLoc DL(Op);
12401 SDValue FPOne = DAG.getConstantFP(1.0, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012402
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012403 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012404
Sanjay Patelab7f4602014-09-30 20:44:23 +000012405 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12406 for (unsigned i = 0; i < Iterations; ++i) {
12407 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12408 AddToWorklist(NewEst.getNode());
12409
12410 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12411 AddToWorklist(NewEst.getNode());
12412
12413 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12414 AddToWorklist(NewEst.getNode());
12415
12416 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12417 AddToWorklist(Est.getNode());
12418 }
12419 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012420 return Est;
12421 }
12422
12423 return SDValue();
12424}
12425
Sanjay Patel957efc232014-10-24 17:02:16 +000012426/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12427/// For the reciprocal sqrt, we need to find the zero of the function:
12428/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12429/// =>
12430/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12431/// As a result, we precompute A/2 prior to the iteration loop.
12432SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12433 unsigned Iterations) {
12434 EVT VT = Arg.getValueType();
12435 SDLoc DL(Arg);
12436 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012437
Sanjay Patel957efc232014-10-24 17:02:16 +000012438 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12439 // this entire sequence requires only one FP constant.
12440 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12441 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012442
Sanjay Patel957efc232014-10-24 17:02:16 +000012443 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12444 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012445
Sanjay Patel957efc232014-10-24 17:02:16 +000012446 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12447 for (unsigned i = 0; i < Iterations; ++i) {
12448 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12449 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012450
Sanjay Patel957efc232014-10-24 17:02:16 +000012451 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12452 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012453
Sanjay Patel957efc232014-10-24 17:02:16 +000012454 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12455 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012456
Sanjay Patel957efc232014-10-24 17:02:16 +000012457 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12458 AddToWorklist(Est.getNode());
12459 }
12460 return Est;
12461}
12462
12463/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12464/// For the reciprocal sqrt, we need to find the zero of the function:
12465/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12466/// =>
12467/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12468SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12469 unsigned Iterations) {
12470 EVT VT = Arg.getValueType();
12471 SDLoc DL(Arg);
12472 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12473 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12474
12475 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12476 for (unsigned i = 0; i < Iterations; ++i) {
12477 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12478 AddToWorklist(HalfEst.getNode());
12479
12480 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12481 AddToWorklist(Est.getNode());
12482
12483 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12484 AddToWorklist(Est.getNode());
12485
12486 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12487 AddToWorklist(Est.getNode());
12488
12489 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12490 AddToWorklist(Est.getNode());
12491 }
12492 return Est;
12493}
12494
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012495SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12496 if (Level >= AfterLegalizeDAG)
12497 return SDValue();
12498
12499 // Expose the DAG combiner to the target combiner implementations.
12500 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000012501 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000012502 bool UseOneConstNR = false;
12503 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12504 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000012505 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000012506 Est = UseOneConstNR ?
12507 BuildRsqrtNROneConst(Op, Est, Iterations) :
12508 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000012509 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012510 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000012511 }
12512
12513 return SDValue();
12514}
12515
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012516/// Return true if base is a frame index, which is known not to alias with
12517/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000012518static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000012519 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000012520 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000012521 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012522
Jim Laskey0463e082006-10-07 23:37:56 +000012523 // If it's an adding a simple constant then integrate the offset.
12524 if (Base.getOpcode() == ISD::ADD) {
12525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12526 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000012527 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000012528 }
12529 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012530
Nate Begeman18150d52009-09-25 06:05:26 +000012531 // Return the underlying GlobalValue, and update the Offset. Return false
12532 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12533 // by multiple nodes with different offsets.
12534 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12535 GV = G->getGlobal();
12536 Offset += G->getOffset();
12537 return false;
12538 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012539
Nate Begeman18150d52009-09-25 06:05:26 +000012540 // Return the underlying Constant value, and update the Offset. Return false
12541 // for ConstantSDNodes since the same constant pool entry may be represented
12542 // by multiple nodes with different offsets.
12543 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000012544 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12545 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000012546 Offset += C->getOffset();
12547 return false;
12548 }
Jim Laskey0463e082006-10-07 23:37:56 +000012549 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000012550 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000012551}
12552
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012553/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012554bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000012555 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012556 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012557
Richard Sandiford981fdeb2013-10-28 12:00:00 +000012558 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012559 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000012560
Jim Laskey0463e082006-10-07 23:37:56 +000012561 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012562 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000012563 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000012564 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000012565 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012566 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12567 Base1, Offset1, GV1, CV1);
12568 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12569 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012570
Nate Begeman18150d52009-09-25 06:05:26 +000012571 // If they have a same base address then check to see if they overlap.
12572 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012573 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12574 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012575
Owen Anderson272ff942010-09-20 20:39:59 +000012576 // It is possible for different frame indices to alias each other, mostly
12577 // when tail call optimization reuses return address slots for arguments.
12578 // To catch this case, look up the actual index of frame indices to compute
12579 // the real alias relationship.
12580 if (isFrameIndex1 && isFrameIndex2) {
12581 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12582 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12583 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012584 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12585 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000012586 }
12587
Wesley Peck527da1b2010-11-23 03:31:01 +000012588 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000012589 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000012590 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12591 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000012592
Nate Begeman879d8f12009-09-15 00:18:30 +000012593 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12594 // compared to the size and offset of the access, we may be able to prove they
12595 // do not alias. This check is conservative for now to catch cases created by
12596 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012597 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12598 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12599 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12600 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12601 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12602 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12603 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000012604
Nate Begeman879d8f12009-09-15 00:18:30 +000012605 // There is no overlap between these relatively aligned accesses of similar
12606 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012607 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12608 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000012609 return false;
12610 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012611
Eric Christopherf55d4712014-10-08 23:38:39 +000012612 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12613 ? CombinerGlobalAA
12614 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000012615#ifndef NDEBUG
12616 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12617 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12618 UseAA = false;
12619#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012620 if (UseAA &&
12621 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000012622 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012623 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12624 Op1->getSrcValueOffset());
12625 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12626 Op0->getSrcValueOffset() - MinOffset;
12627 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12628 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012629 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012630 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12631 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000012632 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012633 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12634 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000012635 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000012636 if (AAResult == AliasAnalysis::NoAlias)
12637 return false;
12638 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000012639
12640 // Otherwise we have to assume they alias.
12641 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000012642}
12643
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012644/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000012645/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012646void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000012647 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012648 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000012649 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012650
Jim Laskeyd07be232006-09-25 16:29:54 +000012651 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012652 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000012653
Jim Laskey708d0db2006-10-04 16:53:27 +000012654 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000012655 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012656 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000012657
Jim Laskey6549d222006-10-05 15:07:25 +000012658 // Look at each chain and determine if it is an alias. If so, add it to the
12659 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000012660 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000012661 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012662 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000012663 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000012664
12665 // For TokenFactor nodes, look at each operand and only continue up the
12666 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012667 // find more and revert to original chain since the xform is unlikely to be
12668 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000012669 //
12670 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012671 // chain we found before we hit a tokenfactor rather than the original
12672 // chain.
12673 if (Depth > 6 || Aliases.size() == 2) {
12674 Aliases.clear();
12675 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000012676 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012677 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012678
Nate Begeman879d8f12009-09-15 00:18:30 +000012679 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000012680 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000012681 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012682
Jim Laskey6549d222006-10-05 15:07:25 +000012683 switch (Chain.getOpcode()) {
12684 case ISD::EntryToken:
12685 // Entry token is ideal chain operand, but handled in FindBetterChain.
12686 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012687
Jim Laskey6549d222006-10-05 15:07:25 +000012688 case ISD::LOAD:
12689 case ISD::STORE: {
12690 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012691 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12692 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012693
Jim Laskey6549d222006-10-05 15:07:25 +000012694 // If chain is alias then stop here.
12695 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012696 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000012697 Aliases.push_back(Chain);
12698 } else {
12699 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012700 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012701 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000012702 }
Jim Laskey6549d222006-10-05 15:07:25 +000012703 break;
12704 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012705
Jim Laskey6549d222006-10-05 15:07:25 +000012706 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000012707 // We have to check each of the operands of the token factor for "small"
12708 // token factors, so we queue them up. Adding the operands to the queue
12709 // (stack) in reverse order maintains the original order and increases the
12710 // likelihood that getNode will find a matching token factor (CSE.)
12711 if (Chain.getNumOperands() > 16) {
12712 Aliases.push_back(Chain);
12713 break;
12714 }
Jim Laskey6549d222006-10-05 15:07:25 +000012715 for (unsigned n = Chain.getNumOperands(); n;)
12716 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012717 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000012718 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012719
Jim Laskey6549d222006-10-05 15:07:25 +000012720 default:
12721 // For all other instructions we will just have to take what we can get.
12722 Aliases.push_back(Chain);
12723 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000012724 }
12725 }
Hal Finkel51a98382014-01-24 20:12:02 +000012726
12727 // We need to be careful here to also search for aliases through the
12728 // value operand of a store, etc. Consider the following situation:
12729 // Token1 = ...
12730 // L1 = load Token1, %52
12731 // S1 = store Token1, L1, %51
12732 // L2 = load Token1, %52+8
12733 // S2 = store Token1, L2, %51+8
12734 // Token2 = Token(S1, S2)
12735 // L3 = load Token2, %53
12736 // S3 = store Token2, L3, %52
12737 // L4 = load Token2, %53+8
12738 // S4 = store Token2, L4, %52+8
12739 // If we search for aliases of S3 (which loads address %52), and we look
12740 // only through the chain, then we'll miss the trivial dependence on L1
12741 // (which also loads from %52). We then might change all loads and
12742 // stores to use Token1 as their chain operand, which could result in
12743 // copying %53 into %52 before copying %52 into %51 (which should
12744 // happen first).
12745 //
12746 // The problem is, however, that searching for such data dependencies
12747 // can become expensive, and the cost is not directly related to the
12748 // chain depth. Instead, we'll rule out such configurations here by
12749 // insisting that we've visited all chain users (except for users
12750 // of the original chain, which is not necessary). When doing this,
12751 // we need to look through nodes we don't care about (otherwise, things
12752 // like register copies will interfere with trivial cases).
12753
12754 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000012755 for (const SDNode *N : Visited)
12756 if (N != OriginalChain.getNode())
12757 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000012758
12759 while (!Worklist.empty()) {
12760 const SDNode *M = Worklist.pop_back_val();
12761
12762 // We have already visited M, and want to make sure we've visited any uses
12763 // of M that we care about. For uses that we've not visisted, and don't
12764 // care about, queue them to the worklist.
12765
12766 for (SDNode::use_iterator UI = M->use_begin(),
12767 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000012768 if (UI.getUse().getValueType() == MVT::Other &&
12769 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000012770 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12771 // We've not visited this use, and we care about it (it could have an
12772 // ordering dependency with the original node).
12773 Aliases.clear();
12774 Aliases.push_back(OriginalChain);
12775 return;
12776 }
12777
12778 // We've not visited this use, but we don't care about it. Mark it as
12779 // visited and enqueue it to the worklist.
12780 Worklist.push_back(*UI);
12781 }
12782 }
Jim Laskey708d0db2006-10-04 16:53:27 +000012783}
12784
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012785/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12786/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012787SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12788 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012789
Jim Laskey708d0db2006-10-04 16:53:27 +000012790 // Accumulate all the aliases to this node.
12791 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012792
Dan Gohman4298df62011-05-17 22:20:36 +000012793 // If no operands then chain to entry token.
12794 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000012795 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000012796
12797 // If a single operand then chain to it. We don't need to revisit it.
12798 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000012799 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000012800
Jim Laskey708d0db2006-10-04 16:53:27 +000012801 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000012802 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000012803}
12804
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012805/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000012806void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000012807 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012808 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000012809 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000012810}