blob: 1179b7617e60e10385fbb14c8d3f821a5f25eb7c [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);
Matthias Braun3ecb5572015-03-06 19:49:06 +0000249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000250 SDValue visitOR(SDNode *N);
Matthias Braun3ecb5572015-03-06 19:49:06 +0000251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000257 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000258 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000260 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000264 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000272 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000277 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000280 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
Matt Arsenault7c936902014-10-21 23:01:01 +0000294 SDValue visitFMINNUM(SDNode *N);
295 SDValue visitFMAXNUM(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000296 SDValue visitBRCOND(SDNode *N);
297 SDValue visitBR_CC(SDNode *N);
298 SDValue visitLOAD(SDNode *N);
299 SDValue visitSTORE(SDNode *N);
300 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302 SDValue visitBUILD_VECTOR(SDNode *N);
303 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000305 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +0000306 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000307 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +0000308 SDValue visitMLOAD(SDNode *N);
309 SDValue visitMSTORE(SDNode *N);
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +0000310 SDValue visitFP_TO_FP16(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000311
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +0000312 SDValue visitFADDForFMACombine(SDNode *N);
313 SDValue visitFSUBForFMACombine(SDNode *N);
314
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000315 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000316 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000317
Matt Arsenault985b9de2014-03-17 18:58:01 +0000318 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000320 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
321 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000322 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
323 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000324 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000325 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000326 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000327 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000328
329 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
330 SDValue &CC) const;
331 bool isOneUseSetCC(SDValue N) const;
332
Scott Michelcf0da6c2009-02-17 22:15:04 +0000333 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000334 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000335 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Ahmed Bougachae892d132015-02-05 18:31:02 +0000336 SDValue CombineExtLoad(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000337 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000338 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000339 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000340 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000341 SDValue BuildReciprocalEstimate(SDValue Op);
342 SDValue BuildRsqrtEstimate(SDValue Op);
Sanjay Patel957efc232014-10-24 17:02:16 +0000343 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
344 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000345 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
346 bool DemandHighBits = true);
347 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000348 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
349 SDValue InnerPos, SDValue InnerNeg,
350 unsigned PosOpcode, unsigned NegOpcode,
351 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000352 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000353 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000354 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000355 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000356 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000357 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000358
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000359 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000360
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000361 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000362 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000363 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000364 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000365
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000366 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000367 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000368
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000369 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
370 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000371 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000372
Sanjay Patel37c41c12015-01-22 18:21:26 +0000373 /// Holds a pointer to an LSBaseSDNode as well as information on where it
374 /// is located in a sequence of memory operations connected by a chain.
375 struct MemOpLink {
376 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
377 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
378 // Ptr to the mem node.
379 LSBaseSDNode *MemNode;
380 // Offset from the base ptr.
381 int64_t OffsetFromBase;
382 // What is the sequence number of this mem node.
383 // Lowest mem operand in the DAG starts at zero.
384 unsigned SequenceNum;
385 };
386
387 /// This is a helper function for MergeConsecutiveStores. When the source
388 /// elements of the consecutive stores are all constants or all extracted
389 /// vector elements, try to merge them into one larger store.
390 /// \return True if a merged store was created.
391 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
Quentin Colombet308b1712015-01-27 23:58:01 +0000392 EVT MemVT, unsigned NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +0000393 bool IsConstantSrc, bool UseVector);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +0000394
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000395 /// Merge consecutive store operations into a wide store.
396 /// This optimization uses wide integers or vectors when possible.
397 /// \return True if some memory operations were changed.
398 bool MergeConsecutiveStores(StoreSDNode *N);
399
Adam Nemet67483892014-03-04 23:28:31 +0000400 /// \brief Try to transform a truncation where C is a constant:
401 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
402 ///
403 /// \p N needs to be a truncation and its first operand an AND. Other
404 /// requirements are checked by the function (e.g. that trunc is
405 /// single-use) and if missed an empty SDValue is returned.
406 SDValue distributeTruncateThroughAnd(SDNode *N);
407
Chris Lattner4041ab62010-04-15 04:48:01 +0000408 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000409 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000410 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
411 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000412 auto *F = DAG.getMachineFunction().getFunction();
413 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
414 F->hasFnAttribute(Attribute::MinSize);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000415 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000416
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000417 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000418 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000419
Chris Lattner4041ab62010-04-15 04:48:01 +0000420 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000421
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000422 /// Returns a type large enough to hold any valid shift amount - before type
423 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000424 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000425 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
426 if (LHSTy.isVector())
427 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000428 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
429 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000430 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000431
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000432 /// This method returns true if we are running before type legalization or
433 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000434 bool isTypeLegal(const EVT &VT) {
435 if (!LegalTypes) return true;
436 return TLI.isTypeLegal(VT);
437 }
Matt Arsenault758659232013-05-18 00:21:46 +0000438
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000439 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000440 EVT getSetCCResultType(EVT VT) const {
441 return TLI.getSetCCResultType(*DAG.getContext(), VT);
442 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000443 };
444}
445
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000446
447namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000448/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000449/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000450class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000451 DAGCombiner &DC;
452public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000453 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000454 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000455
Craig Topper7b883b32014-03-08 06:31:39 +0000456 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000457 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000458 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000459};
460}
461
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000462//===----------------------------------------------------------------------===//
463// TargetLowering::DAGCombinerInfo implementation
464//===----------------------------------------------------------------------===//
465
466void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000467 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000468}
469
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000470void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000471 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000472}
473
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000474SDValue TargetLowering::DAGCombinerInfo::
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +0000475CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
Evan Chengfd81c732009-03-28 05:57:29 +0000476 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000477}
478
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000479SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000480CombineTo(SDNode *N, SDValue Res, bool AddTo) {
481 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000482}
483
484
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000485SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000486CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
487 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000488}
489
Dan Gohmane58ab792009-01-29 01:59:02 +0000490void TargetLowering::DAGCombinerInfo::
491CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
492 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
493}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000494
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000495//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000496// Helper Functions
497//===----------------------------------------------------------------------===//
498
Chandler Carruth18066972014-08-02 10:02:07 +0000499void DAGCombiner::deleteAndRecombine(SDNode *N) {
500 removeFromWorklist(N);
501
502 // If the operands of this node are only used by the node, they will now be
503 // dead. Make sure to re-visit them and recursively delete dead nodes.
504 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000505 // For an operand generating multiple values, one of the values may
506 // become dead allowing further simplification (e.g. split index
507 // arithmetic from an indexed load).
508 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000509 AddToWorklist(Op.getNode());
510
511 DAG.DeleteNode(N);
512}
513
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000514/// Return 1 if we can compute the negated form of the specified expression for
515/// the same cost as the expression itself, or 2 if we can compute the negated
516/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000517static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000518 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000519 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000520 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000521 // fneg is removable even if it has multiple uses.
522 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000523
Chris Lattnere49c9742007-05-14 22:04:50 +0000524 // Don't allow anything with multiple uses.
525 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000526
Chris Lattner46980832007-05-25 02:19:06 +0000527 // Don't recurse exponentially.
528 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000529
Chris Lattnere49c9742007-05-14 22:04:50 +0000530 switch (Op.getOpcode()) {
531 default: return false;
532 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000533 // Don't invert constant FP values after legalize. The negated constant
534 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000535 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000536 case ISD::FADD:
537 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000538 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000539
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000540 // After operation legalization, it might not be legal to create new FSUBs.
541 if (LegalOperations &&
542 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
543 return 0;
544
Craig Topper03f39772012-09-09 22:58:45 +0000545 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000546 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
547 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000548 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000550 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000551 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000552 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000553 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000554 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000555
Bill Wendling6fbf5492009-01-30 23:10:18 +0000556 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000557 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000558
Chris Lattnere49c9742007-05-14 22:04:50 +0000559 case ISD::FMUL:
560 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000561 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562
Bill Wendling6fbf5492009-01-30 23:10:18 +0000563 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000564 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000566 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000567
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000568 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000569 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000570
Chris Lattnere49c9742007-05-14 22:04:50 +0000571 case ISD::FP_EXTEND:
572 case ISD::FP_ROUND:
573 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000574 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000575 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000576 }
577}
578
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000579/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000580static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000581 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000582 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000583 // fneg is removable even if it has multiple uses.
584 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000585
Chris Lattnere49c9742007-05-14 22:04:50 +0000586 // Don't allow anything with multiple uses.
587 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000588
Chris Lattner46980832007-05-25 02:19:06 +0000589 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000590 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000591 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000592 case ISD::ConstantFP: {
593 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
594 V.changeSign();
595 return DAG.getConstantFP(V, Op.getValueType());
596 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000597 case ISD::FADD:
598 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000599 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000600
Bill Wendling6fbf5492009-01-30 23:10:18 +0000601 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000602 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000603 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000604 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000605 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000606 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000607 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000608 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000609 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000610 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000611 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000612 Op.getOperand(0));
613 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000614 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000615 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000616
Bill Wendling6fbf5492009-01-30 23:10:18 +0000617 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000618 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000619 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000620 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000621
Bill Wendling6fbf5492009-01-30 23:10:18 +0000622 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000623 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000624 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000625
Chris Lattnere49c9742007-05-14 22:04:50 +0000626 case ISD::FMUL:
627 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000628 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000629
Bill Wendling6fbf5492009-01-30 23:10:18 +0000630 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000631 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000632 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000633 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000634 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000635 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000636 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000637
Bill Wendling6fbf5492009-01-30 23:10:18 +0000638 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000639 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000640 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000641 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000642 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000643
Chris Lattnere49c9742007-05-14 22:04:50 +0000644 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000645 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000646 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000647 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000648 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000649 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000650 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000651 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000652 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000653 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000654 }
655}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000656
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000657// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000658// that selects between the target values used for true and false, making it
659// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
660// the appropriate nodes based on the type of node we are checking. This
661// simplifies life a bit for the callers.
662bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
663 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000664 if (N.getOpcode() == ISD::SETCC) {
665 LHS = N.getOperand(0);
666 RHS = N.getOperand(1);
667 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000668 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000669 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000670
671 if (N.getOpcode() != ISD::SELECT_CC ||
672 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
673 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
674 return false;
675
Oliver Stannardd29db9b2014-11-17 10:49:31 +0000676 if (TLI.getBooleanContents(N.getValueType()) ==
677 TargetLowering::UndefinedBooleanContent)
678 return false;
679
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000680 LHS = N.getOperand(0);
681 RHS = N.getOperand(1);
682 CC = N.getOperand(4);
683 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000684}
685
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000686/// Return true if this is a SetCC-equivalent operation with only one use.
687/// If this is true, it allows the users to invert the operation for free when
688/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000689bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000690 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000691 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000692 return true;
693 return false;
694}
695
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000696/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000697/// elements are all the same constant or undefined.
698static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
699 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
700 if (!C)
701 return false;
702
703 APInt SplatUndef;
704 unsigned SplatBitSize;
705 bool HasAnyUndefs;
706 EVT EltVT = N->getValueType(0).getVectorElementType();
707 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
708 HasAnyUndefs) &&
709 EltVT.getSizeInBits() >= SplatBitSize);
710}
711
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000712// \brief Returns the SDNode if it is a constant integer BuildVector
713// or constant integer.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +0000714static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
715 if (isa<ConstantSDNode>(N))
716 return N.getNode();
717 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
718 return N.getNode();
719 return nullptr;
720}
721
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000722// \brief Returns the SDNode if it is a constant float BuildVector
723// or constant float.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +0000724static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
725 if (isa<ConstantFPSDNode>(N))
726 return N.getNode();
727 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
728 return N.getNode();
729 return nullptr;
730}
731
Matt Arsenault985b9de2014-03-17 18:58:01 +0000732// \brief Returns the SDNode if it is a constant splat BuildVector or constant
733// int.
734static ConstantSDNode *isConstOrConstSplat(SDValue N) {
735 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
736 return CN;
737
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000738 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000739 BitVector UndefElements;
740 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000741
742 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000743 // FIXME: We blindly ignore splats which include undef which is overly
744 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000745 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000746 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000747 return CN;
748 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000749
750 return nullptr;
751}
752
Matt Arsenault6cc00422014-08-16 10:14:19 +0000753// \brief Returns the SDNode if it is a constant splat BuildVector or constant
754// float.
755static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
756 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
757 return CN;
758
759 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
760 BitVector UndefElements;
761 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
762
Matt Arsenault965de302014-09-02 18:33:51 +0000763 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000764 return CN;
765 }
766
767 return nullptr;
768}
769
Andrew Trickef9de2a2013-05-25 02:42:55 +0000770SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000771 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000772 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000773 if (N0.getOpcode() == Opc) {
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000774 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
775 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
Juergen Ributzka68402822014-01-13 21:49:25 +0000776 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000777 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
778 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
779 return SDValue();
Juergen Ributzka73844052014-01-13 20:51:35 +0000780 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000781 if (N0.hasOneUse()) {
782 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
783 // use
784 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
785 if (!OpNode.getNode())
786 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000787 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000788 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000789 }
790 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000791 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000792
Juergen Ributzka68402822014-01-13 21:49:25 +0000793 if (N1.getOpcode() == Opc) {
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000794 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
795 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
Juergen Ributzka68402822014-01-13 21:49:25 +0000796 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000797 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
798 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
799 return SDValue();
Juergen Ributzka68402822014-01-13 21:49:25 +0000800 }
801 if (N1.hasOneUse()) {
802 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
803 // use
804 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
805 if (!OpNode.getNode())
806 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000807 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000808 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
809 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000810 }
811 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000812
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000813 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000814}
815
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000816SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
817 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000818 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
819 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000820 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000821 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000822 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000823 To[0].getNode()->dump(&DAG);
Mehdi Aminid3892082014-12-23 18:59:02 +0000824 dbgs() << " and " << NumTo-1 << " other values\n");
825 for (unsigned i = 0, e = NumTo; i != e; ++i)
826 assert((!To[i].getNode() ||
827 N->getValueType(i) == To[i].getValueType()) &&
828 "Cannot combine value to value of different type!");
829
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000830 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000831 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000832 if (AddTo) {
833 // Push the new nodes and any users onto the worklist
834 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000835 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000836 AddToWorklist(To[i].getNode());
837 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000838 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000839 }
840 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000841
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000842 // Finally, if the node is now dead, remove it from the graph. The node
843 // may not be dead if the replacement process recursively simplified to
844 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000845 if (N->use_empty())
846 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000847 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000848}
849
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000850void DAGCombiner::
851CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000852 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000853 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000854 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000855 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000856
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000857 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000858 AddToWorklist(TLO.New.getNode());
859 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000860
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000861 // Finally, if the node is now dead, remove it from the graph. The node
862 // may not be dead if the replacement process recursively simplified to
863 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000864 if (TLO.Old.getNode()->use_empty())
865 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000866}
867
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000868/// Check the specified integer node value to see if it can be simplified or if
869/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000870bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000871 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000872 APInt KnownZero, KnownOne;
873 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
874 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000875
Dan Gohmane58ab792009-01-29 01:59:02 +0000876 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000877 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000878
Dan Gohmane58ab792009-01-29 01:59:02 +0000879 // Replace the old value with the new one.
880 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000881 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000882 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000883 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000884 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000885 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000886
Dan Gohmane58ab792009-01-29 01:59:02 +0000887 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000888 return true;
889}
890
Evan Cheng0abb54d2010-04-24 04:43:44 +0000891void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000892 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000893 EVT VT = Load->getValueType(0);
894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000895
Evan Cheng0abb54d2010-04-24 04:43:44 +0000896 DEBUG(dbgs() << "\nReplacing.9 ";
897 Load->dump(&DAG);
898 dbgs() << "\nWith: ";
899 Trunc.getNode()->dump(&DAG);
900 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000901 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000902 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
903 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000904 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000905 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000906}
907
908SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
909 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000910 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000911 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000912 EVT MemVT = LD->getMemoryVT();
913 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000914 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
915 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000916 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000917 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000918 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000919 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000920 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000921 }
922
Evan Chenge19aa5c2010-04-19 19:29:22 +0000923 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000924 switch (Opc) {
925 default: break;
926 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000927 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000928 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000929 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000930 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000931 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000932 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000933 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000934 case ISD::Constant: {
935 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000936 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000937 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000938 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000939 }
940
941 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000942 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000943 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000944}
945
Evan Cheng0abb54d2010-04-24 04:43:44 +0000946SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000947 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
948 return SDValue();
949 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000950 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000951 bool Replace = false;
952 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000953 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000954 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000955 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000956
957 if (Replace)
958 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
959 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000960 DAG.getValueType(OldVT));
961}
962
Evan Cheng0abb54d2010-04-24 04:43:44 +0000963SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000964 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000965 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000966 bool Replace = false;
967 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000968 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000969 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000970 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000971
972 if (Replace)
973 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
974 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000975}
976
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000977/// Promote the specified integer binary operation if the target indicates it is
978/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
979/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000980SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
981 if (!LegalOperations)
982 return SDValue();
983
984 EVT VT = Op.getValueType();
985 if (VT.isVector() || !VT.isInteger())
986 return SDValue();
987
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000988 // If operation type is 'undesirable', e.g. i16 on x86, consider
989 // promoting it.
990 unsigned Opc = Op.getOpcode();
991 if (TLI.isTypeDesirableForOp(Opc, VT))
992 return SDValue();
993
Evan Chengaf56fac2010-04-16 06:14:10 +0000994 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000995 // Consult target whether it is a good idea to promote this operation and
996 // what's the right type to promote it to.
997 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000998 assert(PVT != VT && "Don't know what type to promote to!");
999
Evan Cheng0abb54d2010-04-24 04:43:44 +00001000 bool Replace0 = false;
1001 SDValue N0 = Op.getOperand(0);
1002 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +00001003 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +00001004 return SDValue();
1005
Evan Cheng0abb54d2010-04-24 04:43:44 +00001006 bool Replace1 = false;
1007 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +00001008 SDValue NN1;
1009 if (N0 == N1)
1010 NN1 = NN0;
1011 else {
1012 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +00001013 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +00001014 return SDValue();
1015 }
Evan Chengf1223bd2010-04-22 20:19:46 +00001016
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001017 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +00001018 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001019 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001020
1021 if (Replace0)
1022 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1023 if (Replace1)
1024 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +00001025
Evan Chenge8136902010-04-27 19:48:13 +00001026 DEBUG(dbgs() << "\nPromoting ";
1027 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001028 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +00001029 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +00001030 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +00001031 }
1032 return SDValue();
1033}
1034
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001035/// Promote the specified integer shift operation if the target indicates it is
1036/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +00001038SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1039 if (!LegalOperations)
1040 return SDValue();
1041
1042 EVT VT = Op.getValueType();
1043 if (VT.isVector() || !VT.isInteger())
1044 return SDValue();
1045
1046 // If operation type is 'undesirable', e.g. i16 on x86, consider
1047 // promoting it.
1048 unsigned Opc = Op.getOpcode();
1049 if (TLI.isTypeDesirableForOp(Opc, VT))
1050 return SDValue();
1051
1052 EVT PVT = VT;
1053 // Consult target whether it is a good idea to promote this operation and
1054 // what's the right type to promote it to.
1055 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056 assert(PVT != VT && "Don't know what type to promote to!");
1057
Evan Cheng0abb54d2010-04-24 04:43:44 +00001058 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001059 SDValue N0 = Op.getOperand(0);
1060 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001061 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001062 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001063 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001064 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001065 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001066 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001067 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001068
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001069 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001070 if (Replace)
1071 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001072
Evan Chenge8136902010-04-27 19:48:13 +00001073 DEBUG(dbgs() << "\nPromoting ";
1074 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001075 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001076 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001077 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001078 }
1079 return SDValue();
1080}
1081
Evan Chenge19aa5c2010-04-19 19:29:22 +00001082SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1083 if (!LegalOperations)
1084 return SDValue();
1085
1086 EVT VT = Op.getValueType();
1087 if (VT.isVector() || !VT.isInteger())
1088 return SDValue();
1089
1090 // If operation type is 'undesirable', e.g. i16 on x86, consider
1091 // promoting it.
1092 unsigned Opc = Op.getOpcode();
1093 if (TLI.isTypeDesirableForOp(Opc, VT))
1094 return SDValue();
1095
1096 EVT PVT = VT;
1097 // Consult target whether it is a good idea to promote this operation and
1098 // what's the right type to promote it to.
1099 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100 assert(PVT != VT && "Don't know what type to promote to!");
1101 // fold (aext (aext x)) -> (aext x)
1102 // fold (aext (zext x)) -> (zext x)
1103 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001104 DEBUG(dbgs() << "\nPromoting ";
1105 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001106 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001107 }
1108 return SDValue();
1109}
1110
1111bool DAGCombiner::PromoteLoad(SDValue Op) {
1112 if (!LegalOperations)
1113 return false;
1114
1115 EVT VT = Op.getValueType();
1116 if (VT.isVector() || !VT.isInteger())
1117 return false;
1118
1119 // If operation type is 'undesirable', e.g. i16 on x86, consider
1120 // promoting it.
1121 unsigned Opc = Op.getOpcode();
1122 if (TLI.isTypeDesirableForOp(Opc, VT))
1123 return false;
1124
1125 EVT PVT = VT;
1126 // Consult target whether it is a good idea to promote this operation and
1127 // what's the right type to promote it to.
1128 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1129 assert(PVT != VT && "Don't know what type to promote to!");
1130
Andrew Trickef9de2a2013-05-25 02:42:55 +00001131 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001132 SDNode *N = Op.getNode();
1133 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001134 EVT MemVT = LD->getMemoryVT();
1135 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00001136 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1137 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001138 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001139 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001140 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001141 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001142 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1143
Evan Cheng0abb54d2010-04-24 04:43:44 +00001144 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001145 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001146 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001147 Result.getNode()->dump(&DAG);
1148 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001149 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001150 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1151 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001152 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001153 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001154 return true;
1155 }
1156 return false;
1157}
1158
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001159/// \brief Recursively delete a node which has no uses and any operands for
1160/// which it is the only use.
1161///
1162/// Note that this both deletes the nodes and removes them from the worklist.
1163/// It also adds any nodes who have had a user deleted to the worklist as they
1164/// may now have only one use and subject to other combines.
1165bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1166 if (!N->use_empty())
1167 return false;
1168
1169 SmallSetVector<SDNode *, 16> Nodes;
1170 Nodes.insert(N);
1171 do {
1172 N = Nodes.pop_back_val();
1173 if (!N)
1174 continue;
1175
1176 if (N->use_empty()) {
1177 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178 Nodes.insert(N->getOperand(i).getNode());
1179
1180 removeFromWorklist(N);
1181 DAG.DeleteNode(N);
1182 } else {
1183 AddToWorklist(N);
1184 }
1185 } while (!Nodes.empty());
1186 return true;
1187}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001188
Chris Lattnere49c9742007-05-14 22:04:50 +00001189//===----------------------------------------------------------------------===//
1190// Main DAG Combiner implementation
1191//===----------------------------------------------------------------------===//
1192
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001193void DAGCombiner::Run(CombineLevel AtLevel) {
1194 // set the instance variables, so that the various visit routines may use it.
1195 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001196 LegalOperations = Level >= AfterLegalizeVectorOps;
1197 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001198
Evan Cheng5e7658c2008-08-29 22:21:44 +00001199 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001200 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1201 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001202 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001203
Evan Cheng5e7658c2008-08-29 22:21:44 +00001204 // Create a dummy node (which is not added to allnodes), that adds a reference
1205 // to the root node, preventing it from being deleted, and tracking any
1206 // changes of the root.
1207 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001208
James Molloy67b6b112012-02-16 09:17:04 +00001209 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001210 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001211 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001212 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001213 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001214 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001215 N = Worklist.pop_back_val();
1216 } while (!N);
1217
1218 bool GoodWorklistEntry = WorklistMap.erase(N);
1219 (void)GoodWorklistEntry;
1220 assert(GoodWorklistEntry &&
1221 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001222
Evan Cheng5e7658c2008-08-29 22:21:44 +00001223 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1224 // N is deleted from the DAG, since they too may now be dead or may have a
1225 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001226 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001227 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001228
1229 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001230
Chandler Carruth411fb402014-07-26 05:49:40 +00001231 // If this combine is running after legalizing the DAG, re-legalize any
1232 // nodes pulled off the worklist.
1233 if (Level == AfterLegalizeDAG) {
1234 SmallSetVector<SDNode *, 16> UpdatedNodes;
1235 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1236
1237 for (SDNode *LN : UpdatedNodes) {
1238 AddToWorklist(LN);
1239 AddUsersToWorklist(LN);
1240 }
1241 if (!NIsValid)
1242 continue;
1243 }
1244
Chandler Carruthb1432742014-07-28 17:55:07 +00001245 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1246
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001247 // Add any operands of the new node which have not yet been combined to the
1248 // worklist as well. Because the worklist uniques things already, this
1249 // won't repeatedly process the same operand.
1250 CombinedNodes.insert(N);
1251 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1252 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1253 AddToWorklist(N->getOperand(i).getNode());
1254
Evan Cheng5e7658c2008-08-29 22:21:44 +00001255 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001256
Craig Topperc0196b12014-04-14 00:51:57 +00001257 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001258 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001259
Evan Cheng5e7658c2008-08-29 22:21:44 +00001260 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001261
Evan Cheng5e7658c2008-08-29 22:21:44 +00001262 // If we get back the same node we passed in, rather than a new node or
1263 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001264 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001265 // mechanics for us, we have no work to do in this case.
1266 if (RV.getNode() == N)
1267 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001268
Evan Cheng5e7658c2008-08-29 22:21:44 +00001269 assert(N->getOpcode() != ISD::DELETED_NODE &&
1270 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1271 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001272
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001273 DEBUG(dbgs() << " ... into: ";
1274 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001275
Devang Patelefec7712011-05-23 22:04:42 +00001276 // Transfer debug value.
1277 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001278 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001279 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001280 else {
1281 assert(N->getValueType(0) == RV.getValueType() &&
1282 N->getNumValues() == 1 && "Type mismatch");
1283 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001284 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001285 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001286
Evan Cheng5e7658c2008-08-29 22:21:44 +00001287 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001288 AddToWorklist(RV.getNode());
1289 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001290
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001291 // Finally, if the node is now dead, remove it from the graph. The node
1292 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001293 // something else needing this node. This will also take care of adding any
1294 // operands which have lost a user to the worklist.
1295 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001296 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001297
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001298 // If the root changed (e.g. it was a dead load, update the root).
1299 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001300 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001301}
1302
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001303SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001304 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001305 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001306 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001307 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001308 case ISD::ADD: return visitADD(N);
1309 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001310 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001311 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001312 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001313 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001314 case ISD::MUL: return visitMUL(N);
1315 case ISD::SDIV: return visitSDIV(N);
1316 case ISD::UDIV: return visitUDIV(N);
1317 case ISD::SREM: return visitSREM(N);
1318 case ISD::UREM: return visitUREM(N);
1319 case ISD::MULHU: return visitMULHU(N);
1320 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001321 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1322 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001323 case ISD::SMULO: return visitSMULO(N);
1324 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001325 case ISD::SDIVREM: return visitSDIVREM(N);
1326 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001327 case ISD::AND: return visitAND(N);
1328 case ISD::OR: return visitOR(N);
1329 case ISD::XOR: return visitXOR(N);
1330 case ISD::SHL: return visitSHL(N);
1331 case ISD::SRA: return visitSRA(N);
1332 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001333 case ISD::ROTR:
1334 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001335 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001336 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001337 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001338 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001339 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001340 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001341 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001342 case ISD::SELECT_CC: return visitSELECT_CC(N);
1343 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001344 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1345 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001346 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001347 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1348 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001349 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001350 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001351 case ISD::FADD: return visitFADD(N);
1352 case ISD::FSUB: return visitFSUB(N);
1353 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001354 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001355 case ISD::FDIV: return visitFDIV(N);
1356 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001357 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001358 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001359 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1360 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1361 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1362 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1363 case ISD::FP_ROUND: return visitFP_ROUND(N);
1364 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1365 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1366 case ISD::FNEG: return visitFNEG(N);
1367 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001368 case ISD::FFLOOR: return visitFFLOOR(N);
Matt Arsenault7c936902014-10-21 23:01:01 +00001369 case ISD::FMINNUM: return visitFMINNUM(N);
1370 case ISD::FMAXNUM: return visitFMAXNUM(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001371 case ISD::FCEIL: return visitFCEIL(N);
1372 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001373 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001374 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001375 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001376 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001377 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001378 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001379 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1380 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001381 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001382 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +00001383 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001384 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001385 case ISD::MLOAD: return visitMLOAD(N);
1386 case ISD::MSTORE: return visitMSTORE(N);
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +00001387 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001388 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001389 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001390}
1391
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001392SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001393 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001394
1395 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001396 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001397 assert(N->getOpcode() != ISD::DELETED_NODE &&
1398 "Node was deleted but visit returned NULL!");
1399
1400 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1401 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1402
1403 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001404 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001405 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001406
1407 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1408 }
1409 }
1410
Evan Chengf1005572010-04-28 07:10:39 +00001411 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001412 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001413 switch (N->getOpcode()) {
1414 default: break;
1415 case ISD::ADD:
1416 case ISD::SUB:
1417 case ISD::MUL:
1418 case ISD::AND:
1419 case ISD::OR:
1420 case ISD::XOR:
1421 RV = PromoteIntBinOp(SDValue(N, 0));
1422 break;
1423 case ISD::SHL:
1424 case ISD::SRA:
1425 case ISD::SRL:
1426 RV = PromoteIntShiftOp(SDValue(N, 0));
1427 break;
1428 case ISD::SIGN_EXTEND:
1429 case ISD::ZERO_EXTEND:
1430 case ISD::ANY_EXTEND:
1431 RV = PromoteExtend(SDValue(N, 0));
1432 break;
1433 case ISD::LOAD:
1434 if (PromoteLoad(SDValue(N, 0)))
1435 RV = SDValue(N, 0);
1436 break;
1437 }
1438 }
1439
Scott Michelcf0da6c2009-02-17 22:15:04 +00001440 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001441 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001442 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001443 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001444 SDValue N0 = N->getOperand(0);
1445 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001446
Evan Cheng31604a62008-03-22 01:55:50 +00001447 // Constant operands are canonicalized to RHS.
1448 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001449 SDValue Ops[] = {N1, N0};
1450 SDNode *CSENode;
1451 if (const BinaryWithFlagsSDNode *BinNode =
1452 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1453 CSENode = DAG.getNodeIfExists(
1454 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1455 BinNode->hasNoSignedWrap(), BinNode->isExact());
1456 } else {
1457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1458 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001459 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001460 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001461 }
1462 }
1463
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001464 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001465}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001466
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001467/// Given a node, return its input chain if it has one, otherwise return a null
1468/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001469static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001470 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001471 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001472 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001473 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001474 return N->getOperand(NumOps-1);
1475 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001476 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001477 return N->getOperand(i);
1478 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001479 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001480}
1481
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001482SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001483 // If N has two operands, where one has an input chain equal to the other,
1484 // the 'other' chain is redundant.
1485 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001486 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001487 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001488 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001489 return N->getOperand(1);
1490 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001491
Chris Lattner48fb92f2007-05-16 06:37:59 +00001492 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001493 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001494 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001495 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001496
Jim Laskey708d0db2006-10-04 16:53:27 +00001497 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001498 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001499
Jim Laskey0463e082006-10-07 23:37:56 +00001500 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001501 // encountered.
1502 for (unsigned i = 0; i < TFs.size(); ++i) {
1503 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001504
Jim Laskey708d0db2006-10-04 16:53:27 +00001505 // Check each of the operands.
1506 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001507 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001508
Jim Laskey708d0db2006-10-04 16:53:27 +00001509 switch (Op.getOpcode()) {
1510 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001511 // Entry tokens don't need to be added to the list. They are
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001512 // redundant.
Jim Laskey6549d222006-10-05 15:07:25 +00001513 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001514 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001515
Jim Laskey708d0db2006-10-04 16:53:27 +00001516 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001517 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001518 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001519 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001520 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001521 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001522 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001523 Changed = true;
1524 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001525 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001526 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001527
Jim Laskey708d0db2006-10-04 16:53:27 +00001528 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001529 // Only add if it isn't already in the list.
David Blaikie70573dc2014-11-19 07:49:26 +00001530 if (SeenOps.insert(Op.getNode()).second)
Jim Laskey6549d222006-10-05 15:07:25 +00001531 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001532 else
1533 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001534 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001535 }
1536 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001537 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001538
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001539 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001540
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001541 // If we've changed things around then replace token factor.
Jim Laskey708d0db2006-10-04 16:53:27 +00001542 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001543 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001544 // The entry token is the only possible outcome.
1545 Result = DAG.getEntryNode();
1546 } else {
1547 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001548 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001549 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001550
Jonas Paulssonbf8d0cc2015-02-11 16:10:31 +00001551 // Add users to worklist if AA is enabled, since it may introduce
1552 // a lot of new chained token factors while removing memory deps.
1553 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1554 : DAG.getSubtarget().useAA();
1555 return CombineTo(N, Result, UseAA /*add to worklist*/);
Nate Begeman02b23c62005-10-13 03:11:28 +00001556 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001557
Jim Laskey708d0db2006-10-04 16:53:27 +00001558 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001559}
1560
Chris Lattneree322b42008-02-13 07:25:05 +00001561/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001562SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001563 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001564 // Replacing results may cause a different MERGE_VALUES to suddenly
1565 // be CSE'd with N, and carry its uses with it. Iterate until no
1566 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001567 // First add the users of this node to the work list so that they
1568 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001569 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001570 do {
1571 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001572 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001573 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001574 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001575 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001576}
1577
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001578SDValue DAGCombiner::visitADD(SDNode *N) {
1579 SDValue N0 = N->getOperand(0);
1580 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001581 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001582
1583 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001584 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001585 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1586 return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001587
1588 // fold (add x, 0) -> x, vector edition
1589 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1590 return N0;
1591 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1592 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001593 }
Bill Wendling0864a752008-12-10 22:36:00 +00001594
Dan Gohman06563a82007-07-03 14:03:57 +00001595 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001596 if (N0.getOpcode() == ISD::UNDEF)
1597 return N0;
1598 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001599 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001600 // fold (add c1, c2) -> c1+c2
Matthias Braun00a40762015-02-24 18:52:01 +00001601 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1602 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001603 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001604 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001605 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00001606 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1607 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001608 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001609 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001610 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001611 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001612 // fold (add Sym, c) -> Sym+c
1613 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001614 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001615 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001616 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001617 GA->getOffset() +
1618 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001619 // fold ((c1-A)+c2) -> (c1+c2)-A
1620 if (N1C && N0.getOpcode() == ISD::SUB)
1621 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001622 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001623 DAG.getConstant(N1C->getAPIntValue()+
1624 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001625 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001626 // reassociate add
Simon Pilgrimd15c2802015-03-29 16:49:51 +00001627 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00001628 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001629 // fold ((0-A) + B) -> B-A
1630 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1631 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001632 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001633 // fold (A + (0-B)) -> A-B
1634 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1635 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001636 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001637 // fold (A+(B-A)) -> B
1638 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001639 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001640 // fold ((B-A)+A) -> B
1641 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1642 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001643 // fold (A+(B-(A+C))) to (B-C)
1644 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001645 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001646 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001647 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001648 // fold (A+(B-(C+A))) to (B-C)
1649 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001650 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001651 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001652 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001653 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001654 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1655 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001656 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001657 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001658 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001659
Dale Johannesen8c766702008-12-02 01:30:54 +00001660 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1661 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1662 SDValue N00 = N0.getOperand(0);
1663 SDValue N01 = N0.getOperand(1);
1664 SDValue N10 = N1.getOperand(0);
1665 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001666
1667 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001668 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1669 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1670 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001671 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001672
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001673 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1674 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001675
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001676 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001677 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001678 APInt LHSZero, LHSOne;
1679 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001680 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001681
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001682 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001683 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001684
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001685 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1686 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001687 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1688 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1689 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1690 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001691 }
1692 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001693
Dan Gohman954f4902010-01-19 23:30:49 +00001694 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1695 if (N1.getOpcode() == ISD::SHL &&
1696 N1.getOperand(0).getOpcode() == ISD::SUB)
1697 if (ConstantSDNode *C =
1698 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1699 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1701 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001702 N1.getOperand(0).getOperand(1),
1703 N1.getOperand(1)));
1704 if (N0.getOpcode() == ISD::SHL &&
1705 N0.getOperand(0).getOpcode() == ISD::SUB)
1706 if (ConstantSDNode *C =
1707 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1708 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001709 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1710 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001711 N0.getOperand(0).getOperand(1),
1712 N0.getOperand(1)));
1713
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001714 if (N1.getOpcode() == ISD::AND) {
1715 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001716 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001717 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1718 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001719
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001720 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1721 // and similar xforms where the inner op is either ~0 or 0.
1722 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001723 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001724 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1725 }
1726 }
1727
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001728 // add (sext i1), X -> sub X, (zext i1)
1729 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1730 N0.getOperand(0).getValueType() == MVT::i1 &&
1731 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001732 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001733 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1734 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1735 }
1736
Jan Veselyaf62cf42014-10-17 14:45:25 +00001737 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1738 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1739 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1740 if (TN->getVT() == MVT::i1) {
1741 SDLoc DL(N);
1742 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1743 DAG.getConstant(1, VT));
1744 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1745 }
1746 }
1747
Evan Chengf1005572010-04-28 07:10:39 +00001748 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001749}
1750
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001751SDValue DAGCombiner::visitADDC(SDNode *N) {
1752 SDValue N0 = N->getOperand(0);
1753 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001754 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001755
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001756 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001757 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001758 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001759 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001760 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001761
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001762 // canonicalize constant to RHS.
Matthias Braun00a40762015-02-24 18:52:01 +00001763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001765 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001766 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001767
Chris Lattner47206662007-03-04 20:40:38 +00001768 // fold (addc x, 0) -> x + no carry out
1769 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001770 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001771 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001772
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001773 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001774 APInt LHSZero, LHSOne;
1775 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001776 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001777
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001778 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001779 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001780
Chris Lattner47206662007-03-04 20:40:38 +00001781 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1782 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001783 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001784 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001785 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001786 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001787 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001788
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001789 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001790}
1791
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001792SDValue DAGCombiner::visitADDE(SDNode *N) {
1793 SDValue N0 = N->getOperand(0);
1794 SDValue N1 = N->getOperand(1);
1795 SDValue CarryIn = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001796
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001797 // canonicalize constant to RHS
Matthias Braun00a40762015-02-24 18:52:01 +00001798 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1799 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001800 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001801 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001802 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001803
Chris Lattner47206662007-03-04 20:40:38 +00001804 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001805 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001806 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001807
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001808 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001809}
1810
Eric Christophere5ca1e02011-02-16 04:50:12 +00001811// Since it may not be valid to emit a fold to zero for vector initializers
1812// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001813static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001814 SelectionDAG &DAG,
1815 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001816 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001817 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001818 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1819 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001820 return SDValue();
1821}
1822
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001823SDValue DAGCombiner::visitSUB(SDNode *N) {
1824 SDValue N0 = N->getOperand(0);
1825 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001826 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001827
Dan Gohmana8665142007-06-25 16:23:39 +00001828 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001829 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001830 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1831 return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001832
1833 // fold (sub x, 0) -> x, vector edition
1834 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1835 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001836 }
Bill Wendling0864a752008-12-10 22:36:00 +00001837
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001838 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001839 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001840 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001841 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001842 // fold (sub c1, c2) -> c1-c2
Matthias Braun00a40762015-02-24 18:52:01 +00001843 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1844 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001845 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001846 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001847 // fold (sub x, c) -> (add x, -c)
1848 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001849 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001850 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001851 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1852 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001853 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001854 // fold A-(A-B) -> B
1855 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1856 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001857 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001858 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001859 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001860 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001861 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001862 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001863 // fold C2-(A+C1) -> (C2-C1)-A
Matthias Braun00a40762015-02-24 18:52:01 +00001864 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1865 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001866 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001867 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1868 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001869 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001870 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001871 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001872 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001873 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001874 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1875 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001876 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001877 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001878 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001879 // fold ((A+(C+B))-B) -> A+C
1880 if (N0.getOpcode() == ISD::ADD &&
1881 N0.getOperand(1).getOpcode() == ISD::ADD &&
1882 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001883 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001884 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001885 // fold ((A-(B-C))-C) -> A-B
1886 if (N0.getOpcode() == ISD::SUB &&
1887 N0.getOperand(1).getOpcode() == ISD::SUB &&
1888 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001889 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001890 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001891
Dan Gohman06563a82007-07-03 14:03:57 +00001892 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001893 if (N0.getOpcode() == ISD::UNDEF)
1894 return N0;
1895 if (N1.getOpcode() == ISD::UNDEF)
1896 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001897
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001898 // If the relocation model supports it, consider symbol offsets.
1899 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001900 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001901 // fold (sub Sym, c) -> Sym-c
1902 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001903 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001904 GA->getOffset() -
1905 (uint64_t)N1C->getSExtValue());
1906 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1907 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1908 if (GA->getGlobal() == GB->getGlobal())
1909 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1910 VT);
1911 }
1912
Jan Veselyaf62cf42014-10-17 14:45:25 +00001913 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1914 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1915 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1916 if (TN->getVT() == MVT::i1) {
1917 SDLoc DL(N);
1918 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1919 DAG.getConstant(1, VT));
1920 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1921 }
1922 }
1923
Evan Chengf1005572010-04-28 07:10:39 +00001924 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001925}
1926
Craig Topper43a1bd62012-01-07 09:06:39 +00001927SDValue DAGCombiner::visitSUBC(SDNode *N) {
1928 SDValue N0 = N->getOperand(0);
1929 SDValue N1 = N->getOperand(1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001930 EVT VT = N0.getValueType();
1931
1932 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001933 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001934 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1935 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001936 MVT::Glue));
1937
1938 // fold (subc x, x) -> 0 + no borrow
1939 if (N0 == N1)
1940 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001941 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001942 MVT::Glue));
1943
1944 // fold (subc x, 0) -> x + no borrow
Matthias Braun00a40762015-02-24 18:52:01 +00001945 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1946 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001947 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001948 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001949 MVT::Glue));
1950
1951 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1952 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001953 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1954 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001955 MVT::Glue));
1956
1957 return SDValue();
1958}
1959
1960SDValue DAGCombiner::visitSUBE(SDNode *N) {
1961 SDValue N0 = N->getOperand(0);
1962 SDValue N1 = N->getOperand(1);
1963 SDValue CarryIn = N->getOperand(2);
1964
1965 // fold (sube x, y, false) -> (subc x, y)
1966 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001967 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001968
1969 return SDValue();
1970}
1971
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001972SDValue DAGCombiner::visitMUL(SDNode *N) {
1973 SDValue N0 = N->getOperand(0);
1974 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001975 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001976
Dan Gohman06563a82007-07-03 14:03:57 +00001977 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001978 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001979 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001980
1981 bool N0IsConst = false;
1982 bool N1IsConst = false;
1983 APInt ConstValue0, ConstValue1;
1984 // fold vector ops
1985 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001986 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1987 return FoldedVOp;
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001988
1989 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1990 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1991 } else {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001992 N0IsConst = isa<ConstantSDNode>(N0);
1993 if (N0IsConst)
1994 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
1995 N1IsConst = isa<ConstantSDNode>(N1);
1996 if (N1IsConst)
1997 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001998 }
1999
Nate Begeman21158fc2005-09-01 00:19:25 +00002000 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002001 if (N0IsConst && N1IsConst)
2002 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
2003
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00002004 // canonicalize constant to RHS (vector doesn't have to splat)
2005 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2006 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002007 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002008 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002009 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00002010 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002011 // We require a splat of the entire scalar bit width for non-contiguous
2012 // bit patterns.
2013 bool IsFullSplat =
2014 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002015 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002016 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002017 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00002018 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002019 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002020 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002021 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002022 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002023 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002024 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002025 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002026 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00002027 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002028 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002029 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002030 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00002031 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002032 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002033 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002034 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002035 DAG.getConstant(Log2Val,
2036 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00002037 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002038
2039 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00002040 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00002041 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002042 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2043 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002044 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002045 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002046 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002047 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002048 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002049 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002050
Chris Lattner324871e2006-03-01 03:44:24 +00002051 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2052 // use.
2053 {
Craig Topperc0196b12014-04-14 00:51:57 +00002054 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002055 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002056 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002057 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2058 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002059 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002060 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002061 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002062 isa<ConstantSDNode>(N1.getOperand(1)) &&
2063 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002064 Sh = N1; Y = N0;
2065 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002066
Gabor Greiff304a7a2008-08-28 21:40:38 +00002067 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002068 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002069 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002070 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002071 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002072 }
2073 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002074
Chris Lattnerf29f5202006-03-04 23:33:26 +00002075 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002076 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2077 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2078 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002079 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2080 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002081 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002082 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002083 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002084
Nate Begeman22e251a2006-02-03 06:46:56 +00002085 // reassociate mul
Simon Pilgrimd15c2802015-03-29 16:49:51 +00002086 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00002087 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002088
Evan Chengf1005572010-04-28 07:10:39 +00002089 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002090}
2091
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002092SDValue DAGCombiner::visitSDIV(SDNode *N) {
2093 SDValue N0 = N->getOperand(0);
2094 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002095 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002096
Dan Gohmana8665142007-06-25 16:23:39 +00002097 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002098 if (VT.isVector())
2099 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2100 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002101
Nate Begeman21158fc2005-09-01 00:19:25 +00002102 // fold (sdiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002103 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2104 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002105 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002106 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002107 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002108 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002109 return N0;
2110 // fold (sdiv X, -1) -> 0-X
2111 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002112 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002113 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002114 // If we know the sign bits of both operands are zero, strength reduce to a
2115 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002116 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002117 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002118 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002119 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002120 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002121
Nate Begeman57b35672006-02-17 07:26:20 +00002122 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002123 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2124 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002125 // If dividing by powers of two is cheap, then don't perform the following
2126 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002127 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002128 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002129
Chad Rosier17020f92014-07-23 14:57:52 +00002130 // Target-specific implementation of sdiv x, pow2.
2131 SDValue Res = BuildSDIVPow2(N);
2132 if (Res.getNode())
2133 return Res;
2134
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002135 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002136
Chris Lattner471627c2006-02-16 08:02:36 +00002137 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002138 SDValue SGN =
2139 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2140 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2141 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002142 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002143
Chris Lattner471627c2006-02-16 08:02:36 +00002144 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002145 SDValue SRL =
2146 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2147 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2148 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002149 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002150 AddToWorklist(SRL.getNode());
2151 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002152 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002153 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002154
Nate Begeman4dd38312005-10-21 00:02:42 +00002155 // If we're dividing by a positive value, we're done. Otherwise, we must
2156 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002157 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002158 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002159
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002160 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002161 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002162 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002163
Sanjay Pateld399d942015-03-31 16:17:51 +00002164 // If integer divide is expensive and we satisfy the requirements, emit an
Nate Begemanc6f067a2005-10-20 02:15:44 +00002165 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002166 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002167 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002168 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002169 }
Dan Gohmana8665142007-06-25 16:23:39 +00002170
Dan Gohman06563a82007-07-03 14:03:57 +00002171 // undef / X -> 0
2172 if (N0.getOpcode() == ISD::UNDEF)
2173 return DAG.getConstant(0, VT);
2174 // X / undef -> undef
2175 if (N1.getOpcode() == ISD::UNDEF)
2176 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002177
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002178 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002179}
2180
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002181SDValue DAGCombiner::visitUDIV(SDNode *N) {
2182 SDValue N0 = N->getOperand(0);
2183 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002184 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002185
Dan Gohmana8665142007-06-25 16:23:39 +00002186 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002187 if (VT.isVector())
2188 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2189 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002190
Nate Begeman21158fc2005-09-01 00:19:25 +00002191 // fold (udiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002192 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2193 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002194 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002195 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002196 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002197 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002198 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002199 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002200 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002201 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002202 if (N1.getOpcode() == ISD::SHL) {
2203 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002204 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002205 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002206 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002207 N1.getOperand(1),
2208 DAG.getConstant(SHC->getAPIntValue()
2209 .logBase2(),
2210 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002211 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002212 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002213 }
2214 }
2215 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002216 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002217 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002218 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002219 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002220 }
Dan Gohmana8665142007-06-25 16:23:39 +00002221
Dan Gohman06563a82007-07-03 14:03:57 +00002222 // undef / X -> 0
2223 if (N0.getOpcode() == ISD::UNDEF)
2224 return DAG.getConstant(0, VT);
2225 // X / undef -> undef
2226 if (N1.getOpcode() == ISD::UNDEF)
2227 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002228
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002229 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002230}
2231
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002232SDValue DAGCombiner::visitSREM(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002235 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002236
Nate Begeman21158fc2005-09-01 00:19:25 +00002237 // fold (srem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002238 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2239 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002240 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002241 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002242 // If we know the sign bits of both operands are zero, strength reduce to a
2243 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002244 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002245 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002246 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002247 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002248
Dan Gohman9a693412007-11-26 23:46:11 +00002249 // If X/C can be simplified by the division-by-constant logic, lower
2250 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002251 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002252 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002253 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002254 SDValue OptimizedDiv = combine(Div.getNode());
2255 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002256 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002257 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002258 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002259 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002260 return Sub;
2261 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002262 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002263
Dan Gohman06563a82007-07-03 14:03:57 +00002264 // undef % X -> 0
2265 if (N0.getOpcode() == ISD::UNDEF)
2266 return DAG.getConstant(0, VT);
2267 // X % undef -> undef
2268 if (N1.getOpcode() == ISD::UNDEF)
2269 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002270
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002271 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002272}
2273
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002274SDValue DAGCombiner::visitUREM(SDNode *N) {
2275 SDValue N0 = N->getOperand(0);
2276 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002277 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002278
Nate Begeman21158fc2005-09-01 00:19:25 +00002279 // fold (urem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002280 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2281 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002282 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002283 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002284 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002285 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002286 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002287 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002288 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2289 if (N1.getOpcode() == ISD::SHL) {
2290 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002291 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002292 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002293 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002294 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002295 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002296 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002297 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002298 }
2299 }
2300 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002301
Dan Gohman9a693412007-11-26 23:46:11 +00002302 // If X/C can be simplified by the division-by-constant logic, lower
2303 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002304 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002305 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002306 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002307 SDValue OptimizedDiv = combine(Div.getNode());
2308 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002309 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002310 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002311 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002312 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002313 return Sub;
2314 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002315 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002316
Dan Gohman06563a82007-07-03 14:03:57 +00002317 // undef % X -> 0
2318 if (N0.getOpcode() == ISD::UNDEF)
2319 return DAG.getConstant(0, VT);
2320 // X % undef -> undef
2321 if (N1.getOpcode() == ISD::UNDEF)
2322 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002323
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002324 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002325}
2326
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002327SDValue DAGCombiner::visitMULHS(SDNode *N) {
2328 SDValue N0 = N->getOperand(0);
2329 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002330 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002331 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002332 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002333
Nate Begeman21158fc2005-09-01 00:19:25 +00002334 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002335 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002336 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002337 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002338 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002339 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002340 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002341 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002342 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002343 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002344 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002345
Chris Lattner10bd29f2010-12-13 08:39:01 +00002346 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2347 // plus a shift.
2348 if (VT.isSimple() && !VT.isVector()) {
2349 MVT Simple = VT.getSimpleVT();
2350 unsigned SimpleSize = Simple.getSizeInBits();
2351 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2352 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2353 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2354 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2355 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002356 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002357 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002358 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2359 }
2360 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002361
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002362 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002363}
2364
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002365SDValue DAGCombiner::visitMULHU(SDNode *N) {
2366 SDValue N0 = N->getOperand(0);
2367 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002368 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002369 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002370 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002371
Nate Begeman21158fc2005-09-01 00:19:25 +00002372 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002373 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002374 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002375 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002376 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002377 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002378 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002379 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002380 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002381
Chris Lattner10bd29f2010-12-13 08:39:01 +00002382 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2383 // plus a shift.
2384 if (VT.isSimple() && !VT.isVector()) {
2385 MVT Simple = VT.getSimpleVT();
2386 unsigned SimpleSize = Simple.getSizeInBits();
2387 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2388 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2389 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2390 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2391 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2392 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002393 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002394 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2395 }
2396 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002397
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002398 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002399}
2400
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002401/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2402/// give the opcodes for the two computations that are being performed. Return
2403/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002404SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002405 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002406 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002407 bool HiExists = N->hasAnyUseOfValue(1);
2408 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002409 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002410 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002411 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002412 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002413 }
2414
2415 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002416 bool LoExists = N->hasAnyUseOfValue(0);
2417 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002418 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002419 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002420 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002421 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002422 }
2423
Evan Chengece4c682007-11-08 09:25:29 +00002424 // If both halves are used, return as it is.
2425 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002426 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002427
2428 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002429 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002430 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002431 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002432 SDValue LoOpt = combine(Lo.getNode());
2433 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002434 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002435 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002436 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002437 }
2438
Evan Chengece4c682007-11-08 09:25:29 +00002439 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002440 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002441 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002442 SDValue HiOpt = combine(Hi.getNode());
2443 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002444 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002445 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002446 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002447 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002448
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002449 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002450}
2451
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002452SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2453 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002454 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002455
Chris Lattner15090e12010-12-15 06:04:19 +00002456 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002457 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002458
Sanjay Pateld399d942015-03-31 16:17:51 +00002459 // If the type is twice as wide is legal, transform the mulhu to a wider
2460 // multiply plus a shift.
Chris Lattner15090e12010-12-15 06:04:19 +00002461 if (VT.isSimple() && !VT.isVector()) {
2462 MVT Simple = VT.getSimpleVT();
2463 unsigned SimpleSize = Simple.getSizeInBits();
2464 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2467 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2468 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2469 // Compute the high part as N1.
2470 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002471 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002472 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2473 // Compute the low part as N0.
2474 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2475 return CombineTo(N, Lo, Hi);
2476 }
2477 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002478
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002479 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002480}
2481
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002482SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2483 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002484 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002485
Chris Lattner15090e12010-12-15 06:04:19 +00002486 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002487 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002488
Sanjay Pateld399d942015-03-31 16:17:51 +00002489 // If the type is twice as wide is legal, transform the mulhu to a wider
2490 // multiply plus a shift.
Chris Lattner15090e12010-12-15 06:04:19 +00002491 if (VT.isSimple() && !VT.isVector()) {
2492 MVT Simple = VT.getSimpleVT();
2493 unsigned SimpleSize = Simple.getSizeInBits();
2494 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2495 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2496 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2497 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2498 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2499 // Compute the high part as N1.
2500 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002501 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002502 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2503 // Compute the low part as N0.
2504 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2505 return CombineTo(N, Lo, Hi);
2506 }
2507 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002508
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002509 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002510}
2511
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002512SDValue DAGCombiner::visitSMULO(SDNode *N) {
2513 // (smulo x, 2) -> (saddo x, x)
2514 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2515 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002516 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002517 N->getOperand(0), N->getOperand(0));
2518
2519 return SDValue();
2520}
2521
2522SDValue DAGCombiner::visitUMULO(SDNode *N) {
2523 // (umulo x, 2) -> (uaddo x, x)
2524 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2525 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002526 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002527 N->getOperand(0), N->getOperand(0));
2528
2529 return SDValue();
2530}
2531
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002532SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2533 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002534 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002535
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002536 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002537}
2538
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002539SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2540 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002541 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002543 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002544}
2545
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002546/// If this is a binary operator with two operands of the same opcode, try to
2547/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002548SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2549 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002550 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002551 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002552
Dan Gohmandd5286d2010-01-14 03:08:49 +00002553 // Bail early if none of these transforms apply.
2554 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2555
Chris Lattner002ee912006-05-05 06:31:05 +00002556 // For each of OP in AND/OR/XOR:
2557 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2558 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2559 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002560 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002561 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002562 //
2563 // do not sink logical op inside of a vector extend, since it may combine
2564 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002565 EVT Op0VT = N0.getOperand(0).getValueType();
2566 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002567 N0.getOpcode() == ISD::SIGN_EXTEND ||
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002568 N0.getOpcode() == ISD::BSWAP ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002569 // Avoid infinite looping with PromoteIntBinOp.
2570 (N0.getOpcode() == ISD::ANY_EXTEND &&
2571 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002572 (N0.getOpcode() == ISD::TRUNCATE &&
2573 (!TLI.isZExtFree(VT, Op0VT) ||
2574 !TLI.isTruncateFree(Op0VT, VT)) &&
2575 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002576 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002577 Op0VT == N1.getOperand(0).getValueType() &&
2578 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002579 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002580 N0.getOperand(0).getValueType(),
2581 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002582 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002583 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002584 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002585
Chris Lattner5ac42932006-05-05 06:10:43 +00002586 // For each of OP in SHL/SRL/SRA/AND...
2587 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2588 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2589 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002590 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002591 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002592 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002593 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002594 N0.getOperand(0).getValueType(),
2595 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002596 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002597 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002598 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002599 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002600
Nadav Rotemb0783502012-04-01 19:31:22 +00002601 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2602 // Only perform this optimization after type legalization and before
2603 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2604 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2605 // we don't want to undo this promotion.
2606 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2607 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002608 if ((N0.getOpcode() == ISD::BITCAST ||
2609 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2610 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002611 SDValue In0 = N0.getOperand(0);
2612 SDValue In1 = N1.getOperand(0);
2613 EVT In0Ty = In0.getValueType();
2614 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002615 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002616 // If both incoming values are integers, and the original types are the
2617 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002618 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002619 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2620 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002621 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002622 return BC;
2623 }
2624 }
2625
2626 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2627 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2628 // If both shuffles use the same mask, and both shuffle within a single
2629 // vector, then it is worthwhile to move the swizzle after the operation.
2630 // The type-legalizer generates this pattern when loading illegal
2631 // vector types from memory. In many cases this allows additional shuffle
2632 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002633 // There are other cases where moving the shuffle after the xor/and/or
2634 // is profitable even if shuffles don't perform a swizzle.
2635 // If both shuffles use the same mask, and both shuffles have the same first
2636 // or second operand, then it might still be profitable to move the shuffle
2637 // after the xor/and/or operation.
2638 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002639 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2640 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002641
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002642 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002643 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002644
Nadav Rotemb0783502012-04-01 19:31:22 +00002645 // Check that both shuffles use the same mask. The masks are known to be of
2646 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002647 // Check also that shuffles have only one use to avoid introducing extra
2648 // instructions.
2649 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2650 SVN0->getMask().equals(SVN1->getMask())) {
2651 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002652
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002653 // Don't try to fold this node if it requires introducing a
2654 // build vector of all zeros that might be illegal at this stage.
2655 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2656 if (!LegalTypes)
2657 ShOp = DAG.getConstant(0, VT);
2658 else
2659 ShOp = SDValue();
2660 }
2661
2662 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2663 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2664 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2665 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2666 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2667 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002668 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002669 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2670 &SVN0->getMask()[0]);
2671 }
2672
2673 // Don't try to fold this node if it requires introducing a
2674 // build vector of all zeros that might be illegal at this stage.
2675 ShOp = N0->getOperand(0);
2676 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2677 if (!LegalTypes)
2678 ShOp = DAG.getConstant(0, VT);
2679 else
2680 ShOp = SDValue();
2681 }
2682
2683 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2684 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2685 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2686 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2687 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2688 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002689 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002690 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2691 &SVN0->getMask()[0]);
2692 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002693 }
2694 }
Craig Topper9c3da312012-04-09 07:19:09 +00002695
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002696 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002697}
2698
Matthias Braun3ecb5572015-03-06 19:49:06 +00002699/// This contains all DAGCombine rules which reduce two values combined by
2700/// an And operation to a single value. This makes them reusable in the context
2701/// of visitSELECT(). Rules involving constants are not included as
2702/// visitSELECT() already handles those cases.
2703SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2704 SDNode *LocReference) {
2705 EVT VT = N1.getValueType();
2706
2707 // fold (and x, undef) -> 0
2708 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2709 return DAG.getConstant(0, VT);
2710 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2711 SDValue LL, LR, RL, RR, CC0, CC1;
2712 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2713 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2714 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2715
2716 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2717 LL.getValueType().isInteger()) {
2718 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2719 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2720 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2721 LR.getValueType(), LL, RL);
2722 AddToWorklist(ORNode.getNode());
2723 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2724 }
2725 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2727 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2728 LR.getValueType(), LL, RL);
2729 AddToWorklist(ANDNode.getNode());
2730 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2731 }
2732 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2733 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2734 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2735 LR.getValueType(), LL, RL);
2736 AddToWorklist(ORNode.getNode());
2737 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2738 }
2739 }
2740 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2741 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2742 Op0 == Op1 && LL.getValueType().isInteger() &&
2743 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2744 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2745 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2746 cast<ConstantSDNode>(RR)->isNullValue()))) {
2747 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2748 LL, DAG.getConstant(1, LL.getValueType()));
2749 AddToWorklist(ADDNode.getNode());
2750 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2751 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2752 }
2753 // canonicalize equivalent to ll == rl
2754 if (LL == RR && LR == RL) {
2755 Op1 = ISD::getSetCCSwappedOperands(Op1);
2756 std::swap(RL, RR);
2757 }
2758 if (LL == RL && LR == RR) {
2759 bool isInteger = LL.getValueType().isInteger();
2760 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2761 if (Result != ISD::SETCC_INVALID &&
2762 (!LegalOperations ||
2763 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2764 TLI.isOperationLegal(ISD::SETCC,
2765 getSetCCResultType(N0.getSimpleValueType())))))
2766 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2767 LL, LR, Result);
2768 }
2769 }
2770
2771 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2772 VT.getSizeInBits() <= 64) {
2773 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2774 APInt ADDC = ADDI->getAPIntValue();
2775 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2776 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2777 // immediate for an add, but it is legal if its top c2 bits are set,
2778 // transform the ADD so the immediate doesn't need to be materialized
2779 // in a register.
2780 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2781 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2782 SRLI->getZExtValue());
2783 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2784 ADDC |= Mask;
2785 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2786 SDValue NewAdd =
2787 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2788 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2789 CombineTo(N0.getNode(), NewAdd);
2790 // Return N so it doesn't get rechecked!
2791 return SDValue(LocReference, 0);
2792 }
2793 }
2794 }
2795 }
2796 }
2797 }
2798
2799 return SDValue();
2800}
2801
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002802SDValue DAGCombiner::visitAND(SDNode *N) {
2803 SDValue N0 = N->getOperand(0);
2804 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002805 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002806
Dan Gohmana8665142007-06-25 16:23:39 +00002807 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002808 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002809 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2810 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002811
2812 // fold (and x, 0) -> 0, vector edition
2813 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002814 // do not return N0, because undef node may exist in N0
2815 return DAG.getConstant(
2816 APInt::getNullValue(
2817 N0.getValueType().getScalarType().getSizeInBits()),
2818 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002819 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002820 // do not return N1, because undef node may exist in N1
2821 return DAG.getConstant(
2822 APInt::getNullValue(
2823 N1.getValueType().getScalarType().getSizeInBits()),
2824 N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002825
2826 // fold (and x, -1) -> x, vector edition
2827 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2828 return N1;
2829 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2830 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002831 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002832
Nate Begeman21158fc2005-09-01 00:19:25 +00002833 // fold (and c1, c2) -> c1&c2
Matthias Braun00a40762015-02-24 18:52:01 +00002834 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002836 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002837 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002838 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00002839 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2840 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002841 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002842 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002843 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002844 return N0;
2845 // if (and x, c) is known to be zero, return 0
Matthias Braun00a40762015-02-24 18:52:01 +00002846 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002847 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002848 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002849 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002850 // reassociate and
Simon Pilgrimd15c2802015-03-29 16:49:51 +00002851 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00002852 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002853 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002854 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002855 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002856 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002857 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002858 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2859 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002860 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002861 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002862 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002863 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002864 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002865 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002866
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002867 // Replace uses of the AND with uses of the Zero extend node.
2868 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002869
Chris Lattner49beaf42006-02-02 07:17:31 +00002870 // We actually want to replace all uses of the any_extend with the
2871 // zero_extend, to avoid duplicating things. This will later cause this
2872 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002873 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002874 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002875 }
2876 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002877 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002878 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2879 // already be zero by virtue of the width of the base type of the load.
2880 //
2881 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2882 // more cases.
2883 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2884 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2885 N0.getOpcode() == ISD::LOAD) {
2886 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2887 N0 : N0.getOperand(0) );
2888
2889 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2890 // This can be a pure constant or a vector splat, in which case we treat the
2891 // vector as a scalar and use the splat value.
2892 APInt Constant = APInt::getNullValue(1);
2893 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2894 Constant = C->getAPIntValue();
2895 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2896 APInt SplatValue, SplatUndef;
2897 unsigned SplatBitSize;
2898 bool HasAnyUndefs;
2899 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2900 SplatBitSize, HasAnyUndefs);
2901 if (IsSplat) {
2902 // Undef bits can contribute to a possible optimisation if set, so
2903 // set them.
2904 SplatValue |= SplatUndef;
2905
2906 // The splat value may be something like "0x00FFFFFF", which means 0 for
2907 // the first vector value and FF for the rest, repeating. We need a mask
2908 // that will apply equally to all members of the vector, so AND all the
2909 // lanes of the constant together.
2910 EVT VT = Vector->getValueType(0);
2911 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002912
2913 // If the splat value has been compressed to a bitlength lower
2914 // than the size of the vector lane, we need to re-expand it to
2915 // the lane size.
2916 if (BitWidth > SplatBitSize)
2917 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2918 SplatBitSize < BitWidth;
2919 SplatBitSize = SplatBitSize * 2)
2920 SplatValue |= SplatValue.shl(SplatBitSize);
2921
Andrea Di Biagioc9d79e82015-03-07 12:24:55 +00002922 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2923 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2924 if (SplatBitSize % BitWidth == 0) {
2925 Constant = APInt::getAllOnesValue(BitWidth);
2926 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2927 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2928 }
James Molloy862fe492012-02-20 12:02:38 +00002929 }
2930 }
2931
2932 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2933 // actually legal and isn't going to get expanded, else this is a false
2934 // optimisation.
2935 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002936 Load->getValueType(0),
James Molloy862fe492012-02-20 12:02:38 +00002937 Load->getMemoryVT());
2938
2939 // Resize the constant to the same size as the original memory access before
2940 // extension. If it is still the AllOnesValue then this AND is completely
2941 // unneeded.
2942 Constant =
2943 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2944
2945 bool B;
2946 switch (Load->getExtensionType()) {
2947 default: B = false; break;
2948 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2949 case ISD::ZEXTLOAD:
2950 case ISD::NON_EXTLOAD: B = true; break;
2951 }
2952
2953 if (B && Constant.isAllOnesValue()) {
2954 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2955 // preserve semantics once we get rid of the AND.
2956 SDValue NewLoad(Load, 0);
2957 if (Load->getExtensionType() == ISD::EXTLOAD) {
2958 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002959 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002960 Load->getChain(), Load->getBasePtr(),
2961 Load->getOffset(), Load->getMemoryVT(),
2962 Load->getMemOperand());
2963 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002964 if (Load->getNumValues() == 3) {
2965 // PRE/POST_INC loads have 3 values.
2966 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2967 NewLoad.getValue(2) };
2968 CombineTo(Load, To, 3, true);
2969 } else {
2970 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2971 }
James Molloy862fe492012-02-20 12:02:38 +00002972 }
2973
2974 // Fold the AND away, taking care not to fold to the old load node if we
2975 // replaced it.
2976 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2977
2978 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2979 }
2980 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002981
Chris Lattnerf0032b32006-02-28 06:49:37 +00002982 // fold (and (load x), 255) -> (zextload x, i8)
2983 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002984 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2985 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2986 (N0.getOpcode() == ISD::ANY_EXTEND &&
2987 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2988 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2989 LoadSDNode *LN0 = HasAnyExt
2990 ? cast<LoadSDNode>(N0.getOperand(0))
2991 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002992 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002993 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002994 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002995 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2996 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2997 EVT LoadedVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002998 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Duncan Sands93b66092008-06-09 11:32:28 +00002999
Evan Cheng166a4e62010-01-06 19:38:29 +00003000 if (ExtVT == LoadedVT &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003001 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3002 ExtVT))) {
Wesley Peck527da1b2010-11-23 03:31:01 +00003003
3004 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003005 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00003006 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3007 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003008 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003009 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3011 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003012
Chris Lattner88de3842010-01-07 21:53:27 +00003013 // Do not change the width of a volatile load.
3014 // Do not generate loads of non-round integer types since these can
3015 // be expensive (and would be wrong if the type is not byte sized).
3016 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003017 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3018 ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00003019 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00003020
Chris Lattner88de3842010-01-07 21:53:27 +00003021 unsigned Alignment = LN0->getAlignment();
3022 SDValue NewPtr = LN0->getBasePtr();
3023
3024 // For big endian targets, we need to add an offset to the pointer
3025 // to load the correct bytes. For little endian systems, we merely
3026 // need to read fewer bytes from the same pointer.
3027 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00003028 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3029 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3030 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003031 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00003032 NewPtr, DAG.getConstant(PtrOff, PtrType));
3033 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00003034 }
Chris Lattner88de3842010-01-07 21:53:27 +00003035
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003036 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00003037
Chris Lattner88de3842010-01-07 21:53:27 +00003038 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003039 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00003040 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00003041 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00003042 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00003043 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003044 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003045 CombineTo(LN0, Load, Load.getValue(1));
3046 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003047 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003048 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003049 }
3050 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003051
Matthias Braun3ecb5572015-03-06 19:49:06 +00003052 if (SDValue Combined = visitANDLike(N0, N1, N))
3053 return Combined;
3054
3055 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3056 if (N0.getOpcode() == N1.getOpcode()) {
3057 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3058 if (Tmp.getNode()) return Tmp;
Evan Chenge6a3b032012-07-17 18:54:11 +00003059 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003060
Matthias Braun3ecb5572015-03-06 19:49:06 +00003061 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3062 // fold (and (sra)) -> (and (srl)) when possible.
3063 if (!VT.isVector() &&
3064 SimplifyDemandedBits(SDValue(N, 0)))
3065 return SDValue(N, 0);
3066
3067 // fold (zext_inreg (extload x)) -> (zextload x)
3068 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3069 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3070 EVT MemVT = LN0->getMemoryVT();
3071 // If we zero all the possible extended bits, then we can turn this into
3072 // a zextload if we are running before legalize or the operation is legal.
3073 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3074 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3075 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3076 ((!LegalOperations && !LN0->isVolatile()) ||
3077 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3078 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3079 LN0->getChain(), LN0->getBasePtr(),
3080 MemVT, LN0->getMemOperand());
3081 AddToWorklist(N);
3082 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3083 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3084 }
3085 }
3086 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3087 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3088 N0.hasOneUse()) {
3089 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3090 EVT MemVT = LN0->getMemoryVT();
3091 // If we zero all the possible extended bits, then we can turn this into
3092 // a zextload if we are running before legalize or the operation is legal.
3093 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3094 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3095 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3096 ((!LegalOperations && !LN0->isVolatile()) ||
3097 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3098 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3099 LN0->getChain(), LN0->getBasePtr(),
3100 MemVT, LN0->getMemOperand());
3101 AddToWorklist(N);
3102 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3103 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3104 }
3105 }
Tim Northover819bfb52013-08-27 13:46:45 +00003106 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3107 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3108 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3109 N0.getOperand(1), false);
3110 if (BSwap.getNode())
3111 return BSwap;
3112 }
3113
Evan Chengf1005572010-04-28 07:10:39 +00003114 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003115}
3116
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003117/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003118SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3119 bool DemandHighBits) {
3120 if (!LegalOperations)
3121 return SDValue();
3122
3123 EVT VT = N->getValueType(0);
3124 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3125 return SDValue();
3126 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3127 return SDValue();
3128
3129 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3130 bool LookPassAnd0 = false;
3131 bool LookPassAnd1 = false;
3132 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3133 std::swap(N0, N1);
3134 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3135 std::swap(N0, N1);
3136 if (N0.getOpcode() == ISD::AND) {
3137 if (!N0.getNode()->hasOneUse())
3138 return SDValue();
3139 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3140 if (!N01C || N01C->getZExtValue() != 0xFF00)
3141 return SDValue();
3142 N0 = N0.getOperand(0);
3143 LookPassAnd0 = true;
3144 }
3145
3146 if (N1.getOpcode() == ISD::AND) {
3147 if (!N1.getNode()->hasOneUse())
3148 return SDValue();
3149 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3150 if (!N11C || N11C->getZExtValue() != 0xFF)
3151 return SDValue();
3152 N1 = N1.getOperand(0);
3153 LookPassAnd1 = true;
3154 }
3155
3156 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3157 std::swap(N0, N1);
3158 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3159 return SDValue();
3160 if (!N0.getNode()->hasOneUse() ||
3161 !N1.getNode()->hasOneUse())
3162 return SDValue();
3163
3164 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3165 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3166 if (!N01C || !N11C)
3167 return SDValue();
3168 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3169 return SDValue();
3170
3171 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3172 SDValue N00 = N0->getOperand(0);
3173 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3174 if (!N00.getNode()->hasOneUse())
3175 return SDValue();
3176 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3177 if (!N001C || N001C->getZExtValue() != 0xFF)
3178 return SDValue();
3179 N00 = N00.getOperand(0);
3180 LookPassAnd0 = true;
3181 }
3182
3183 SDValue N10 = N1->getOperand(0);
3184 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3185 if (!N10.getNode()->hasOneUse())
3186 return SDValue();
3187 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3188 if (!N101C || N101C->getZExtValue() != 0xFF00)
3189 return SDValue();
3190 N10 = N10.getOperand(0);
3191 LookPassAnd1 = true;
3192 }
3193
3194 if (N00 != N10)
3195 return SDValue();
3196
Tim Northover819bfb52013-08-27 13:46:45 +00003197 // Make sure everything beyond the low halfword gets set to zero since the SRL
3198 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003199 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003200 if (DemandHighBits && OpSizeInBits > 16) {
3201 // If the left-shift isn't masked out then the only way this is a bswap is
3202 // if all bits beyond the low 8 are 0. In that case the entire pattern
3203 // reduces to a left shift anyway: leave it for other parts of the combiner.
3204 if (!LookPassAnd0)
3205 return SDValue();
3206
3207 // However, if the right shift isn't masked out then it might be because
3208 // it's not needed. See if we can spot that too.
3209 if (!LookPassAnd1 &&
3210 !DAG.MaskedValueIsZero(
3211 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3212 return SDValue();
3213 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003214
Andrew Trickef9de2a2013-05-25 02:42:55 +00003215 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003216 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003217 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003218 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3219 return Res;
3220}
3221
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003222/// Return true if the specified node is an element that makes up a 32-bit
3223/// packed halfword byteswap.
3224/// ((x & 0x000000ff) << 8) |
3225/// ((x & 0x0000ff00) >> 8) |
3226/// ((x & 0x00ff0000) << 8) |
3227/// ((x & 0xff000000) >> 8)
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003228static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003229 if (!N.getNode()->hasOneUse())
3230 return false;
3231
3232 unsigned Opc = N.getOpcode();
3233 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3234 return false;
3235
3236 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3237 if (!N1C)
3238 return false;
3239
3240 unsigned Num;
3241 switch (N1C->getZExtValue()) {
3242 default:
3243 return false;
3244 case 0xFF: Num = 0; break;
3245 case 0xFF00: Num = 1; break;
3246 case 0xFF0000: Num = 2; break;
3247 case 0xFF000000: Num = 3; break;
3248 }
3249
3250 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3251 SDValue N0 = N.getOperand(0);
3252 if (Opc == ISD::AND) {
3253 if (Num == 0 || Num == 2) {
3254 // (x >> 8) & 0xff
3255 // (x >> 8) & 0xff0000
3256 if (N0.getOpcode() != ISD::SRL)
3257 return false;
3258 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3259 if (!C || C->getZExtValue() != 8)
3260 return false;
3261 } else {
3262 // (x << 8) & 0xff00
3263 // (x << 8) & 0xff000000
3264 if (N0.getOpcode() != ISD::SHL)
3265 return false;
3266 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3267 if (!C || C->getZExtValue() != 8)
3268 return false;
3269 }
3270 } else if (Opc == ISD::SHL) {
3271 // (x & 0xff) << 8
3272 // (x & 0xff0000) << 8
3273 if (Num != 0 && Num != 2)
3274 return false;
3275 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276 if (!C || C->getZExtValue() != 8)
3277 return false;
3278 } else { // Opc == ISD::SRL
3279 // (x & 0xff00) >> 8
3280 // (x & 0xff000000) >> 8
3281 if (Num != 1 && Num != 3)
3282 return false;
3283 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3284 if (!C || C->getZExtValue() != 8)
3285 return false;
3286 }
3287
3288 if (Parts[Num])
3289 return false;
3290
3291 Parts[Num] = N0.getOperand(0).getNode();
3292 return true;
3293}
3294
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003295/// Match a 32-bit packed halfword bswap. That is
3296/// ((x & 0x000000ff) << 8) |
3297/// ((x & 0x0000ff00) >> 8) |
3298/// ((x & 0x00ff0000) << 8) |
3299/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003300/// => (rotl (bswap x), 16)
3301SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3302 if (!LegalOperations)
3303 return SDValue();
3304
3305 EVT VT = N->getValueType(0);
3306 if (VT != MVT::i32)
3307 return SDValue();
3308 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3309 return SDValue();
3310
Evan Cheng4c0bd962011-06-21 06:01:08 +00003311 // Look for either
3312 // (or (or (and), (and)), (or (and), (and)))
3313 // (or (or (or (and), (and)), (and)), (and))
3314 if (N0.getOpcode() != ISD::OR)
3315 return SDValue();
3316 SDValue N00 = N0.getOperand(0);
3317 SDValue N01 = N0.getOperand(1);
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003318 SDNode *Parts[4] = {};
Evan Cheng4c0bd962011-06-21 06:01:08 +00003319
Evan Chengbf0baa92012-12-13 01:34:32 +00003320 if (N1.getOpcode() == ISD::OR &&
3321 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003322 // (or (or (and), (and)), (or (and), (and)))
3323 SDValue N000 = N00.getOperand(0);
3324 if (!isBSwapHWordElement(N000, Parts))
3325 return SDValue();
3326
3327 SDValue N001 = N00.getOperand(1);
3328 if (!isBSwapHWordElement(N001, Parts))
3329 return SDValue();
3330 SDValue N010 = N01.getOperand(0);
3331 if (!isBSwapHWordElement(N010, Parts))
3332 return SDValue();
3333 SDValue N011 = N01.getOperand(1);
3334 if (!isBSwapHWordElement(N011, Parts))
3335 return SDValue();
3336 } else {
3337 // (or (or (or (and), (and)), (and)), (and))
3338 if (!isBSwapHWordElement(N1, Parts))
3339 return SDValue();
3340 if (!isBSwapHWordElement(N01, Parts))
3341 return SDValue();
3342 if (N00.getOpcode() != ISD::OR)
3343 return SDValue();
3344 SDValue N000 = N00.getOperand(0);
3345 if (!isBSwapHWordElement(N000, Parts))
3346 return SDValue();
3347 SDValue N001 = N00.getOperand(1);
3348 if (!isBSwapHWordElement(N001, Parts))
3349 return SDValue();
3350 }
3351
3352 // Make sure the parts are all coming from the same node.
3353 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3354 return SDValue();
3355
Andrew Trickef9de2a2013-05-25 02:42:55 +00003356 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003357 SDValue(Parts[0],0));
3358
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003359 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003360 // do (x << 16) | (x >> 16).
3361 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3362 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003363 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003364 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003365 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3366 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3367 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3368 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003369}
3370
Matthias Braun3ecb5572015-03-06 19:49:06 +00003371/// This contains all DAGCombine rules which reduce two values combined by
3372/// an Or operation to a single value \see visitANDLike().
3373SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3374 EVT VT = N1.getValueType();
3375 // fold (or x, undef) -> -1
3376 if (!LegalOperations &&
3377 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3378 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3379 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3380 }
3381 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3382 SDValue LL, LR, RL, RR, CC0, CC1;
3383 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3384 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3385 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3386
3387 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3388 LL.getValueType().isInteger()) {
3389 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3390 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3391 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3392 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3393 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3394 LR.getValueType(), LL, RL);
3395 AddToWorklist(ORNode.getNode());
3396 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3397 }
3398 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3399 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3400 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3401 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3402 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3403 LR.getValueType(), LL, RL);
3404 AddToWorklist(ANDNode.getNode());
3405 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3406 }
3407 }
3408 // canonicalize equivalent to ll == rl
3409 if (LL == RR && LR == RL) {
3410 Op1 = ISD::getSetCCSwappedOperands(Op1);
3411 std::swap(RL, RR);
3412 }
3413 if (LL == RL && LR == RR) {
3414 bool isInteger = LL.getValueType().isInteger();
3415 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3416 if (Result != ISD::SETCC_INVALID &&
3417 (!LegalOperations ||
3418 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3419 TLI.isOperationLegal(ISD::SETCC,
3420 getSetCCResultType(N0.getValueType())))))
3421 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3422 LL, LR, Result);
3423 }
3424 }
3425
3426 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3427 if (N0.getOpcode() == ISD::AND &&
3428 N1.getOpcode() == ISD::AND &&
3429 N0.getOperand(1).getOpcode() == ISD::Constant &&
3430 N1.getOperand(1).getOpcode() == ISD::Constant &&
3431 // Don't increase # computations.
3432 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3433 // We can only do this xform if we know that bits from X that are set in C2
3434 // but not in C1 are already zero. Likewise for Y.
3435 const APInt &LHSMask =
3436 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3437 const APInt &RHSMask =
3438 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3439
3440 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3441 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3442 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3443 N0.getOperand(0), N1.getOperand(0));
3444 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3445 DAG.getConstant(LHSMask | RHSMask, VT));
3446 }
3447 }
3448
3449 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3450 if (N0.getOpcode() == ISD::AND &&
3451 N1.getOpcode() == ISD::AND &&
3452 N0.getOperand(0) == N1.getOperand(0) &&
3453 // Don't increase # computations.
3454 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3455 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3456 N0.getOperand(1), N1.getOperand(1));
3457 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3458 }
3459
3460 return SDValue();
3461}
3462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003463SDValue DAGCombiner::visitOR(SDNode *N) {
3464 SDValue N0 = N->getOperand(0);
3465 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003466 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003467
Dan Gohmana8665142007-06-25 16:23:39 +00003468 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003469 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00003470 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3471 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003472
3473 // fold (or x, 0) -> x, vector edition
3474 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3475 return N1;
3476 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3477 return N0;
3478
3479 // fold (or x, -1) -> -1, vector edition
3480 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003481 // do not return N0, because undef node may exist in N0
3482 return DAG.getConstant(
3483 APInt::getAllOnesValue(
3484 N0.getValueType().getScalarType().getSizeInBits()),
3485 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003486 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003487 // do not return N1, because undef node may exist in N1
3488 return DAG.getConstant(
3489 APInt::getAllOnesValue(
3490 N1.getValueType().getScalarType().getSizeInBits()),
3491 N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003492
3493 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3494 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3495 // Do this only if the resulting shuffle is legal.
3496 if (isa<ShuffleVectorSDNode>(N0) &&
3497 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003498 // Avoid folding a node with illegal type.
3499 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003500 N0->getOperand(1) == N1->getOperand(1) &&
3501 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3502 bool CanFold = true;
3503 unsigned NumElts = VT.getVectorNumElements();
3504 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3505 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3506 // We construct two shuffle masks:
3507 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3508 // and N1 as the second operand.
3509 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3510 // and N0 as the second operand.
3511 // We do this because OR is commutable and therefore there might be
3512 // two ways to fold this node into a shuffle.
3513 SmallVector<int,4> Mask1;
3514 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003515
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003516 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3517 int M0 = SV0->getMaskElt(i);
3518 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003519
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003520 // Both shuffle indexes are undef. Propagate Undef.
3521 if (M0 < 0 && M1 < 0) {
3522 Mask1.push_back(M0);
3523 Mask2.push_back(M0);
3524 continue;
3525 }
3526
3527 if (M0 < 0 || M1 < 0 ||
3528 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3529 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3530 CanFold = false;
3531 break;
3532 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003533
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003534 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3535 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3536 }
3537
3538 if (CanFold) {
3539 // Fold this sequence only if the resulting shuffle is 'legal'.
3540 if (TLI.isShuffleMaskLegal(Mask1, VT))
3541 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3542 N1->getOperand(0), &Mask1[0]);
3543 if (TLI.isShuffleMaskLegal(Mask2, VT))
3544 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3545 N0->getOperand(0), &Mask2[0]);
3546 }
3547 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003548 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003549
Nate Begeman21158fc2005-09-01 00:19:25 +00003550 // fold (or c1, c2) -> c1|c2
Matthias Braun00a40762015-02-24 18:52:01 +00003551 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3552 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003553 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003554 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003555 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00003556 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3557 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003558 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003559 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003560 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003561 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003562 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003563 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003564 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003565 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003566 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003567 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003568
Matthias Braun3ecb5572015-03-06 19:49:06 +00003569 if (SDValue Combined = visitORLike(N0, N1, N))
3570 return Combined;
3571
Evan Cheng4c0bd962011-06-21 06:01:08 +00003572 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3573 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003574 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003575 return BSwap;
3576 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003577 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003578 return BSwap;
3579
Nate Begeman22e251a2006-02-03 06:46:56 +00003580 // reassociate or
Simon Pilgrimd15c2802015-03-29 16:49:51 +00003581 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00003582 return ROR;
3583 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003584 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003585 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003586 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003587 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003588 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
Matthias Braunf50ab432015-01-13 22:17:46 +00003589 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3590 return DAG.getNode(
3591 ISD::AND, SDLoc(N), VT,
3592 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3593 return SDValue();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003594 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003595 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003596 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003597 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003598 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003599 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003600 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003601
Chris Lattner97614c82006-09-14 20:50:57 +00003602 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003603 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003604 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003605
Dan Gohman600f62b2010-06-24 14:30:44 +00003606 // Simplify the operands using demanded-bits information.
3607 if (!VT.isVector() &&
3608 SimplifyDemandedBits(SDValue(N, 0)))
3609 return SDValue(N, 0);
3610
Evan Chengf1005572010-04-28 07:10:39 +00003611 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003612}
3613
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003614/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003615static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003616 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003617 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003618 Mask = Op.getOperand(1);
3619 Op = Op.getOperand(0);
3620 } else {
3621 return false;
3622 }
3623 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003624
Chris Lattner97614c82006-09-14 20:50:57 +00003625 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3626 Shift = Op;
3627 return true;
3628 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003629
Scott Michelcf0da6c2009-02-17 22:15:04 +00003630 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003631}
3632
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003633// Return true if we can prove that, whenever Neg and Pos are both in the
3634// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003635// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3636//
3637// (or (shift1 X, Neg), (shift2 X, Pos))
3638//
Adam Nemetc6553a82014-03-07 23:56:24 +00003639// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3640// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3641// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003642static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003643 // If OpSize is a power of 2 then:
3644 //
3645 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3646 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3647 //
3648 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3649 // for the stronger condition:
3650 //
3651 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3652 //
3653 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3654 // we can just replace Neg with Neg' for the rest of the function.
3655 //
3656 // In other cases we check for the even stronger condition:
3657 //
3658 // Neg == OpSize - Pos [B]
3659 //
3660 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3661 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003662 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003663 // We could actually use [A] whenever OpSize is a power of 2, but the
3664 // only extra cases that it would match are those uninteresting ones
3665 // where Neg and Pos are never in range at the same time. E.g. for
3666 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3667 // as well as (sub 32, Pos), but:
3668 //
3669 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3670 //
3671 // always invokes undefined behavior for 32-bit X.
3672 //
3673 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003674 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003675 if (Neg.getOpcode() == ISD::AND &&
3676 isPowerOf2_64(OpSize) &&
3677 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3678 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3679 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003680 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003681 }
3682
Richard Sandiford0f264db2014-01-09 10:49:40 +00003683 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3684 if (Neg.getOpcode() != ISD::SUB)
3685 return 0;
3686 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3687 if (!NegC)
3688 return 0;
3689 SDValue NegOp1 = Neg.getOperand(1);
3690
Adam Nemet5117f5d2014-03-07 23:56:28 +00003691 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3692 // Pos'. The truncation is redundant for the purpose of the equality.
3693 if (MaskLoBits &&
3694 Pos.getOpcode() == ISD::AND &&
3695 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3696 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3697 Pos = Pos.getOperand(0);
3698
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003699 // The condition we need is now:
3700 //
3701 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3702 //
3703 // If NegOp1 == Pos then we need:
3704 //
3705 // OpSize & Mask == NegC & Mask
3706 //
3707 // (because "x & Mask" is a truncation and distributes through subtraction).
3708 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003709 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003710 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003711 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3712 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003713 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003714 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3715 //
3716 // which, again because "x & Mask" is a truncation, becomes:
3717 //
3718 // NegC & Mask == (OpSize - PosC) & Mask
3719 // OpSize & Mask == (NegC + PosC) & Mask
3720 else if (Pos.getOpcode() == ISD::ADD &&
3721 Pos.getOperand(0) == NegOp1 &&
3722 Pos.getOperand(1).getOpcode() == ISD::Constant)
3723 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3724 NegC->getAPIntValue());
3725 else
3726 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003727
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003728 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003729 if (MaskLoBits)
3730 // Opsize & Mask is 0 since Mask is Opsize - 1.
3731 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003732 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003733}
3734
Richard Sandiford95c864d2014-01-08 15:40:47 +00003735// A subroutine of MatchRotate used once we have found an OR of two opposite
3736// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3737// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3738// former being preferred if supported. InnerPos and InnerNeg are Pos and
3739// Neg with outer conversions stripped away.
3740SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3741 SDValue Neg, SDValue InnerPos,
3742 SDValue InnerNeg, unsigned PosOpcode,
3743 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003744 // fold (or (shl x, (*ext y)),
3745 // (srl x, (*ext (sub 32, y)))) ->
3746 // (rotl x, y) or (rotr x, (sub 32, y))
3747 //
3748 // fold (or (shl x, (*ext (sub 32, y))),
3749 // (srl x, (*ext y))) ->
3750 // (rotr x, y) or (rotl x, (sub 32, y))
3751 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003752 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003753 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3754 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3755 HasPos ? Pos : Neg).getNode();
3756 }
3757
Craig Topperc0196b12014-04-14 00:51:57 +00003758 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003759}
3760
Chris Lattner97614c82006-09-14 20:50:57 +00003761// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3762// idioms for rotate, and if the target supports rotation instructions, generate
3763// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003764SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003765 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003766 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003767 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003768
3769 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003770 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3771 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003772 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003773
Chris Lattner97614c82006-09-14 20:50:57 +00003774 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003775 SDValue LHSShift; // The shift.
3776 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003777 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003778 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003779
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003780 SDValue RHSShift; // The shift.
3781 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003782 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003783 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003784
Chris Lattner97614c82006-09-14 20:50:57 +00003785 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003786 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003787
3788 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003789 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003790
Chris Lattner97614c82006-09-14 20:50:57 +00003791 // Canonicalize shl to left side in a shl/srl pair.
3792 if (RHSShift.getOpcode() == ISD::SHL) {
3793 std::swap(LHS, RHS);
3794 std::swap(LHSShift, RHSShift);
3795 std::swap(LHSMask , RHSMask );
3796 }
3797
Duncan Sands13237ac2008-06-06 12:08:01 +00003798 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003799 SDValue LHSShiftArg = LHSShift.getOperand(0);
3800 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003801 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003802 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003803
3804 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3805 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003806 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3807 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003808 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3809 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003810 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003811 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003812
Craig Topper65161fa2012-09-29 06:54:22 +00003813 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3814 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003815
Chris Lattner97614c82006-09-14 20:50:57 +00003816 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003817 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003818 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003819
Gabor Greiff304a7a2008-08-28 21:40:38 +00003820 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003821 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3822 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003823 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003824 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003825 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3826 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003827 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003828
Bill Wendling35972a92009-01-30 21:14:50 +00003829 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003830 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003831
Gabor Greiff304a7a2008-08-28 21:40:38 +00003832 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003833 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003834
Chris Lattner97614c82006-09-14 20:50:57 +00003835 // If there is a mask here, and we have a variable shift, we can't be sure
3836 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003837 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003838 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003839
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003840 // If the shift amount is sign/zext/any-extended just peel it off.
3841 SDValue LExtOp0 = LHSShiftAmt;
3842 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003843 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3844 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3845 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3846 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3847 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3848 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3849 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3850 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003851 LExtOp0 = LHSShiftAmt.getOperand(0);
3852 RExtOp0 = RHSShiftAmt.getOperand(0);
3853 }
3854
Richard Sandiford95c864d2014-01-08 15:40:47 +00003855 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3856 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3857 if (TryL)
3858 return TryL;
3859
3860 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3861 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3862 if (TryR)
3863 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003864
Craig Topperc0196b12014-04-14 00:51:57 +00003865 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003866}
3867
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003868SDValue DAGCombiner::visitXOR(SDNode *N) {
3869 SDValue N0 = N->getOperand(0);
3870 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003871 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003872
Dan Gohmana8665142007-06-25 16:23:39 +00003873 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003874 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00003875 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3876 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003877
3878 // fold (xor x, 0) -> x, vector edition
3879 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3880 return N1;
3881 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3882 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003883 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003884
Evan Chengdf1690d2008-03-25 20:08:07 +00003885 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3886 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3887 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003888 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003889 if (N0.getOpcode() == ISD::UNDEF)
3890 return N0;
3891 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003892 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003893 // fold (xor c1, c2) -> c1^c2
Matthias Braun00a40762015-02-24 18:52:01 +00003894 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3895 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003896 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003897 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003898 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00003899 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3900 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003901 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003902 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003903 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003904 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003905 // reassociate xor
Simon Pilgrimd15c2802015-03-29 16:49:51 +00003906 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00003907 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003908
Nate Begeman21158fc2005-09-01 00:19:25 +00003909 // fold !(x cc y) -> (x !cc y)
Matthias Brauna8558ca2015-02-24 18:51:59 +00003910 SDValue LHS, RHS, CC;
Oliver Stannardd29db9b2014-11-17 10:49:31 +00003911 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003912 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003913 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3914 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003915
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003916 if (!LegalOperations ||
3917 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003918 switch (N0.getOpcode()) {
3919 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003920 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003921 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003922 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003923 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003924 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003925 N0.getOperand(3), NotCC);
3926 }
3927 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003928 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003929
Chris Lattner58c227b2007-09-10 21:39:07 +00003930 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003931 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003932 N0.getNode()->hasOneUse() &&
3933 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003934 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003935 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003936 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003937 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003938 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003939 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003940
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003941 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003942 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003943 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003944 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003945 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3946 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003947 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3948 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003949 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003950 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003951 }
3952 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003953 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003954 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003955 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003956 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003957 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3958 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003959 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3960 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003961 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003962 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003963 }
3964 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003965 // fold (xor (and x, y), y) -> (and (not x), y)
3966 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003967 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003968 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003969 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003970 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003971 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003972 }
Bill Wendling35972a92009-01-30 21:14:50 +00003973 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003974 if (N1C && N0.getOpcode() == ISD::XOR) {
3975 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3976 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3977 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003978 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003979 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003980 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003981 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003982 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003983 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003984 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003985 }
3986 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003987 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003988 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003989
David Majnemere48237d2015-03-18 00:03:36 +00003990 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
3991 // Here is a concrete example of this equivalence:
3992 // i16 x == 14
3993 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
3994 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
3995 //
3996 // =>
3997 //
3998 // i16 ~1 == 0b1111111111111110
3999 // i16 rol(~1, 14) == 0b1011111111111111
4000 //
4001 // Some additional tips to help conceptualize this transform:
4002 // - Try to see the operation as placing a single zero in a value of all ones.
4003 // - There exists no value for x which would allow the result to contain zero.
4004 // - Values of x larger than the bitwidth are undefined and do not require a
4005 // consistent result.
4006 // - Pushing the zero left requires shifting one bits in from the right.
4007 // A rotate left of ~1 is a nice way of achieving the desired result.
4008 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4009 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4010 if (N0.getOpcode() == ISD::SHL)
4011 if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4012 if (N1C->isAllOnesValue() && ShlLHS->isOne())
4013 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, DAG.getConstant(~1, VT),
4014 N0.getOperand(1));
4015
Chris Lattner8d6fc202006-05-05 05:51:50 +00004016 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4017 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004018 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004019 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00004020 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004021
Chris Lattner098c01e2006-04-08 04:15:24 +00004022 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00004023 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004024 SimplifyDemandedBits(SDValue(N, 0)))
4025 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004026
Evan Chengf1005572010-04-28 07:10:39 +00004027 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004028}
4029
Sanjay Patel50cbfc52014-08-28 16:29:51 +00004030/// Handle transforms common to the three shifts, when the shift amount is a
4031/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004032SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004033 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004034 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004035 return SDValue();
4036
Gabor Greiff304a7a2008-08-28 21:40:38 +00004037 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004038 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004039
Chris Lattner7c709a52007-12-06 07:33:36 +00004040 // We want to pull some binops through shifts, so that we have (and (shift))
4041 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4042 // thing happens with address calculations, so it's important to canonicalize
4043 // it.
4044 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00004045
Chris Lattner7c709a52007-12-06 07:33:36 +00004046 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004047 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004048 case ISD::OR:
4049 case ISD::XOR:
4050 HighBitSet = false; // We can only transform sra if the high bit is clear.
4051 break;
4052 case ISD::AND:
4053 HighBitSet = true; // We can only transform sra if the high bit is set.
4054 break;
4055 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00004056 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004057 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00004058 HighBitSet = false; // We can only transform sra if the high bit is clear.
4059 break;
4060 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004061
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004062 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00004063 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004064 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004065
4066 // FIXME: disable this unless the input to the binop is a shift by a constant.
4067 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00004068 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004069 // void foo(int *X, int i) { X[i & 1235] = 1; }
4070 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00004071 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004072 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00004073 BinOpLHSVal->getOpcode() != ISD::SRA &&
4074 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4075 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004076 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004077
Owen Anderson53aa7a92009-08-10 22:56:29 +00004078 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004079
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004080 // If this is a signed shift right, and the high bit is modified by the
4081 // logical operation, do not perform the transformation. The highBitSet
4082 // boolean indicates the value of the high bit of the constant which would
4083 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00004084 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00004085 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4086 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004087 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004088 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004089
Weiming Zhao7f6daf12014-04-30 21:07:24 +00004090 if (!TLI.isDesirableToCommuteWithShift(LHS))
4091 return SDValue();
4092
Chris Lattner7c709a52007-12-06 07:33:36 +00004093 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004094 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004095 N->getValueType(0),
4096 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004097 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00004098
4099 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004100 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004101 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004102 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00004103
4104 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004105 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00004106}
4107
Adam Nemet67483892014-03-04 23:28:31 +00004108SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4109 assert(N->getOpcode() == ISD::TRUNCATE);
4110 assert(N->getOperand(0).getOpcode() == ISD::AND);
4111
4112 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4113 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4114 SDValue N01 = N->getOperand(0).getOperand(1);
4115
Matt Arsenault985b9de2014-03-17 18:58:01 +00004116 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00004117 EVT TruncVT = N->getValueType(0);
4118 SDValue N00 = N->getOperand(0).getOperand(0);
4119 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004120 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00004121
4122 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4123 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4124 DAG.getConstant(TruncC, TruncVT));
4125 }
4126 }
4127
4128 return SDValue();
4129}
Adam Nemet7f928f12014-03-07 23:56:30 +00004130
4131SDValue DAGCombiner::visitRotate(SDNode *N) {
4132 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4133 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4134 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4135 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4136 if (NewOp1.getNode())
4137 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4138 N->getOperand(0), NewOp1);
4139 }
4140 return SDValue();
4141}
4142
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004143SDValue DAGCombiner::visitSHL(SDNode *N) {
4144 SDValue N0 = N->getOperand(0);
4145 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004146 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004147 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004148
Daniel Sandersa1840d22013-11-11 17:23:41 +00004149 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004150 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004151 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004152 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4153 return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004154
4155 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4156 // If setcc produces all-one true value then:
4157 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004158 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004159 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004160 SDValue N00 = N0->getOperand(0);
4161 SDValue N01 = N0->getOperand(1);
4162 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004163
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004164 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4165 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4166 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matthias Braunf50ab432015-01-13 22:17:46 +00004167 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004168 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4169 }
4170 } else {
4171 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004172 }
4173 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004174 }
4175
Nate Begeman21158fc2005-09-01 00:19:25 +00004176 // fold (shl c1, c2) -> c1<<c2
Matthias Braun00a40762015-02-24 18:52:01 +00004177 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004178 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004179 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004180 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004181 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004182 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004183 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004184 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004185 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004186 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004187 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004188 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004189 // fold (shl undef, x) -> 0
4190 if (N0.getOpcode() == ISD::UNDEF)
4191 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004192 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004193 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004194 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004195 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004196 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004197 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004198 N1.getOperand(0).getOpcode() == ISD::AND) {
4199 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4200 if (NewOp1.getNode())
4201 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004202 }
4203
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004204 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4205 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004206
4207 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004208 if (N1C && N0.getOpcode() == ISD::SHL) {
4209 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4210 uint64_t c1 = N0C1->getZExtValue();
4211 uint64_t c2 = N1C->getZExtValue();
4212 if (c1 + c2 >= OpSizeInBits)
4213 return DAG.getConstant(0, VT);
4214 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4215 DAG.getConstant(c1 + c2, N1.getValueType()));
4216 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004217 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004218
4219 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4220 // For this to be valid, the second form must not preserve any of the bits
4221 // that are shifted out by the inner shift in the first form. This means
4222 // the outer shift size must be >= the number of bits added by the ext.
4223 // As a corollary, we don't care what kind of ext it is.
4224 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4225 N0.getOpcode() == ISD::ANY_EXTEND ||
4226 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004227 N0.getOperand(0).getOpcode() == ISD::SHL) {
4228 SDValue N0Op0 = N0.getOperand(0);
4229 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4230 uint64_t c1 = N0Op0C1->getZExtValue();
4231 uint64_t c2 = N1C->getZExtValue();
4232 EVT InnerShiftVT = N0Op0.getValueType();
4233 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4234 if (c2 >= OpSizeInBits - InnerShiftSize) {
4235 if (c1 + c2 >= OpSizeInBits)
4236 return DAG.getConstant(0, VT);
4237 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4238 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4239 N0Op0->getOperand(0)),
4240 DAG.getConstant(c1 + c2, N1.getValueType()));
4241 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004242 }
4243 }
4244
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004245 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4246 // Only fold this if the inner zext has no other uses to avoid increasing
4247 // the total number of instructions.
4248 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004249 N0.getOperand(0).getOpcode() == ISD::SRL) {
4250 SDValue N0Op0 = N0.getOperand(0);
4251 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4252 uint64_t c1 = N0Op0C1->getZExtValue();
4253 if (c1 < VT.getScalarSizeInBits()) {
4254 uint64_t c2 = N1C->getZExtValue();
4255 if (c1 == c2) {
4256 SDValue NewOp0 = N0.getOperand(0);
4257 EVT CountVT = NewOp0.getOperand(1).getValueType();
4258 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4259 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004260 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004261 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4262 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004263 }
4264 }
4265 }
4266
Eli Friedman1877ac92011-06-09 22:14:44 +00004267 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4268 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004269 // Only fold this if the inner shift has no other uses -- if it does, folding
4270 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004271 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4272 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4273 uint64_t c1 = N0C1->getZExtValue();
4274 if (c1 < OpSizeInBits) {
4275 uint64_t c2 = N1C->getZExtValue();
4276 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4277 SDValue Shift;
4278 if (c2 > c1) {
4279 Mask = Mask.shl(c2 - c1);
4280 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4281 DAG.getConstant(c2 - c1, N1.getValueType()));
4282 } else {
4283 Mask = Mask.lshr(c1 - c2);
4284 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4285 DAG.getConstant(c1 - c2, N1.getValueType()));
4286 }
4287 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4288 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004289 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004290 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004291 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004292 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004293 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004294 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004295 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004296 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4297 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004298 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004299 HiBitsMask);
4300 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004301
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004302 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4303 // Variant of version done on multiply, except mul by a power of 2 is turned
4304 // into a shift.
4305 APInt Val;
4306 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4307 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4308 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4309 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4310 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4311 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4312 }
4313
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004314 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004315 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004316 if (NewSHL.getNode())
4317 return NewSHL;
4318 }
4319
Evan Chengf1005572010-04-28 07:10:39 +00004320 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004321}
4322
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004323SDValue DAGCombiner::visitSRA(SDNode *N) {
4324 SDValue N0 = N->getOperand(0);
4325 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004326 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004327 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004328
Daniel Sandersa1840d22013-11-11 17:23:41 +00004329 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004330 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004331 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004332 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4333 return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004334
4335 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004336 }
4337
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004338 // fold (sra c1, c2) -> (sra c1, c2)
Matthias Braun00a40762015-02-24 18:52:01 +00004339 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004340 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004341 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004342 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004343 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004344 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004345 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004346 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004347 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004348 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004349 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004350 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004351 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004352 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004353 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004354 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4355 // sext_inreg.
4356 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004357 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004358 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4359 if (VT.isVector())
4360 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4361 ExtVT, VT.getVectorNumElements());
4362 if ((!LegalOperations ||
4363 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004364 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004365 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004366 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004367
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004368 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004369 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004370 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004371 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004372 if (Sum >= OpSizeInBits)
4373 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004374 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004375 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004376 }
4377 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004378
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004379 // fold (sra (shl X, m), (sub result_size, n))
4380 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004381 // result_size - n != m.
4382 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004383 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004384 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004385 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004386 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4387 if (N01C) {
4388 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004389 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004390 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4391
4392 if (VT.isVector())
4393 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4394
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004395 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004396 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004397
Scott Michelcf0da6c2009-02-17 22:15:04 +00004398 // If the shift is not a no-op (in which case this should be just a sign
4399 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004400 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004401 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004402 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004403 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4404 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004405 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004406
Owen Andersonb2c80da2011-02-25 21:41:48 +00004407 SDValue Amt = DAG.getConstant(ShiftAmt,
4408 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004409 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004410 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004411 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004412 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004413 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004414 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004415 }
4416 }
4417 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004418
Duncan Sands3ed76882009-02-01 18:06:53 +00004419 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004420 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004421 N1.getOperand(0).getOpcode() == ISD::AND) {
4422 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4423 if (NewOp1.getNode())
4424 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004425 }
4426
Matt Arsenault985b9de2014-03-17 18:58:01 +00004427 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004428 // if c1 is equal to the number of bits the trunc removes
4429 if (N0.getOpcode() == ISD::TRUNCATE &&
4430 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4431 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4432 N0.getOperand(0).hasOneUse() &&
4433 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004434 N1C) {
4435 SDValue N0Op0 = N0.getOperand(0);
4436 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4437 unsigned LargeShiftVal = LargeShift->getZExtValue();
4438 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004439
Matt Arsenault985b9de2014-03-17 18:58:01 +00004440 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4441 SDValue Amt =
4442 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4443 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4444 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4445 N0Op0.getOperand(0), Amt);
4446 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4447 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004448 }
4449 }
4450
Scott Michelcf0da6c2009-02-17 22:15:04 +00004451 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004452 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4453 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004454
4455
Nate Begeman21158fc2005-09-01 00:19:25 +00004456 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004457 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004458 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004459
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004460 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004461 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004462 if (NewSRA.getNode())
4463 return NewSRA;
4464 }
4465
Evan Chengf1005572010-04-28 07:10:39 +00004466 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004467}
4468
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004469SDValue DAGCombiner::visitSRL(SDNode *N) {
4470 SDValue N0 = N->getOperand(0);
4471 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004472 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004473 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004474
Daniel Sandersa1840d22013-11-11 17:23:41 +00004475 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004476 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004477 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004478 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4479 return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004480
4481 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004482 }
4483
Nate Begeman21158fc2005-09-01 00:19:25 +00004484 // fold (srl c1, c2) -> c1 >>u c2
Matthias Braun00a40762015-02-24 18:52:01 +00004485 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004486 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004487 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004488 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004489 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004490 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004491 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004492 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004493 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004494 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004495 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004496 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004497 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004498 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004499 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004500 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004501
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004502 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004503 if (N1C && N0.getOpcode() == ISD::SRL) {
4504 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4505 uint64_t c1 = N01C->getZExtValue();
4506 uint64_t c2 = N1C->getZExtValue();
4507 if (c1 + c2 >= OpSizeInBits)
4508 return DAG.getConstant(0, VT);
4509 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4510 DAG.getConstant(c1 + c2, N1.getValueType()));
4511 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004512 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004513
Dale Johannesencd538af2010-12-17 21:45:49 +00004514 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004515 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4516 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004517 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004518 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004519 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4520 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004521 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4522 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004523 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004524 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004525 if (c1 + OpSizeInBits == InnerShiftSize) {
4526 if (c1 + c2 >= InnerShiftSize)
4527 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004528 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4529 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004530 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004531 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004532 }
4533 }
4534
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004535 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004536 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4537 unsigned BitSize = N0.getScalarValueSizeInBits();
4538 if (BitSize <= 64) {
4539 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4540 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4541 DAG.getConstant(~0ULL >> ShAmt, VT));
4542 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004543 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004544
Michael Liao62ebfd82013-06-21 18:45:27 +00004545 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004546 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4547 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004548 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004549 unsigned BitSize = SmallVT.getScalarSizeInBits();
4550 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004551 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004552
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004553 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004554 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004555 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004556 N0.getOperand(0),
4557 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004558 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004559 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004560 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4561 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4562 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004563 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004564 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004565
Chris Lattner2e33fb42006-10-12 20:23:19 +00004566 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4567 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004568 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004569 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004570 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004571 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004572
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004573 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004574 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004575 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004576 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004577 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004578
Chris Lattner49932492006-04-02 06:11:11 +00004579 // If any of the input bits are KnownOne, then the input couldn't be all
4580 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004581 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004582
Chris Lattner49932492006-04-02 06:11:11 +00004583 // If all of the bits input the to ctlz node are known to be zero, then
4584 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004585 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004586 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004587
Chris Lattner49932492006-04-02 06:11:11 +00004588 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004589 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004590 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004591 // could be set on input to the CTLZ node. If this bit is set, the SRL
4592 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4593 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004594 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004595 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004596
Chris Lattner49932492006-04-02 06:11:11 +00004597 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004598 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004599 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004600 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004601 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004602
Andrew Trickef9de2a2013-05-25 02:42:55 +00004603 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004604 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004605 }
4606 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004607
Duncan Sands3ed76882009-02-01 18:06:53 +00004608 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004609 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004610 N1.getOperand(0).getOpcode() == ISD::AND) {
4611 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4612 if (NewOp1.getNode())
4613 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004614 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004615
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004616 // fold operands of srl based on knowledge that the low bits are not
4617 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004618 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4619 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004620
Evan Chengb175de62009-12-18 21:31:31 +00004621 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004622 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004623 if (NewSRL.getNode())
4624 return NewSRL;
4625 }
4626
Dan Gohman600f62b2010-06-24 14:30:44 +00004627 // Attempt to convert a srl of a load into a narrower zero-extending load.
4628 SDValue NarrowLoad = ReduceLoadWidth(N);
4629 if (NarrowLoad.getNode())
4630 return NarrowLoad;
4631
Evan Chengb175de62009-12-18 21:31:31 +00004632 // Here is a common situation. We want to optimize:
4633 //
4634 // %a = ...
4635 // %b = and i32 %a, 2
4636 // %c = srl i32 %b, 1
4637 // brcond i32 %c ...
4638 //
4639 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004640 //
Evan Chengb175de62009-12-18 21:31:31 +00004641 // %a = ...
4642 // %b = and %a, 2
4643 // %c = setcc eq %b, 0
4644 // brcond %c ...
4645 //
4646 // However when after the source operand of SRL is optimized into AND, the SRL
4647 // itself may not be optimized further. Look for it and add the BRCOND into
4648 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004649 if (N->hasOneUse()) {
4650 SDNode *Use = *N->use_begin();
4651 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004652 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004653 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4654 // Also look pass the truncate.
4655 Use = *Use->use_begin();
4656 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004657 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004658 }
4659 }
Evan Chengb175de62009-12-18 21:31:31 +00004660
Evan Chengf1005572010-04-28 07:10:39 +00004661 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004662}
4663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004664SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4665 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004666 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004667
4668 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004669 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004670 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004671 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004672}
4673
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004674SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4675 SDValue N0 = N->getOperand(0);
4676 EVT VT = N->getValueType(0);
4677
4678 // fold (ctlz_zero_undef c1) -> c2
4679 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004680 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004681 return SDValue();
4682}
4683
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004684SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4685 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004686 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004687
Nate Begeman21158fc2005-09-01 00:19:25 +00004688 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004689 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004690 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004691 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004692}
4693
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004694SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4695 SDValue N0 = N->getOperand(0);
4696 EVT VT = N->getValueType(0);
4697
4698 // fold (cttz_zero_undef c1) -> c2
4699 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004700 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004701 return SDValue();
4702}
4703
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004704SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4705 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004706 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004707
Nate Begeman21158fc2005-09-01 00:19:25 +00004708 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004709 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004710 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004711 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004712}
4713
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004714
4715/// \brief Generate Min/Max node
4716static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4717 SDValue True, SDValue False,
4718 ISD::CondCode CC, const TargetLowering &TLI,
4719 SelectionDAG &DAG) {
4720 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4721 return SDValue();
4722
4723 switch (CC) {
4724 case ISD::SETOLT:
4725 case ISD::SETOLE:
4726 case ISD::SETLT:
4727 case ISD::SETLE:
4728 case ISD::SETULT:
4729 case ISD::SETULE: {
4730 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4731 if (TLI.isOperationLegal(Opcode, VT))
4732 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4733 return SDValue();
4734 }
4735 case ISD::SETOGT:
4736 case ISD::SETOGE:
4737 case ISD::SETGT:
4738 case ISD::SETGE:
4739 case ISD::SETUGT:
4740 case ISD::SETUGE: {
4741 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4742 if (TLI.isOperationLegal(Opcode, VT))
4743 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4744 return SDValue();
4745 }
4746 default:
4747 return SDValue();
4748 }
4749}
4750
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004751SDValue DAGCombiner::visitSELECT(SDNode *N) {
4752 SDValue N0 = N->getOperand(0);
4753 SDValue N1 = N->getOperand(1);
4754 SDValue N2 = N->getOperand(2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004755 EVT VT = N->getValueType(0);
4756 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004757
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004758 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004759 if (N1 == N2)
4760 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004761 // fold (select true, X, Y) -> X
Matthias Braun00a40762015-02-24 18:52:01 +00004762 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004763 if (N0C && !N0C->isNullValue())
4764 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004765 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004766 if (N0C && N0C->isNullValue())
4767 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004768 // fold (select C, 1, X) -> (or C, X)
Matthias Braun00a40762015-02-24 18:52:01 +00004769 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson9f944592009-08-11 20:47:22 +00004770 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004771 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004772 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004773 // We can't do this reliably if integer based booleans have different contents
4774 // to floating point based booleans. This is because we can't tell whether we
4775 // have an integer-based boolean or a floating-point-based boolean unless we
4776 // can find the SETCC that produced it and inspect its operands. This is
4777 // fairly easy if C is the SETCC node, but it can potentially be
4778 // undiscoverable (or not reasonably discoverable). For example, it could be
4779 // in another basic block or it could require searching a complicated
4780 // expression.
Matthias Braun00a40762015-02-24 18:52:01 +00004781 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004782 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004783 (VT0 == MVT::i1 || (VT0.isInteger() &&
4784 TLI.getBooleanContents(false, false) ==
4785 TLI.getBooleanContents(false, true) &&
4786 TLI.getBooleanContents(false, false) ==
4787 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004788 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004789 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004790 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004791 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004792 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004793 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004794 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004795 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004796 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004797 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4798 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004799 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004800 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004801 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004802 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004803 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004804 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004805 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004806 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004807 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004808 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004809 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004810 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004811 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004812 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004813 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004814 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004815 // fold (select X, X, Y) -> (or X, Y)
4816 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004817 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004818 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004819 // fold (select X, Y, X) -> (and X, Y)
4820 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004821 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004822 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004823
Chris Lattner6c14c352005-10-18 06:04:22 +00004824 // If we can fold this based on the true/false value, do so.
4825 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004826 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004827
Nate Begemanc760f802005-09-19 22:34:01 +00004828 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004829 if (N0.getOpcode() == ISD::SETCC) {
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004830 // select x, y (fcmp lt x, y) -> fminnum x, y
4831 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4832 //
4833 // This is OK if we don't care about what happens if either operand is a
4834 // NaN.
4835 //
4836
4837 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4838 // no signed zeros as well as no nans.
4839 const TargetOptions &Options = DAG.getTarget().Options;
4840 if (Options.UnsafeFPMath &&
4841 VT.isFloatingPoint() && N0.hasOneUse() &&
4842 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4843 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4844
4845 SDValue FMinMax =
4846 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4847 N1, N2, CC, TLI, DAG);
4848 if (FMinMax)
4849 return FMinMax;
4850 }
4851
Tom Stellard3787b122014-06-10 16:01:29 +00004852 if ((!LegalOperations &&
4853 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004854 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004855 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004856 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004857 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004858 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004859 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004860
Matthias Braun898d11e2015-03-06 19:49:10 +00004861 if (VT0 == MVT::i1) {
4862 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4863 // select (and Cond0, Cond1), X, Y
4864 // -> select Cond0, (select Cond1, X, Y), Y
4865 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4866 SDValue Cond0 = N0->getOperand(0);
4867 SDValue Cond1 = N0->getOperand(1);
4868 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4869 N1.getValueType(), Cond1, N1, N2);
4870 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4871 InnerSelect, N2);
4872 }
4873 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4874 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4875 SDValue Cond0 = N0->getOperand(0);
4876 SDValue Cond1 = N0->getOperand(1);
4877 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4878 N1.getValueType(), Cond1, N1, N2);
4879 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4880 InnerSelect);
4881 }
4882 }
4883
4884 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4885 if (N1->getOpcode() == ISD::SELECT) {
4886 SDValue N1_0 = N1->getOperand(0);
4887 SDValue N1_1 = N1->getOperand(1);
4888 SDValue N1_2 = N1->getOperand(2);
Matthias Brauna283cb32015-04-13 17:16:33 +00004889 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
Matthias Braun898d11e2015-03-06 19:49:10 +00004890 // Create the actual and node if we can generate good code for it.
4891 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4892 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4893 N0, N1_0);
4894 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4895 N1_1, N2);
4896 }
4897 // Otherwise see if we can optimize the "and" to a better pattern.
4898 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4899 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4900 N1_1, N2);
4901 }
4902 }
4903 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4904 if (N2->getOpcode() == ISD::SELECT) {
4905 SDValue N2_0 = N2->getOperand(0);
4906 SDValue N2_1 = N2->getOperand(1);
4907 SDValue N2_2 = N2->getOperand(2);
Matthias Brauna283cb32015-04-13 17:16:33 +00004908 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
Matthias Braun898d11e2015-03-06 19:49:10 +00004909 // Create the actual or node if we can generate good code for it.
4910 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4911 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4912 N0, N2_0);
4913 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4914 N1, N2_2);
4915 }
4916 // Otherwise see if we can optimize to a better pattern.
4917 if (SDValue Combined = visitORLike(N0, N2_0, N))
4918 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4919 N1, N2_2);
4920 }
4921 }
4922 }
4923
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004924 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004925}
4926
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004927static
4928std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4929 SDLoc DL(N);
4930 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004931 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004932
4933 // Split the inputs.
4934 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004935 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4936 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004937
4938 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4939 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4940
4941 return std::make_pair(Lo, Hi);
4942}
4943
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004944// This function assumes all the vselect's arguments are CONCAT_VECTOR
4945// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4946static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4947 SDLoc dl(N);
4948 SDValue Cond = N->getOperand(0);
4949 SDValue LHS = N->getOperand(1);
4950 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004951 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004952 int NumElems = VT.getVectorNumElements();
4953 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4954 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4955 Cond.getOpcode() == ISD::BUILD_VECTOR);
4956
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004957 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4958 // binary ones here.
4959 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4960 return SDValue();
4961
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004962 // We're sure we have an even number of elements due to the
4963 // concat_vectors we have as arguments to vselect.
4964 // Skip BV elements until we find one that's not an UNDEF
4965 // After we find an UNDEF element, keep looping until we get to half the
4966 // length of the BV and see if all the non-undef nodes are the same.
4967 ConstantSDNode *BottomHalf = nullptr;
4968 for (int i = 0; i < NumElems / 2; ++i) {
4969 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4970 continue;
4971
4972 if (BottomHalf == nullptr)
4973 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4974 else if (Cond->getOperand(i).getNode() != BottomHalf)
4975 return SDValue();
4976 }
4977
4978 // Do the same for the second half of the BuildVector
4979 ConstantSDNode *TopHalf = nullptr;
4980 for (int i = NumElems / 2; i < NumElems; ++i) {
4981 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4982 continue;
4983
4984 if (TopHalf == nullptr)
4985 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4986 else if (Cond->getOperand(i).getNode() != TopHalf)
4987 return SDValue();
4988 }
4989
4990 assert(TopHalf && BottomHalf &&
4991 "One half of the selector was all UNDEFs and the other was all the "
4992 "same value. This should have been addressed before this function.");
4993 return DAG.getNode(
4994 ISD::CONCAT_VECTORS, dl, VT,
4995 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4996 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4997}
4998
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004999SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5000
5001 if (Level >= AfterLegalizeTypes)
5002 return SDValue();
5003
5004 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5005 SDValue Mask = MST->getMask();
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005006 SDValue Data = MST->getValue();
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005007 SDLoc DL(N);
5008
5009 // If the MSTORE data type requires splitting and the mask is provided by a
5010 // SETCC, then split both nodes and its operands before legalization. This
5011 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5012 // and enables future optimizations (e.g. min/max pattern matching on X86).
5013 if (Mask.getOpcode() == ISD::SETCC) {
5014
5015 // Check if any splitting is required.
5016 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5017 TargetLowering::TypeSplitVector)
5018 return SDValue();
5019
5020 SDValue MaskLo, MaskHi, Lo, Hi;
5021 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5022
5023 EVT LoVT, HiVT;
5024 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5025
5026 SDValue Chain = MST->getChain();
5027 SDValue Ptr = MST->getBasePtr();
5028
5029 EVT MemoryVT = MST->getMemoryVT();
5030 unsigned Alignment = MST->getOriginalAlignment();
5031
5032 // if Alignment is equal to the vector size,
5033 // take the half of it for the second part
5034 unsigned SecondHalfAlignment =
5035 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5036 Alignment/2 : Alignment;
5037
5038 EVT LoMemVT, HiMemVT;
5039 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5040
5041 SDValue DataLo, DataHi;
5042 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5043
5044 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005045 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005046 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5047 Alignment, MST->getAAInfo(), MST->getRanges());
5048
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005049 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5050 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005051
5052 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5053 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5054 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5055
5056 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005057 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005058 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5059 SecondHalfAlignment, MST->getAAInfo(),
5060 MST->getRanges());
5061
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005062 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5063 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005064
5065 AddToWorklist(Lo.getNode());
5066 AddToWorklist(Hi.getNode());
5067
5068 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5069 }
5070 return SDValue();
5071}
5072
5073SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5074
5075 if (Level >= AfterLegalizeTypes)
5076 return SDValue();
5077
5078 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5079 SDValue Mask = MLD->getMask();
5080 SDLoc DL(N);
5081
5082 // If the MLOAD result requires splitting and the mask is provided by a
5083 // SETCC, then split both nodes and its operands before legalization. This
5084 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5085 // and enables future optimizations (e.g. min/max pattern matching on X86).
5086
5087 if (Mask.getOpcode() == ISD::SETCC) {
5088 EVT VT = N->getValueType(0);
5089
5090 // Check if any splitting is required.
5091 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5092 TargetLowering::TypeSplitVector)
5093 return SDValue();
5094
5095 SDValue MaskLo, MaskHi, Lo, Hi;
5096 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5097
5098 SDValue Src0 = MLD->getSrc0();
5099 SDValue Src0Lo, Src0Hi;
5100 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5101
5102 EVT LoVT, HiVT;
5103 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5104
5105 SDValue Chain = MLD->getChain();
5106 SDValue Ptr = MLD->getBasePtr();
5107 EVT MemoryVT = MLD->getMemoryVT();
5108 unsigned Alignment = MLD->getOriginalAlignment();
5109
5110 // if Alignment is equal to the vector size,
5111 // take the half of it for the second part
5112 unsigned SecondHalfAlignment =
5113 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5114 Alignment/2 : Alignment;
5115
5116 EVT LoMemVT, HiMemVT;
5117 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5118
5119 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005120 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005121 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5122 Alignment, MLD->getAAInfo(), MLD->getRanges());
5123
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005124 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5125 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005126
5127 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5128 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5129 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5130
5131 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005132 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005133 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5134 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5135
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005136 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5137 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005138
5139 AddToWorklist(Lo.getNode());
5140 AddToWorklist(Hi.getNode());
5141
5142 // Build a factor node to remember that this load is independent of the
5143 // other one.
5144 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5145 Hi.getValue(1));
5146
5147 // Legalized the chain result - switch anything that used the old chain to
5148 // use the new one.
5149 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5150
5151 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5152
5153 SDValue RetOps[] = { LoadRes, Chain };
5154 return DAG.getMergeValues(RetOps, DL);
5155 }
5156 return SDValue();
5157}
5158
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005159SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5160 SDValue N0 = N->getOperand(0);
5161 SDValue N1 = N->getOperand(1);
5162 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005163 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005164
5165 // Canonicalize integer abs.
5166 // vselect (setg[te] X, 0), X, -X ->
5167 // vselect (setgt X, -1), X, -X ->
5168 // vselect (setl[te] X, 0), -X, X ->
5169 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5170 if (N0.getOpcode() == ISD::SETCC) {
5171 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5172 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5173 bool isAbs = false;
5174 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5175
5176 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5177 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5178 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5179 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5180 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5181 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5182 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5183
5184 if (isAbs) {
5185 EVT VT = LHS.getValueType();
5186 SDValue Shift = DAG.getNode(
5187 ISD::SRA, DL, VT, LHS,
5188 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5189 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005190 AddToWorklist(Shift.getNode());
5191 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005192 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5193 }
5194 }
5195
Tom Stellard69a7b912015-04-20 19:38:27 +00005196 if (SimplifySelectOps(N, N1, N2))
5197 return SDValue(N, 0); // Don't revisit N.
5198
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005199 // If the VSELECT result requires splitting and the mask is provided by a
5200 // SETCC, then split both nodes and its operands before legalization. This
5201 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5202 // and enables future optimizations (e.g. min/max pattern matching on X86).
5203 if (N0.getOpcode() == ISD::SETCC) {
5204 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005205
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005206 // Check if any splitting is required.
5207 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5208 TargetLowering::TypeSplitVector)
5209 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005210
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005211 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005212 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5213 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5214 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005215
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005216 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5217 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005218
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005219 // Add the new VSELECT nodes to the work list in case they need to be split
5220 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005221 AddToWorklist(Lo.getNode());
5222 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005223
5224 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005225 }
5226
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00005227 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5228 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5229 return N1;
5230 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5231 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5232 return N2;
5233
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005234 // The ConvertSelectToConcatVector function is assuming both the above
5235 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5236 // and addressed.
5237 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5238 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5239 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5240 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5241 if (CV.getNode())
5242 return CV;
5243 }
5244
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005245 return SDValue();
5246}
5247
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005248SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5249 SDValue N0 = N->getOperand(0);
5250 SDValue N1 = N->getOperand(1);
5251 SDValue N2 = N->getOperand(2);
5252 SDValue N3 = N->getOperand(3);
5253 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00005254 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005255
Nate Begemanc760f802005-09-19 22:34:01 +00005256 // fold select_cc lhs, rhs, x, x, cc -> x
5257 if (N2 == N3)
5258 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005259
Chris Lattner8b68dec2006-09-20 06:19:26 +00005260 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00005261 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005262 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00005263 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005264 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00005265
Stephen Lin605207f2013-06-15 04:03:33 +00005266 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5267 if (!SCCC->isNullValue())
5268 return N2; // cond always true -> true val
5269 else
5270 return N3; // cond always false -> false val
Mehdi Amini648eff12015-01-14 05:45:24 +00005271 } else if (SCC->getOpcode() == ISD::UNDEF) {
5272 // When the condition is UNDEF, just return the first operand. This is
5273 // coherent the DAG creation, no setcc node is created in this case
5274 return N2;
5275 } else if (SCC.getOpcode() == ISD::SETCC) {
5276 // Fold to a simpler select_cc
Stephen Lin605207f2013-06-15 04:03:33 +00005277 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5278 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5279 SCC.getOperand(2));
Mehdi Amini648eff12015-01-14 05:45:24 +00005280 }
Chris Lattner8b68dec2006-09-20 06:19:26 +00005281 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005282
Chris Lattner6c14c352005-10-18 06:04:22 +00005283 // If we can fold this based on the true/false value, do so.
5284 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005285 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00005286
Nate Begemanc760f802005-09-19 22:34:01 +00005287 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00005288 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00005289}
5290
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005291SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00005292 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00005293 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005294 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00005295}
5296
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005297// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5298// dag node into a ConstantSDNode or a build_vector of constants.
5299// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005300// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005301// Vector extends are not folded if operations are legal; this is to
5302// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005303static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5304 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005305 bool LegalOperations) {
5306 unsigned Opcode = N->getOpcode();
5307 SDValue N0 = N->getOperand(0);
5308 EVT VT = N->getValueType(0);
5309
5310 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5311 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5312
5313 // fold (sext c1) -> c1
5314 // fold (zext c1) -> c1
5315 // fold (aext c1) -> c1
5316 if (isa<ConstantSDNode>(N0))
5317 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5318
5319 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5320 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5321 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005322 EVT SVT = VT.getScalarType();
5323 if (!(VT.isVector() &&
5324 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005325 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00005326 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005327
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005328 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005329 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005330 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5331 unsigned ShAmt = VTBits - EVTBits;
5332 SmallVector<SDValue, 8> Elts;
5333 unsigned NumElts = N0->getNumOperands();
5334 SDLoc DL(N);
5335
5336 for (unsigned i=0; i != NumElts; ++i) {
5337 SDValue Op = N0->getOperand(i);
5338 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005339 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005340 continue;
5341 }
5342
5343 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5344 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5345 if (Opcode == ISD::SIGN_EXTEND)
5346 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005347 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005348 else
5349 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005350 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005351 }
5352
Craig Topper48d114b2014-04-26 18:35:24 +00005353 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005354}
5355
Evan Chenge106e2f2007-10-29 19:58:20 +00005356// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00005357// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00005358// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00005359// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005360static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00005361 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00005362 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00005363 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005364 bool HasCopyToRegUses = false;
5365 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00005366 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5367 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00005368 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00005369 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00005370 if (User == N)
5371 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00005372 if (UI.getUse().getResNo() != N0.getResNo())
5373 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005374 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00005375 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005376 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5377 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5378 // Sign bits will be lost after a zext.
5379 return false;
5380 bool Add = false;
5381 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005382 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00005383 if (UseOp == N0)
5384 continue;
5385 if (!isa<ConstantSDNode>(UseOp))
5386 return false;
5387 Add = true;
5388 }
5389 if (Add)
5390 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005391 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005392 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00005393 // If truncates aren't free and there are users we can't
5394 // extend, it isn't worthwhile.
5395 if (!isTruncFree)
5396 return false;
5397 // Remember if this value is live-out.
5398 if (User->getOpcode() == ISD::CopyToReg)
5399 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00005400 }
5401
5402 if (HasCopyToRegUses) {
5403 bool BothLiveOut = false;
5404 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5405 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005406 SDUse &Use = UI.getUse();
5407 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5408 BothLiveOut = true;
5409 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00005410 }
5411 }
5412 if (BothLiveOut)
5413 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00005414 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00005415 return ExtendNodes.size();
5416 }
5417 return true;
5418}
5419
Craig Toppere0b71182013-07-13 07:43:40 +00005420void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005421 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005422 ISD::NodeType ExtType) {
5423 // Extend SetCC uses if necessary.
5424 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5425 SDNode *SetCC = SetCCs[i];
5426 SmallVector<SDValue, 4> Ops;
5427
5428 for (unsigned j = 0; j != 2; ++j) {
5429 SDValue SOp = SetCC->getOperand(j);
5430 if (SOp == Trunc)
5431 Ops.push_back(ExtLoad);
5432 else
5433 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5434 }
5435
5436 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005437 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005438 }
5439}
5440
Ahmed Bougachae892d132015-02-05 18:31:02 +00005441// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5442SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5443 SDValue N0 = N->getOperand(0);
5444 EVT DstVT = N->getValueType(0);
5445 EVT SrcVT = N0.getValueType();
5446
5447 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5448 N->getOpcode() == ISD::ZERO_EXTEND) &&
5449 "Unexpected node type (not an extend)!");
5450
5451 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5452 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5453 // (v8i32 (sext (v8i16 (load x))))
5454 // into:
5455 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5456 // (v4i32 (sextload (x + 16)))))
5457 // Where uses of the original load, i.e.:
5458 // (v8i16 (load x))
5459 // are replaced with:
5460 // (v8i16 (truncate
5461 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5462 // (v4i32 (sextload (x + 16)))))))
5463 //
5464 // This combine is only applicable to illegal, but splittable, vectors.
5465 // All legal types, and illegal non-vector types, are handled elsewhere.
5466 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5467 //
5468 if (N0->getOpcode() != ISD::LOAD)
5469 return SDValue();
5470
5471 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5472
5473 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5474 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5475 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5476 return SDValue();
5477
5478 SmallVector<SDNode *, 4> SetCCs;
5479 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5480 return SDValue();
5481
5482 ISD::LoadExtType ExtType =
5483 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5484
5485 // Try to split the vector types to get down to legal types.
5486 EVT SplitSrcVT = SrcVT;
5487 EVT SplitDstVT = DstVT;
5488 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5489 SplitSrcVT.getVectorNumElements() > 1) {
5490 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5491 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5492 }
5493
5494 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5495 return SDValue();
5496
5497 SDLoc DL(N);
5498 const unsigned NumSplits =
5499 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5500 const unsigned Stride = SplitSrcVT.getStoreSize();
5501 SmallVector<SDValue, 4> Loads;
5502 SmallVector<SDValue, 4> Chains;
5503
5504 SDValue BasePtr = LN0->getBasePtr();
5505 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5506 const unsigned Offset = Idx * Stride;
5507 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5508
5509 SDValue SplitLoad = DAG.getExtLoad(
5510 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5511 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5512 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5513 Align, LN0->getAAInfo());
5514
5515 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5516 DAG.getConstant(Stride, BasePtr.getValueType()));
5517
5518 Loads.push_back(SplitLoad.getValue(0));
5519 Chains.push_back(SplitLoad.getValue(1));
5520 }
5521
5522 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5523 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5524
5525 CombineTo(N, NewValue);
5526
5527 // Replace uses of the original load (before extension)
5528 // with a truncate of the concatenated sextloaded vectors.
5529 SDValue Trunc =
5530 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5531 CombineTo(N0.getNode(), Trunc, NewChain);
5532 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5533 (ISD::NodeType)N->getOpcode());
5534 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5535}
5536
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005537SDValue DAGCombiner::visitSIGN_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);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005544
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005545 // fold (sext (sext x)) -> (sext x)
5546 // fold (sext (aext x)) -> (sext x)
5547 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005548 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005549 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005550
Chris Lattnerfce448f2007-02-26 03:13:59 +00005551 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005552 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5553 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005554 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5555 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005556 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5557 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005558 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005559 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005560 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005561 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005563 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005564
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005565 // See if the value being truncated is already sign extended. If so, just
5566 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005567 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005568 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5569 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5570 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005571 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005572
Chris Lattnerfce448f2007-02-26 03:13:59 +00005573 if (OpBits == DestBits) {
5574 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5575 // bits, it is already ready.
5576 if (NumSignBits > DestBits-MidBits)
5577 return Op;
5578 } else if (OpBits < DestBits) {
5579 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5580 // bits, just sext from i32.
5581 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005582 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005583 } else {
5584 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5585 // bits, just truncate to i32.
5586 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005587 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005588 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005589
Chris Lattnerfce448f2007-02-26 03:13:59 +00005590 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005591 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5592 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005593 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005594 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005595 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005596 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5597 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005598 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005599 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005600 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005601
Evan Chengbce7c472005-12-14 02:19:23 +00005602 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005603 // Only generate vector extloads when 1) they're legal, and 2) they are
5604 // deemed desirable by the target.
5605 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5606 ((!LegalOperations && !VT.isVector() &&
5607 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005608 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005609 bool DoXform = true;
5610 SmallVector<SDNode*, 4> SetCCs;
5611 if (!N0.hasOneUse())
5612 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005613 if (VT.isVector())
5614 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005615 if (DoXform) {
5616 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005617 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005618 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005619 LN0->getBasePtr(), N0.getValueType(),
5620 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005621 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005622 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005623 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005624 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005625 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005626 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005627 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005628 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005629 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005630
Ahmed Bougachae892d132015-02-05 18:31:02 +00005631 // fold (sext (load x)) to multiple smaller sextloads.
5632 // Only on illegal but splittable vectors.
5633 if (SDValue ExtLoad = CombineExtLoad(N))
5634 return ExtLoad;
5635
Chris Lattner7dac1082005-12-14 19:05:06 +00005636 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5637 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005638 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5639 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005640 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005641 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005642 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005643 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005644 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005645 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005646 LN0->getBasePtr(), MemVT,
5647 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005648 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005649 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005650 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005651 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005652 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005654 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005655 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005656
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005657 // fold (sext (and/or/xor (load x), cst)) ->
5658 // (and/or/xor (sextload x), (sext cst))
5659 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5660 N0.getOpcode() == ISD::XOR) &&
5661 isa<LoadSDNode>(N0.getOperand(0)) &&
5662 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005663 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005664 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5665 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005666 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005667 bool DoXform = true;
5668 SmallVector<SDNode*, 4> SetCCs;
5669 if (!N0.hasOneUse())
5670 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5671 SetCCs, TLI);
5672 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005673 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005674 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005675 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005676 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005677 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5678 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005679 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005680 ExtLoad, DAG.getConstant(Mask, VT));
5681 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005682 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005683 N0.getOperand(0).getValueType(), ExtLoad);
5684 CombineTo(N, And);
5685 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005686 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005687 ISD::SIGN_EXTEND);
5688 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5689 }
5690 }
5691 }
5692
Chris Lattner65786b02007-04-11 05:32:27 +00005693 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005694 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005695 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005696 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005697 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005698 TLI.getBooleanContents(N0VT) ==
5699 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005700 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5701 // of the same size as the compared operands. Only optimize sext(setcc())
5702 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005703 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005704
5705 // We know that the # elements of the results is the same as the
5706 // # elements of the compare (and the # elements of the compare result
5707 // for that matter). Check to see that they are the same size. If so,
5708 // we know that the element size of the sext'd result matches the
5709 // element size of the compare operands.
5710 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005711 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005712 N0.getOperand(1),
5713 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005714
Dan Gohmane82c25e2010-04-30 17:19:19 +00005715 // If the desired elements are smaller or larger than the source
5716 // elements we can use a matching integer vector type and then
5717 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005718 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005719 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005720 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005721 N0.getOperand(0), N0.getOperand(1),
5722 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005723 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005724 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005725 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005726
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005727 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005728 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005729 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005730 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005731 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005732 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005733 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005734 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005735 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005736
5737 if (!VT.isVector()) {
5738 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5739 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5740 SDLoc DL(N);
5741 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Hal Finkel98085952014-10-06 20:19:47 +00005742 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005743 N0.getOperand(0), N0.getOperand(1), CC);
Hal Finkel98085952014-10-06 20:19:47 +00005744 return DAG.getSelect(DL, VT, SetCC,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005745 NegOne, DAG.getConstant(0, VT));
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005746 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005747 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005748 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005749
Dan Gohman3eb10f72008-04-28 16:58:24 +00005750 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005751 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005752 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005753 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005754
Evan Chengf1005572010-04-28 07:10:39 +00005755 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005756}
5757
Rafael Espindola8f62b322012-04-09 16:06:03 +00005758// isTruncateOf - If N is a truncate of some other value, return true, record
5759// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5760// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005761// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005762static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5763 APInt &KnownZero) {
5764 APInt KnownOne;
5765 if (N->getOpcode() == ISD::TRUNCATE) {
5766 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005767 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005768 return true;
5769 }
5770
5771 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5772 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5773 return false;
5774
5775 SDValue Op0 = N->getOperand(0);
5776 SDValue Op1 = N->getOperand(1);
5777 assert(Op0.getValueType() == Op1.getValueType());
5778
5779 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5780 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005781 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005782 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005783 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005784 Op = Op0;
5785 else
5786 return false;
5787
Jay Foada0653a32014-05-14 21:14:37 +00005788 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005789
5790 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5791 return false;
5792
5793 return true;
5794}
5795
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005796SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5797 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005798 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005799
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005800 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5801 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005802 return SDValue(Res, 0);
5803
Nate Begeman21158fc2005-09-01 00:19:25 +00005804 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005805 // fold (zext (aext x)) -> (zext x)
5806 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005807 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005808 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005809
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005810 // fold (zext (truncate x)) -> (zext x) or
5811 // (zext (truncate x)) -> (truncate x)
5812 // This is valid when the truncated bits of x are already zero.
5813 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005814 SDValue Op;
5815 APInt KnownZero;
5816 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5817 APInt TruncatedBits =
5818 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5819 APInt(Op.getValueSizeInBits(), 0) :
5820 APInt::getBitsSet(Op.getValueSizeInBits(),
5821 N0.getValueSizeInBits(),
5822 std::min(Op.getValueSizeInBits(),
5823 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005824 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005825 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005826 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005827 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005828 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005829
5830 return Op;
5831 }
5832 }
5833
Evan Cheng464dc9b2007-03-22 01:54:19 +00005834 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5835 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005836 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005837 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5838 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005839 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5840 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005841 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005842 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005843 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005844 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005846 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005847 }
5848
Chris Lattnera31f0a62006-09-21 06:00:20 +00005849 // fold (zext (truncate x)) -> (and x, mask)
5850 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005851 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005852
5853 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5854 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5855 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5856 if (NarrowLoad.getNode()) {
5857 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5858 if (NarrowLoad.getNode() != N0.getNode()) {
5859 CombineTo(N0.getNode(), NarrowLoad);
5860 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005861 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005862 }
5863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5864 }
5865
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005866 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005867 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005868 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005869 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005870 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005871 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005872 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005873 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005874 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005875 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005876 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005877
Dan Gohmanad3e5492009-04-08 00:15:30 +00005878 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5879 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005880 if (N0.getOpcode() == ISD::AND &&
5881 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005882 N0.getOperand(1).getOpcode() == ISD::Constant &&
5883 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5884 N0.getValueType()) ||
5885 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005886 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005887 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005888 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005889 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005890 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005891 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005892 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005893 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005894 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005895 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005896 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005897
Evan Chengbce7c472005-12-14 02:19:23 +00005898 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005899 // Only generate vector extloads when 1) they're legal, and 2) they are
5900 // deemed desirable by the target.
5901 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5902 ((!LegalOperations && !VT.isVector() &&
5903 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005904 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005905 bool DoXform = true;
5906 SmallVector<SDNode*, 4> SetCCs;
5907 if (!N0.hasOneUse())
5908 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005909 if (VT.isVector())
5910 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005911 if (DoXform) {
5912 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005913 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005914 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005915 LN0->getBasePtr(), N0.getValueType(),
5916 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005917 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005918 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005919 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005920 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005921
Andrew Trickef9de2a2013-05-25 02:42:55 +00005922 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005923 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005925 }
Evan Chengbce7c472005-12-14 02:19:23 +00005926 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005927
Ahmed Bougachae892d132015-02-05 18:31:02 +00005928 // fold (zext (load x)) to multiple smaller zextloads.
5929 // Only on illegal but splittable vectors.
5930 if (SDValue ExtLoad = CombineExtLoad(N))
5931 return ExtLoad;
5932
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005933 // fold (zext (and/or/xor (load x), cst)) ->
5934 // (and/or/xor (zextload x), (zext cst))
5935 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5936 N0.getOpcode() == ISD::XOR) &&
5937 isa<LoadSDNode>(N0.getOperand(0)) &&
5938 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005939 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005940 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5941 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005942 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005943 bool DoXform = true;
5944 SmallVector<SDNode*, 4> SetCCs;
5945 if (!N0.hasOneUse())
5946 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5947 SetCCs, TLI);
5948 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005949 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005950 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005951 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005952 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005953 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5954 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005955 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005956 ExtLoad, DAG.getConstant(Mask, VT));
5957 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005958 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005959 N0.getOperand(0).getValueType(), ExtLoad);
5960 CombineTo(N, And);
5961 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005962 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005963 ISD::ZERO_EXTEND);
5964 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5965 }
5966 }
5967 }
5968
Chris Lattner7dac1082005-12-14 19:05:06 +00005969 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5970 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005971 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5972 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005973 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005974 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005975 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005976 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005977 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005978 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005979 LN0->getBasePtr(), MemVT,
5980 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005981 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005982 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005983 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005984 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005985 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005986 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005987 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005988 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005989
Chris Lattner65786b02007-04-11 05:32:27 +00005990 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005991 if (!LegalOperations && VT.isVector() &&
5992 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005993 EVT N0VT = N0.getOperand(0).getValueType();
5994 if (getSetCCResultType(N0VT) == N0.getValueType())
5995 return SDValue();
5996
Evan Chengabd0ad52010-05-19 01:08:17 +00005997 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5998 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005999 EVT EltVT = VT.getVectorElementType();
6000 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6001 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00006002 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00006003 // We know that the # elements of the results is the same as the
6004 // # elements of the compare (and the # elements of the compare result
6005 // for that matter). Check to see that they are the same size. If so,
6006 // we know that the element size of the sext'd result matches the
6007 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006008 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6009 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00006010 N0.getOperand(1),
6011 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006012 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00006013 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00006014
6015 // If the desired elements are smaller or larger than the source
6016 // elements we can use a matching integer vector type and then
6017 // truncate/sign extend
6018 EVT MatchingElementType =
6019 EVT::getIntegerVT(*DAG.getContext(),
6020 N0VT.getScalarType().getSizeInBits());
6021 EVT MatchingVectorType =
6022 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6023 N0VT.getVectorNumElements());
6024 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006025 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00006026 N0.getOperand(1),
6027 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006028 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6029 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00006030 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00006031 }
6032
6033 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00006034 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006035 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00006036 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006037 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006038 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006039 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006040
Evan Cheng852c4862009-12-15 03:00:32 +00006041 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00006042 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00006043 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00006044 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6045 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006046 SDValue ShAmt = N0.getOperand(1);
6047 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00006048 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006049 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00006050 // If the original shl may be shifting out bits, do not perform this
6051 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00006052 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6053 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6054 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00006055 return SDValue();
6056 }
Chris Lattnere95d1952011-02-13 19:09:16 +00006057
Andrew Trickef9de2a2013-05-25 02:42:55 +00006058 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006059
6060 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00006061 if (VT.getSizeInBits() >= 256)
6062 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006063
Chris Lattnere95d1952011-02-13 19:09:16 +00006064 return DAG.getNode(N0.getOpcode(), DL, VT,
6065 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6066 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00006067 }
6068
Evan Chengf1005572010-04-28 07:10:39 +00006069 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006070}
6071
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006072SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6073 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006074 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006075
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00006076 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6077 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00006078 return SDValue(Res, 0);
6079
Chris Lattner812646a2006-05-05 05:58:59 +00006080 // fold (aext (aext x)) -> (aext x)
6081 // fold (aext (zext x)) -> (zext x)
6082 // fold (aext (sext x)) -> (sext x)
6083 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6084 N0.getOpcode() == ISD::ZERO_EXTEND ||
6085 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006086 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006087
Evan Cheng464dc9b2007-03-22 01:54:19 +00006088 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6089 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6090 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006091 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6092 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006093 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6094 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006095 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006096 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006097 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006098 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00006099 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00006100 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006101 }
6102
Chris Lattner8746e2c2006-09-20 06:29:17 +00006103 // fold (aext (truncate x))
6104 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006105 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006106 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006107 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00006108 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006109 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6110 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006111 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006112
Dan Gohmanad3e5492009-04-08 00:15:30 +00006113 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6114 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00006115 if (N0.getOpcode() == ISD::AND &&
6116 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00006117 N0.getOperand(1).getOpcode() == ISD::Constant &&
6118 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6119 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006120 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006121 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006122 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00006123 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006124 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00006125 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00006126 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00006127 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006128 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00006129 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00006130 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006131
Chris Lattner812646a2006-05-05 05:58:59 +00006132 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00006133 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00006134 // on vectors in one instruction. We only perform this transformation on
6135 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00006136 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00006137 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006138 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00006139 bool DoXform = true;
6140 SmallVector<SDNode*, 4> SetCCs;
6141 if (!N0.hasOneUse())
6142 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6143 if (DoXform) {
6144 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006145 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00006146 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006147 LN0->getBasePtr(), N0.getValueType(),
6148 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00006149 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006150 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00006151 N0.getValueType(), ExtLoad);
6152 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006153 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006154 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00006155 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6156 }
Chris Lattner812646a2006-05-05 05:58:59 +00006157 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006158
Chris Lattner812646a2006-05-05 05:58:59 +00006159 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6160 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6161 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006162 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006163 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00006164 N0.hasOneUse()) {
6165 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006166 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00006167 EVT MemVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006168 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006169 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6170 VT, LN0->getChain(), LN0->getBasePtr(),
6171 MemVT, LN0->getMemOperand());
6172 CombineTo(N, ExtLoad);
6173 CombineTo(N0.getNode(),
6174 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6175 N0.getValueType(), ExtLoad),
6176 ExtLoad.getValue(1));
6177 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6178 }
Chris Lattner812646a2006-05-05 05:58:59 +00006179 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006180
Chris Lattner65786b02007-04-11 05:32:27 +00006181 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00006182 // For vectors:
6183 // aext(setcc) -> vsetcc
6184 // aext(setcc) -> truncate(vsetcc)
6185 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00006186 // Only do this before legalize for now.
6187 if (VT.isVector() && !LegalOperations) {
6188 EVT N0VT = N0.getOperand(0).getValueType();
6189 // We know that the # elements of the results is the same as the
6190 // # elements of the compare (and the # elements of the compare result
6191 // for that matter). Check to see that they are the same size. If so,
6192 // we know that the element size of the sext'd result matches the
6193 // element size of the compare operands.
6194 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006195 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006196 N0.getOperand(1),
6197 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00006198 // If the desired elements are smaller or larger than the source
6199 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00006200 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00006201 else {
Hao Liuc636d152014-04-22 09:57:06 +00006202 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006203 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006204 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006205 N0.getOperand(1),
6206 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00006207 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00006208 }
6209 }
6210
6211 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00006212 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006213 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006214 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00006215 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006216 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00006217 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006218 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006219
Evan Chengf1005572010-04-28 07:10:39 +00006220 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00006221}
6222
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006223/// See if the specified operand can be simplified with the knowledge that only
6224/// the bits specified by Mask are used. If so, return the simpler operand,
6225/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006226SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00006227 switch (V.getOpcode()) {
6228 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00006229 case ISD::Constant: {
6230 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00006231 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00006232 const APInt &CVal = CV->getAPIntValue();
6233 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00006234 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00006235 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00006236 break;
6237 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006238 case ISD::OR:
6239 case ISD::XOR:
6240 // If the LHS or RHS don't contribute bits to the or, drop them.
6241 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6242 return V.getOperand(1);
6243 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6244 return V.getOperand(0);
6245 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00006246 case ISD::SRL:
6247 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006248 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00006249 break;
6250 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6251 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00006252 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006253
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00006254 // Watch out for shift count overflow though.
6255 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00006256 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006257 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006258 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006259 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00006260 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00006261 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006262 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006263 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00006264}
6265
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006266/// If the result of a wider load is shifted to right of N bits and then
6267/// truncated to a narrower type and where N is a multiple of number of bits of
6268/// the narrower type, transform it to a narrower load from address + N / num of
6269/// bits of new type. If the result is to be extended, also fold the extension
6270/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006271SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006272 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00006273
Evan Cheng464dc9b2007-03-22 01:54:19 +00006274 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006275 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006276 EVT VT = N->getValueType(0);
6277 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006278
Dan Gohman550c9af2008-08-14 20:04:46 +00006279 // This transformation isn't valid for vector loads.
6280 if (VT.isVector())
6281 return SDValue();
6282
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006283 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00006284 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00006285 if (Opc == ISD::SIGN_EXTEND_INREG) {
6286 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006287 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00006288 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00006289 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00006290 ExtType = ISD::ZEXTLOAD;
6291 N0 = SDValue(N, 0);
6292 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6293 if (!N01) return SDValue();
6294 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6295 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00006296 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006297 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
Richard Osborne272e0842011-01-31 17:41:44 +00006298 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006299
Owen Anderson53aa7a92009-08-10 22:56:29 +00006300 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006301
Chris Lattner9a499e92010-12-22 08:01:44 +00006302 // Do not generate loads of non-round integer types since these can
6303 // be expensive (and would be wrong if the type is not byte sized).
6304 if (!ExtVT.isRound())
6305 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006306
Evan Cheng464dc9b2007-03-22 01:54:19 +00006307 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00006308 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006309 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00006310 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006311 // Is the shift amount a multiple of size of VT?
6312 if ((ShAmt & (EVTBits-1)) == 0) {
6313 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00006314 // Is the load width a multiple of size of VT?
6315 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006316 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006317 }
Wesley Peck527da1b2010-11-23 03:31:01 +00006318
Chris Lattnercafc1e62010-12-22 08:02:57 +00006319 // At this point, we must have a load or else we can't do the transform.
6320 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006321
Chandler Carruthb27041c2012-12-11 00:36:57 +00006322 // Because a SRL must be assumed to *need* to zero-extend the high bits
6323 // (as opposed to anyext the high bits), we can't combine the zextload
6324 // lowering of SRL and an sextload.
6325 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6326 return SDValue();
6327
Chris Lattnera2050552010-10-01 05:36:09 +00006328 // If the shift amount is larger than the input type then we're not
6329 // accessing any of the loaded bytes. If the load was a zextload/extload
6330 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00006331 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00006332 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006333 }
6334 }
6335
Dan Gohman68fb0042010-11-03 01:47:46 +00006336 // If the load is shifted left (and the result isn't shifted back right),
6337 // we can fold the truncate through the shift.
6338 unsigned ShLeftAmt = 0;
6339 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00006340 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006341 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6342 ShLeftAmt = N01->getZExtValue();
6343 N0 = N0.getOperand(0);
6344 }
6345 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00006346
Chris Lattner222374d2010-12-22 07:36:50 +00006347 // If we haven't found a load, we can't narrow it. Don't transform one with
6348 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00006349 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6350 return SDValue();
6351
6352 // Don't change the width of a volatile load.
6353 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6354 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00006355 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006356
Chris Lattner9a499e92010-12-22 08:01:44 +00006357 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00006358 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00006359 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006360
Bill Schmidtd006c692013-01-14 22:04:38 +00006361 // For the transform to be legal, the load must produce only two values
6362 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00006363 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00006364 // transformation is not equivalent, and the downstream logic to replace
6365 // uses gets things wrong.
6366 if (LN0->getNumValues() > 2)
6367 return SDValue();
6368
Benjamin Kramerc7332b22013-07-06 14:05:09 +00006369 // If the load that we're shrinking is an extload and we're not just
6370 // discarding the extension we can't simply shrink the load. Bail.
6371 // TODO: It would be possible to merge the extensions in some cases.
6372 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6373 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6374 return SDValue();
6375
Matt Arsenault810cb622014-12-12 00:00:24 +00006376 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6377 return SDValue();
6378
Chris Lattner222374d2010-12-22 07:36:50 +00006379 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006380
Evan Cheng4c6f9172012-06-26 01:19:33 +00006381 if (PtrType == MVT::Untyped || PtrType.isExtended())
6382 // It's not possible to generate a constant of extended or untyped type.
6383 return SDValue();
6384
Chris Lattner222374d2010-12-22 07:36:50 +00006385 // For big endian targets, we need to adjust the offset to the pointer to
6386 // load the correct bytes.
6387 if (TLI.isBigEndian()) {
6388 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6389 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6390 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006391 }
6392
Chris Lattner222374d2010-12-22 07:36:50 +00006393 uint64_t PtrOff = ShAmt / 8;
6394 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006395 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00006396 PtrType, LN0->getBasePtr(),
6397 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006398 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00006399
Chris Lattner9a499e92010-12-22 08:01:44 +00006400 SDValue Load;
6401 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006402 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006403 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006404 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00006405 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00006406 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006407 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006408 LN0->getPointerInfo().getWithOffset(PtrOff),
6409 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00006410 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00006411
6412 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006413 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00006414 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00006415
6416 // Shift the result left, if we've swallowed a left shift.
6417 SDValue Result = Load;
6418 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00006419 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00006420 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6421 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00006422 // If the shift amount is as large as the result size (but, presumably,
6423 // no larger than the source) then the useful bits of the result are
6424 // zero; we can't simply return the shortened shift, because the result
6425 // of that operation is undefined.
6426 if (ShLeftAmt >= VT.getSizeInBits())
6427 Result = DAG.getConstant(0, VT);
6428 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006429 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00006430 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00006431 }
6432
6433 // Return the new loaded value.
6434 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006435}
6436
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006437SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6438 SDValue N0 = N->getOperand(0);
6439 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006440 EVT VT = N->getValueType(0);
6441 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00006442 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006443 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006444
Nate Begeman21158fc2005-09-01 00:19:25 +00006445 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00006446 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006447 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006448
Chris Lattner2a4d7b82006-05-06 22:43:44 +00006449 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00006450 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00006451 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006452
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006453 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6454 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006455 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006456 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006457 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00006458
Dan Gohman345d63c2008-07-31 00:50:31 +00006459 // fold (sext_in_reg (sext x)) -> (sext x)
6460 // fold (sext_in_reg (aext x)) -> (sext x)
6461 // if x is small enough.
6462 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6463 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00006464 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6465 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006466 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00006467 }
6468
Chris Lattner9ad59152007-04-17 19:03:21 +00006469 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00006470 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006471 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006472
Chris Lattner9ad59152007-04-17 19:03:21 +00006473 // fold operands of sext_in_reg based on knowledge that the top bits are not
6474 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006475 if (SimplifyDemandedBits(SDValue(N, 0)))
6476 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006477
Evan Cheng464dc9b2007-03-22 01:54:19 +00006478 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6479 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006480 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006481 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00006482 return NarrowLoad;
6483
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006484 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006485 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00006486 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6487 if (N0.getOpcode() == ISD::SRL) {
6488 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00006489 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006490 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00006491 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00006492 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00006493 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006494 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006495 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00006496 }
6497 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006498
Nate Begeman02b23c62005-10-13 03:11:28 +00006499 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00006500 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006501 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006502 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006503 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006504 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006505 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006506 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006507 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006508 LN0->getBasePtr(), EVT,
6509 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006510 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006511 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006512 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006513 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006514 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006515 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00006516 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006517 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006518 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006519 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006520 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006521 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006522 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006523 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006524 LN0->getBasePtr(), EVT,
6525 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006526 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006527 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006528 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006529 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00006530
6531 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6532 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6533 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6534 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006535 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006536 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006537 BSwap, N1);
6538 }
6539
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006540 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6541 // into a build_vector.
6542 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6543 SmallVector<SDValue, 8> Elts;
6544 unsigned NumElts = N0->getNumOperands();
6545 unsigned ShAmt = VTBits - EVTBits;
6546
6547 for (unsigned i = 0; i != NumElts; ++i) {
6548 SDValue Op = N0->getOperand(i);
6549 if (Op->getOpcode() == ISD::UNDEF) {
6550 Elts.push_back(Op);
6551 continue;
6552 }
6553
6554 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006555 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6556 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006557 Op.getValueType()));
6558 }
6559
Craig Topper48d114b2014-04-26 18:35:24 +00006560 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006561 }
6562
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006563 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006564}
6565
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006566SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6567 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006568 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006569 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006570
6571 // noop truncate
6572 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006573 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006574 // fold (truncate c1) -> c1
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00006575 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006576 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006577 // fold (truncate (truncate x)) -> (truncate x)
6578 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006579 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006580 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006581 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6582 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006583 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006584 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006585 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006586 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006587 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006588 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006589 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006590 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006591 // if the source and dest are the same type, we can drop both the extend
6592 // and the truncate.
6593 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006594 }
Evan Chengd63baea2007-03-21 20:14:05 +00006595
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006596 // Fold extract-and-trunc into a narrow extract. For example:
6597 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6598 // i32 y = TRUNCATE(i64 x)
6599 // -- becomes --
6600 // v16i8 b = BITCAST (v2i64 val)
6601 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6602 //
6603 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006604 // creates this pattern) and before operation legalization after which
6605 // we need to be more careful about the vector instructions that we generate.
6606 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006607 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006608
6609 EVT VecTy = N0.getOperand(0).getValueType();
6610 EVT ExTy = N0.getValueType();
6611 EVT TrTy = N->getValueType(0);
6612
6613 unsigned NumElem = VecTy.getVectorNumElements();
6614 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6615
6616 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6617 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6618
6619 SDValue EltNo = N0->getOperand(1);
6620 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6621 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006622 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006623 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6624
Andrew Trickef9de2a2013-05-25 02:42:55 +00006625 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006626 NVT, N0.getOperand(0));
6627
6628 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006629 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006630 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006631 }
6632 }
6633
Matt Arsenault3332b702014-07-10 18:21:04 +00006634 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6635 if (N0.getOpcode() == ISD::SELECT) {
6636 EVT SrcVT = N0.getValueType();
6637 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6638 TLI.isTruncateFree(SrcVT, VT)) {
6639 SDLoc SL(N0);
6640 SDValue Cond = N0.getOperand(0);
6641 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6642 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6643 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6644 }
6645 }
6646
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006647 // Fold a series of buildvector, bitcast, and truncate if possible.
6648 // For example fold
6649 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6650 // (2xi32 (buildvector x, y)).
6651 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6652 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6653 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6654 N0.getOperand(0).hasOneUse()) {
6655
6656 SDValue BuildVect = N0.getOperand(0);
6657 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6658 EVT TruncVecEltTy = VT.getVectorElementType();
6659
6660 // Check that the element types match.
6661 if (BuildVectEltTy == TruncVecEltTy) {
6662 // Now we only need to compute the offset of the truncated elements.
6663 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6664 unsigned TruncVecNumElts = VT.getVectorNumElements();
6665 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6666
6667 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6668 "Invalid number of elements");
6669
6670 SmallVector<SDValue, 8> Opnds;
6671 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6672 Opnds.push_back(BuildVect.getOperand(i));
6673
Craig Topper48d114b2014-04-26 18:35:24 +00006674 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006675 }
6676 }
6677
Chris Lattner5e6fe052007-10-13 06:35:54 +00006678 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006679 // only the low bits are being used.
6680 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006681 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006682 // may have different active low bits.
6683 if (!VT.isVector()) {
6684 SDValue Shorter =
6685 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6686 VT.getSizeInBits()));
6687 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006688 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006689 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006690 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006691 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006692 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6693 SDValue Reduced = ReduceLoadWidth(N);
6694 if (Reduced.getNode())
6695 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006696 // Handle the case where the load remains an extending load even
6697 // after truncation.
6698 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6699 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6700 if (!LN0->isVolatile() &&
6701 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6702 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6703 VT, LN0->getChain(), LN0->getBasePtr(),
6704 LN0->getMemoryVT(),
6705 LN0->getMemOperand());
6706 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6707 return NewLoad;
6708 }
6709 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006710 }
Michael Liao3ac82012012-10-17 23:45:54 +00006711 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6712 // where ... are all 'undef'.
6713 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6714 SmallVector<EVT, 8> VTs;
6715 SDValue V;
6716 unsigned Idx = 0;
6717 unsigned NumDefs = 0;
6718
6719 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6720 SDValue X = N0.getOperand(i);
6721 if (X.getOpcode() != ISD::UNDEF) {
6722 V = X;
6723 Idx = i;
6724 NumDefs++;
6725 }
6726 // Stop if more than one members are non-undef.
6727 if (NumDefs > 1)
6728 break;
6729 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6730 VT.getVectorElementType(),
6731 X.getValueType().getVectorNumElements()));
6732 }
6733
6734 if (NumDefs == 0)
6735 return DAG.getUNDEF(VT);
6736
6737 if (NumDefs == 1) {
6738 assert(V.getNode() && "The single defined operand is empty!");
6739 SmallVector<SDValue, 8> Opnds;
6740 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6741 if (i != Idx) {
6742 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6743 continue;
6744 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006745 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006746 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006747 Opnds.push_back(NV);
6748 }
Craig Topper48d114b2014-04-26 18:35:24 +00006749 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006750 }
6751 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006752
6753 // Simplify the operands using demanded-bits information.
6754 if (!VT.isVector() &&
6755 SimplifyDemandedBits(SDValue(N, 0)))
6756 return SDValue(N, 0);
6757
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006758 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006759}
6760
Evan Chengb980f6f2008-05-12 23:04:07 +00006761static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006762 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006763 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006764 return Elt.getNode();
6765 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006766}
6767
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006768/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006769/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006770SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006771 assert(N->getOpcode() == ISD::BUILD_PAIR);
6772
Nate Begeman624690c2009-06-05 21:37:30 +00006773 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6774 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006775 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006776 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006777 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006778 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006779
Evan Chengb980f6f2008-05-12 23:04:07 +00006780 if (ISD::isNON_EXTLoad(LD2) &&
6781 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006782 // If both are volatile this would reduce the number of volatile loads.
6783 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006784 !LD1->isVolatile() &&
6785 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006786 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006787 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006788 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006789 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006790
Duncan Sands8651e9c2008-06-13 19:07:40 +00006791 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006792 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006793 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006794 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006795 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006796 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006797
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006798 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006799}
6800
Wesley Peck527da1b2010-11-23 03:31:01 +00006801SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006802 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006803 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006804
Dan Gohmana8665142007-06-25 16:23:39 +00006805 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6806 // Only do this before legalize, since afterward the target may be depending
6807 // on the bitconvert.
6808 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006809 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006810 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006811 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006812 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006813
Owen Anderson53aa7a92009-08-10 22:56:29 +00006814 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006815 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006816 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006817 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006818 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006819 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006820
Dan Gohman921ddd62008-09-05 01:58:21 +00006821 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006822 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Chandler Carruthb65d61a2015-02-10 02:25:56 +00006823 // If we can't allow illegal operations, we need to check that this is just
6824 // a fp -> int or int -> conversion and that the resulting operation will
6825 // be legal.
6826 if (!LegalOperations ||
6827 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6828 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6829 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6830 TLI.isOperationLegal(ISD::Constant, VT)))
6831 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Chris Lattnera1874602005-12-23 05:30:37 +00006832 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006833
Bill Wendling4e0a6152009-01-30 22:44:24 +00006834 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006835 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006836 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006837 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006838
Chris Lattner54560f62005-12-23 05:44:41 +00006839 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006840 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006841 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006842 // Do not change the width of a volatile load.
6843 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006844 // Do not remove the cast if the types differ in endian layout.
6845 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6846 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006847 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6848 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006849 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006850 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006851 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006852 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006853
Evan Chenga4cf58a2007-05-07 21:27:48 +00006854 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006855 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006856 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006857 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006858 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006859 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006860 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006861 return Load;
6862 }
Chris Lattner54560f62005-12-23 05:44:41 +00006863 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006864
Bill Wendling4e0a6152009-01-30 22:44:24 +00006865 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6866 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006867 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006868 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6869 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006870 N0.getNode()->hasOneUse() && VT.isInteger() &&
6871 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006872 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006873 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006874 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006875
Duncan Sands13237ac2008-06-06 12:08:01 +00006876 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006877 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006878 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006879 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006880 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006881 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006882 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006883 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006884
Bill Wendling4e0a6152009-01-30 22:44:24 +00006885 // fold (bitconvert (fcopysign cst, x)) ->
6886 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6887 // Note that we don't handle (copysign x, cst) because this can always be
6888 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006889 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006890 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006891 VT.isInteger() && !VT.isVector()) {
6892 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006893 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006894 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006895 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006896 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006897 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006898
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006899 // If X has a different width than the result/lhs, sext it or truncate it.
6900 unsigned VTWidth = VT.getSizeInBits();
6901 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006902 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006903 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006904 } else if (OrigXWidth > VTWidth) {
6905 // To get the sign bit in the right place, we have to shift it right
6906 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006907 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006908 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006909 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006910 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006911 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006912 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006913 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006914
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006915 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006916 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006917 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006918 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006919
Andrew Trickef9de2a2013-05-25 02:42:55 +00006920 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006921 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006922 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006923 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006924 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006925
Andrew Trickef9de2a2013-05-25 02:42:55 +00006926 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006927 }
Chris Lattner888560d2008-01-27 17:42:27 +00006928 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006929
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006930 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006931 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006932 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6933 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006934 return CombineLD;
6935 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006936
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006937 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006938}
6939
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006940SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006941 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006942 return CombineConsecutiveLoads(N, VT);
6943}
6944
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006945/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6946/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006947SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006948ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006949 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006950
Chris Lattnere4e64b62006-04-02 02:53:43 +00006951 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006952 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006953
Duncan Sands13237ac2008-06-06 12:08:01 +00006954 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6955 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006956
Chris Lattnere4e64b62006-04-02 02:53:43 +00006957 // If this is a conversion of N elements of one type to N elements of another
6958 // type, convert each element. This handles FP<->INT cases.
6959 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006960 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6961 BV->getValueType(0).getVectorNumElements());
6962
6963 // Due to the FP element handling below calling this routine recursively,
6964 // we can end up with a scalar-to-vector node here.
6965 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006966 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6967 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006968 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006969
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006970 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006971 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006972 SDValue Op = BV->getOperand(i);
6973 // If the vector element type is not legal, the BUILD_VECTOR operands
6974 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006975 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006976 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6977 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006978 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006979 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006980 }
Craig Topper48d114b2014-04-26 18:35:24 +00006981 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006982 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006983
Chris Lattnere4e64b62006-04-02 02:53:43 +00006984 // Otherwise, we're growing or shrinking the elements. To avoid having to
6985 // handle annoying details of growing/shrinking FP values, we convert them to
6986 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006987 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006988 // Convert the input float vector to a int vector where the elements are the
6989 // same sizes.
Owen Anderson117c9e82009-08-12 00:36:31 +00006990 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006991 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006992 SrcEltVT = IntVT;
6993 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006994
Chris Lattnere4e64b62006-04-02 02:53:43 +00006995 // Now we know the input is an integer vector. If the output is a FP type,
6996 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006997 if (DstEltVT.isFloatingPoint()) {
Owen Anderson117c9e82009-08-12 00:36:31 +00006998 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006999 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007000
Chris Lattnere4e64b62006-04-02 02:53:43 +00007001 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00007002 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007003 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007004
Chris Lattnere4e64b62006-04-02 02:53:43 +00007005 // Okay, we know the src/dst types are both integers of differing types.
7006 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00007007 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00007008 if (SrcBitSize < DstBitSize) {
7009 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007010
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007011 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00007012 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00007013 i += NumInputsPerOutput) {
7014 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00007015 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007016 bool EltIsUndef = true;
7017 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7018 // Shift the previously computed bits over.
7019 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007020 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007021 if (Op.getOpcode() == ISD::UNDEF) continue;
7022 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007023
Jay Foad583abbc2010-12-07 08:25:19 +00007024 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00007025 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007026 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007027
Chris Lattnere4e64b62006-04-02 02:53:43 +00007028 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00007029 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007030 else
7031 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7032 }
7033
Owen Anderson117c9e82009-08-12 00:36:31 +00007034 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00007035 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007036 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007037
Chris Lattnere4e64b62006-04-02 02:53:43 +00007038 // Finally, this must be the case where we are shrinking elements: each input
7039 // turns into multiple outputs.
7040 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00007041 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7042 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007043 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007044
Dan Gohmana8665142007-06-25 16:23:39 +00007045 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007046 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00007047 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007048 continue;
7049 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007050
Jay Foad583abbc2010-12-07 08:25:19 +00007051 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7052 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007053
Chris Lattnere4e64b62006-04-02 02:53:43 +00007054 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00007055 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007056 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Dan Gohmane1c4f992008-03-03 23:51:38 +00007057 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007058 }
7059
7060 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00007061 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00007062 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7063 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007064
Craig Topper48d114b2014-04-26 18:35:24 +00007065 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007066}
7067
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007068/// Try to perform FMA combining on a given FADD node.
7069SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7070
7071
7072
7073
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007074 SDValue N0 = N->getOperand(0);
7075 SDValue N1 = N->getOperand(1);
7076 EVT VT = N->getValueType(0);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007077 SDLoc SL(N);
7078
7079 const TargetOptions &Options = DAG.getTarget().Options;
7080 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7081 Options.UnsafeFPMath);
7082
7083 // Floating-point multiply-add with intermediate rounding.
7084 bool HasFMAD = (LegalOperations &&
7085 TLI.isOperationLegal(ISD::FMAD, VT));
7086
7087 // Floating-point multiply-add without intermediate rounding.
7088 bool HasFMA = ((!LegalOperations ||
7089 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7090 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7091 UnsafeFPMath);
7092
7093 // No valid opcode, do not combine.
7094 if (!HasFMAD && !HasFMA)
7095 return SDValue();
7096
7097 // Always prefer FMAD to FMA for precision.
7098 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7099 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7100 bool LookThroughFPExt = TLI.isFPExtFree(VT);
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007101
7102 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7103 if (N0.getOpcode() == ISD::FMUL &&
7104 (Aggressive || N0->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007105 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007106 N0.getOperand(0), N0.getOperand(1), N1);
7107 }
7108
7109 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7110 // Note: Commutes FADD operands.
7111 if (N1.getOpcode() == ISD::FMUL &&
7112 (Aggressive || N1->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007113 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007114 N1.getOperand(0), N1.getOperand(1), N0);
7115 }
7116
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007117 // Look through FP_EXTEND nodes to do more combining.
7118 if (UnsafeFPMath && LookThroughFPExt) {
7119 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7120 if (N0.getOpcode() == ISD::FP_EXTEND) {
7121 SDValue N00 = N0.getOperand(0);
7122 if (N00.getOpcode() == ISD::FMUL)
7123 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7124 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7125 N00.getOperand(0)),
7126 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7127 N00.getOperand(1)), N1);
7128 }
7129
7130 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7131 // Note: Commutes FADD operands.
7132 if (N1.getOpcode() == ISD::FP_EXTEND) {
7133 SDValue N10 = N1.getOperand(0);
7134 if (N10.getOpcode() == ISD::FMUL)
7135 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7136 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7137 N10.getOperand(0)),
7138 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7139 N10.getOperand(1)), N0);
7140 }
7141 }
7142
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007143 // More folding opportunities when target permits.
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007144 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007145 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007146 if (N0.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007147 N0.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007148 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007149 N0.getOperand(0), N0.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007150 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007151 N0.getOperand(2).getOperand(0),
7152 N0.getOperand(2).getOperand(1),
7153 N1));
7154 }
7155
7156 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007157 if (N1->getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007158 N1.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007159 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007160 N1.getOperand(0), N1.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007161 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007162 N1.getOperand(2).getOperand(0),
7163 N1.getOperand(2).getOperand(1),
7164 N0));
7165 }
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007166
7167 if (LookThroughFPExt) {
7168 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7169 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7170 auto FoldFAddFMAFPExtFMul = [&] (
7171 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7172 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7173 DAG.getNode(PreferredFusedOpcode, SL, VT,
7174 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7175 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7176 Z));
7177 };
7178 if (N0.getOpcode() == PreferredFusedOpcode) {
7179 SDValue N02 = N0.getOperand(2);
7180 if (N02.getOpcode() == ISD::FP_EXTEND) {
7181 SDValue N020 = N02.getOperand(0);
7182 if (N020.getOpcode() == ISD::FMUL)
7183 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7184 N020.getOperand(0), N020.getOperand(1),
7185 N1);
7186 }
7187 }
7188
7189 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7190 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7191 // FIXME: This turns two single-precision and one double-precision
7192 // operation into two double-precision operations, which might not be
7193 // interesting for all targets, especially GPUs.
7194 auto FoldFAddFPExtFMAFMul = [&] (
7195 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7196 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7197 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7198 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7199 DAG.getNode(PreferredFusedOpcode, SL, VT,
7200 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7201 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7202 Z));
7203 };
7204 if (N0.getOpcode() == ISD::FP_EXTEND) {
7205 SDValue N00 = N0.getOperand(0);
7206 if (N00.getOpcode() == PreferredFusedOpcode) {
7207 SDValue N002 = N00.getOperand(2);
7208 if (N002.getOpcode() == ISD::FMUL)
7209 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7210 N002.getOperand(0), N002.getOperand(1),
7211 N1);
7212 }
7213 }
7214
7215 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7216 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7217 if (N1.getOpcode() == PreferredFusedOpcode) {
7218 SDValue N12 = N1.getOperand(2);
7219 if (N12.getOpcode() == ISD::FP_EXTEND) {
7220 SDValue N120 = N12.getOperand(0);
7221 if (N120.getOpcode() == ISD::FMUL)
7222 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7223 N120.getOperand(0), N120.getOperand(1),
7224 N0);
7225 }
7226 }
7227
7228 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7229 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7230 // FIXME: This turns two single-precision and one double-precision
7231 // operation into two double-precision operations, which might not be
7232 // interesting for all targets, especially GPUs.
7233 if (N1.getOpcode() == ISD::FP_EXTEND) {
7234 SDValue N10 = N1.getOperand(0);
7235 if (N10.getOpcode() == PreferredFusedOpcode) {
7236 SDValue N102 = N10.getOperand(2);
7237 if (N102.getOpcode() == ISD::FMUL)
7238 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7239 N102.getOperand(0), N102.getOperand(1),
7240 N0);
7241 }
7242 }
7243 }
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007244 }
7245
7246 return SDValue();
7247}
7248
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007249/// Try to perform FMA combining on a given FSUB node.
7250SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7251
7252
7253
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007254 SDValue N0 = N->getOperand(0);
7255 SDValue N1 = N->getOperand(1);
7256 EVT VT = N->getValueType(0);
Rafael Espindola1c842712015-04-09 18:29:32 +00007257
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007258 SDLoc SL(N);
7259
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007260 const TargetOptions &Options = DAG.getTarget().Options;
7261 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7262 Options.UnsafeFPMath);
7263
7264 // Floating-point multiply-add with intermediate rounding.
7265 bool HasFMAD = (LegalOperations &&
7266 TLI.isOperationLegal(ISD::FMAD, VT));
7267
7268 // Floating-point multiply-add without intermediate rounding.
7269 bool HasFMA = ((!LegalOperations ||
7270 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7271 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7272 UnsafeFPMath);
7273
7274 // No valid opcode, do not combine.
7275 if (!HasFMAD && !HasFMA)
7276 return SDValue();
7277
7278 // Always prefer FMAD to FMA for precision.
7279 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7280 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7281 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7282
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007283 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7284 if (N0.getOpcode() == ISD::FMUL &&
7285 (Aggressive || N0->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007286 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007287 N0.getOperand(0), N0.getOperand(1),
7288 DAG.getNode(ISD::FNEG, SL, VT, N1));
7289 }
7290
7291 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7292 // Note: Commutes FSUB operands.
7293 if (N1.getOpcode() == ISD::FMUL &&
7294 (Aggressive || N1->hasOneUse()))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007295 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007296 DAG.getNode(ISD::FNEG, SL, VT,
7297 N1.getOperand(0)),
7298 N1.getOperand(1), N0);
7299
7300 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7301 if (N0.getOpcode() == ISD::FNEG &&
7302 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7303 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7304 SDValue N00 = N0.getOperand(0).getOperand(0);
7305 SDValue N01 = N0.getOperand(0).getOperand(1);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007306 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007307 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7308 DAG.getNode(ISD::FNEG, SL, VT, N1));
7309 }
7310
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007311 // Look through FP_EXTEND nodes to do more combining.
7312 if (UnsafeFPMath && LookThroughFPExt) {
7313 // fold (fsub (fpext (fmul x, y)), z)
7314 // -> (fma (fpext x), (fpext y), (fneg z))
7315 if (N0.getOpcode() == ISD::FP_EXTEND) {
7316 SDValue N00 = N0.getOperand(0);
7317 if (N00.getOpcode() == ISD::FMUL)
7318 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7319 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7320 N00.getOperand(0)),
7321 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7322 N00.getOperand(1)),
7323 DAG.getNode(ISD::FNEG, SL, VT, N1));
7324 }
7325
7326 // fold (fsub x, (fpext (fmul y, z)))
7327 // -> (fma (fneg (fpext y)), (fpext z), x)
7328 // Note: Commutes FSUB operands.
7329 if (N1.getOpcode() == ISD::FP_EXTEND) {
7330 SDValue N10 = N1.getOperand(0);
7331 if (N10.getOpcode() == ISD::FMUL)
7332 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7333 DAG.getNode(ISD::FNEG, SL, VT,
7334 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7335 N10.getOperand(0))),
7336 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7337 N10.getOperand(1)),
7338 N0);
7339 }
7340
7341 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7342 // -> (fneg (fma (fpext x), (fpext y), z))
7343 // Note: This could be removed with appropriate canonicalization of the
7344 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7345 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7346 // from implementing the canonicalization in visitFSUB.
7347 if (N0.getOpcode() == ISD::FP_EXTEND) {
7348 SDValue N00 = N0.getOperand(0);
7349 if (N00.getOpcode() == ISD::FNEG) {
7350 SDValue N000 = N00.getOperand(0);
7351 if (N000.getOpcode() == ISD::FMUL) {
7352 return DAG.getNode(ISD::FNEG, SL, VT,
7353 DAG.getNode(PreferredFusedOpcode, SL, VT,
7354 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7355 N000.getOperand(0)),
7356 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7357 N000.getOperand(1)),
7358 N1));
7359 }
7360 }
7361 }
7362
7363 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7364 // -> (fneg (fma (fpext x)), (fpext y), z)
7365 // Note: This could be removed with appropriate canonicalization of the
7366 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7367 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7368 // from implementing the canonicalization in visitFSUB.
7369 if (N0.getOpcode() == ISD::FNEG) {
7370 SDValue N00 = N0.getOperand(0);
7371 if (N00.getOpcode() == ISD::FP_EXTEND) {
7372 SDValue N000 = N00.getOperand(0);
7373 if (N000.getOpcode() == ISD::FMUL) {
7374 return DAG.getNode(ISD::FNEG, SL, VT,
7375 DAG.getNode(PreferredFusedOpcode, SL, VT,
7376 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7377 N000.getOperand(0)),
7378 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7379 N000.getOperand(1)),
7380 N1));
7381 }
7382 }
7383 }
7384
7385 }
7386
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007387 // More folding opportunities when target permits.
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007388 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007389 // fold (fsub (fma x, y, (fmul u, v)), z)
7390 // -> (fma x, y (fma u, v, (fneg z)))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007391 if (N0.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007392 N0.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007393 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007394 N0.getOperand(0), N0.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007395 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007396 N0.getOperand(2).getOperand(0),
7397 N0.getOperand(2).getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007398 DAG.getNode(ISD::FNEG, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007399 N1)));
7400 }
7401
7402 // fold (fsub x, (fma y, z, (fmul u, v)))
7403 // -> (fma (fneg y), z, (fma (fneg u), v, x))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007404 if (N1.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007405 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7406 SDValue N20 = N1.getOperand(2).getOperand(0);
7407 SDValue N21 = N1.getOperand(2).getOperand(1);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007408 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7409 DAG.getNode(ISD::FNEG, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007410 N1.getOperand(0)),
7411 N1.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007412 DAG.getNode(PreferredFusedOpcode, SL, VT,
7413 DAG.getNode(ISD::FNEG, SL, VT, N20),
7414
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007415 N21, N0));
7416 }
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007417
7418 if (LookThroughFPExt) {
7419 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7420 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7421 if (N0.getOpcode() == PreferredFusedOpcode) {
7422 SDValue N02 = N0.getOperand(2);
7423 if (N02.getOpcode() == ISD::FP_EXTEND) {
7424 SDValue N020 = N02.getOperand(0);
7425 if (N020.getOpcode() == ISD::FMUL)
7426 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7427 N0.getOperand(0), N0.getOperand(1),
7428 DAG.getNode(PreferredFusedOpcode, SL, VT,
7429 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7430 N020.getOperand(0)),
7431 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7432 N020.getOperand(1)),
7433 DAG.getNode(ISD::FNEG, SL, VT,
7434 N1)));
7435 }
7436 }
7437
7438 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7439 // -> (fma (fpext x), (fpext y),
7440 // (fma (fpext u), (fpext v), (fneg z)))
7441 // FIXME: This turns two single-precision and one double-precision
7442 // operation into two double-precision operations, which might not be
7443 // interesting for all targets, especially GPUs.
7444 if (N0.getOpcode() == ISD::FP_EXTEND) {
7445 SDValue N00 = N0.getOperand(0);
7446 if (N00.getOpcode() == PreferredFusedOpcode) {
7447 SDValue N002 = N00.getOperand(2);
7448 if (N002.getOpcode() == ISD::FMUL)
7449 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7450 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7451 N00.getOperand(0)),
7452 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7453 N00.getOperand(1)),
7454 DAG.getNode(PreferredFusedOpcode, SL, VT,
7455 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7456 N002.getOperand(0)),
7457 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7458 N002.getOperand(1)),
7459 DAG.getNode(ISD::FNEG, SL, VT,
7460 N1)));
7461 }
7462 }
7463
7464 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7465 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7466 if (N1.getOpcode() == PreferredFusedOpcode &&
7467 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7468 SDValue N120 = N1.getOperand(2).getOperand(0);
7469 if (N120.getOpcode() == ISD::FMUL) {
7470 SDValue N1200 = N120.getOperand(0);
7471 SDValue N1201 = N120.getOperand(1);
7472 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7473 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7474 N1.getOperand(1),
7475 DAG.getNode(PreferredFusedOpcode, SL, VT,
7476 DAG.getNode(ISD::FNEG, SL, VT,
7477 DAG.getNode(ISD::FP_EXTEND, SL,
7478 VT, N1200)),
7479 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7480 N1201),
7481 N0));
7482 }
7483 }
7484
7485 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7486 // -> (fma (fneg (fpext y)), (fpext z),
7487 // (fma (fneg (fpext u)), (fpext v), x))
7488 // FIXME: This turns two single-precision and one double-precision
7489 // operation into two double-precision operations, which might not be
7490 // interesting for all targets, especially GPUs.
7491 if (N1.getOpcode() == ISD::FP_EXTEND &&
7492 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7493 SDValue N100 = N1.getOperand(0).getOperand(0);
7494 SDValue N101 = N1.getOperand(0).getOperand(1);
7495 SDValue N102 = N1.getOperand(0).getOperand(2);
7496 if (N102.getOpcode() == ISD::FMUL) {
7497 SDValue N1020 = N102.getOperand(0);
7498 SDValue N1021 = N102.getOperand(1);
7499 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7500 DAG.getNode(ISD::FNEG, SL, VT,
7501 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7502 N100)),
7503 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7504 DAG.getNode(PreferredFusedOpcode, SL, VT,
7505 DAG.getNode(ISD::FNEG, SL, VT,
7506 DAG.getNode(ISD::FP_EXTEND, SL,
7507 VT, N1020)),
7508 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7509 N1021),
7510 N0));
7511 }
7512 }
7513 }
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007514 }
7515
7516 return SDValue();
7517}
7518
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007519SDValue DAGCombiner::visitFADD(SDNode *N) {
7520 SDValue N0 = N->getOperand(0);
7521 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00007522 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7523 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007524 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007525 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007526
Dan Gohmana8665142007-06-25 16:23:39 +00007527 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007528 if (VT.isVector())
7529 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7530 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007531
Lang Hamesa33db652012-06-14 20:37:15 +00007532 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007533 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007534 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007535
Nate Begeman418c6e42005-10-18 00:28:13 +00007536 // canonicalize constant to RHS
7537 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007538 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007539
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007540 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007541 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007542 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007543 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007544 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007545
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007546 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007547 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007548 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007549 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007550 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007551
Sanjay Patel8170dea2014-09-08 17:32:19 +00007552 // If 'unsafe math' is enabled, fold lots of things.
7553 if (Options.UnsafeFPMath) {
7554 // No FP constant should be created after legalization as Instruction
7555 // Selection pass has a hard time dealing with FP constants.
7556 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007557
Sanjay Patel8170dea2014-09-08 17:32:19 +00007558 // fold (fadd A, 0) -> A
7559 if (N1CFP && N1CFP->getValueAPF().isZero())
7560 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007561
Sanjay Patel8170dea2014-09-08 17:32:19 +00007562 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7563 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7564 isa<ConstantFPSDNode>(N0.getOperand(1)))
7565 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7566 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7567 N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007568
Sanjay Patel8170dea2014-09-08 17:32:19 +00007569 // If allowed, fold (fadd (fneg x), x) -> 0.0
7570 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7571 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007572
Sanjay Patel8170dea2014-09-08 17:32:19 +00007573 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7574 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7575 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007576
Sanjay Patel8170dea2014-09-08 17:32:19 +00007577 // We can fold chains of FADD's of the same value into multiplications.
7578 // This transform is not safe in general because we are reducing the number
7579 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00007580 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7581 if (N0.getOpcode() == ISD::FMUL) {
7582 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7583 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007584
Sanjay Patel8170dea2014-09-08 17:32:19 +00007585 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7586 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7587 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7588 SDValue(CFP01, 0),
7589 DAG.getConstantFP(1.0, VT));
7590 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7591 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007592
Sanjay Patel8170dea2014-09-08 17:32:19 +00007593 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7594 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7595 N1.getOperand(0) == N1.getOperand(1) &&
7596 N0.getOperand(0) == N1.getOperand(0)) {
7597 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7598 SDValue(CFP01, 0),
7599 DAG.getConstantFP(2.0, VT));
7600 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7601 N0.getOperand(0), NewCFP);
7602 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007603 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007604
Sanjay Patel8170dea2014-09-08 17:32:19 +00007605 if (N1.getOpcode() == ISD::FMUL) {
7606 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7607 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007608
Sanjay Patel8170dea2014-09-08 17:32:19 +00007609 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7610 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7611 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7612 SDValue(CFP11, 0),
7613 DAG.getConstantFP(1.0, VT));
7614 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7615 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007616
Sanjay Patel8170dea2014-09-08 17:32:19 +00007617 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7618 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7619 N0.getOperand(0) == N0.getOperand(1) &&
7620 N1.getOperand(0) == N0.getOperand(0)) {
7621 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7622 SDValue(CFP11, 0),
7623 DAG.getConstantFP(2.0, VT));
7624 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7625 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007626 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007627
Sanjay Patel8170dea2014-09-08 17:32:19 +00007628 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7629 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7630 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7631 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7632 (N0.getOperand(0) == N1))
7633 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7634 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007635 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007636
Sanjay Patel8170dea2014-09-08 17:32:19 +00007637 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7638 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7639 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7640 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7641 N1.getOperand(0) == N0)
7642 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7643 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007644 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007645
Sanjay Patel8170dea2014-09-08 17:32:19 +00007646 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7647 if (AllowNewConst &&
7648 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00007649 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007650 N1.getOperand(0) == N1.getOperand(1) &&
7651 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007652 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00007653 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007654 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00007655 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007656
Lang Hames39fb1d02012-06-19 22:51:23 +00007657 // FADD -> FMA combines:
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007658 SDValue Fused = visitFADDForFMACombine(N);
7659 if (Fused) {
7660 AddToWorklist(Fused.getNode());
7661 return Fused;
Olivier Sallenave04515322015-01-07 20:54:17 +00007662 }
7663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007664 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007665}
7666
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007667SDValue DAGCombiner::visitFSUB(SDNode *N) {
7668 SDValue N0 = N->getOperand(0);
7669 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00007670 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7671 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007672 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007673 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007674 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007675
Dan Gohmana8665142007-06-25 16:23:39 +00007676 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007677 if (VT.isVector())
7678 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7679 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007680
Nate Begeman418c6e42005-10-18 00:28:13 +00007681 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007682 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007683 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00007684
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007685 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007686 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007687 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007688 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007689
Sanjay Patelae402a32014-08-27 20:57:52 +00007690 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007691 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00007692 // (fsub A, 0) -> A
7693 if (N1CFP && N1CFP->getValueAPF().isZero())
7694 return N0;
7695
7696 // (fsub 0, B) -> -B
7697 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00007698 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00007699 return GetNegatedExpression(N1, DAG, LegalOperations);
7700 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7701 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7702 }
7703
7704 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00007705 if (N0 == N1)
7706 return DAG.getConstantFP(0.0f, VT);
7707
Sanjay Patelae402a32014-08-27 20:57:52 +00007708 // (fsub x, (fadd x, y)) -> (fneg y)
7709 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00007710 if (N1.getOpcode() == ISD::FADD) {
7711 SDValue N10 = N1->getOperand(0);
7712 SDValue N11 = N1->getOperand(1);
7713
Sanjay Patel78614bf2014-08-28 15:53:16 +00007714 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007715 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00007716
Sanjay Patel78614bf2014-08-28 15:53:16 +00007717 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007718 return GetNegatedExpression(N10, DAG, LegalOperations);
7719 }
7720 }
7721
Lang Hames39fb1d02012-06-19 22:51:23 +00007722 // FSUB -> FMA combines:
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007723 SDValue Fused = visitFSUBForFMACombine(N);
7724 if (Fused) {
7725 AddToWorklist(Fused.getNode());
7726 return Fused;
Lang Hames39fb1d02012-06-19 22:51:23 +00007727 }
7728
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007729 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007730}
7731
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007732SDValue DAGCombiner::visitFMUL(SDNode *N) {
7733 SDValue N0 = N->getOperand(0);
7734 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00007735 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7736 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007737 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007738 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007739
Dan Gohmana8665142007-06-25 16:23:39 +00007740 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007741 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007742 // This just handles C1 * C2 for vectors. Other vector folds are below.
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007743 if (SDValue FoldedVOp = SimplifyVBinOp(N))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007744 return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007745 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007746
Nate Begemanec48a1b2005-10-17 20:40:11 +00007747 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007748 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007749 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00007750
Nate Begemanec48a1b2005-10-17 20:40:11 +00007751 // canonicalize constant to RHS
Simon Pilgrimbcf3bc22015-04-05 14:30:37 +00007752 if (isConstantFPBuildVectorOrConstantFP(N0) &&
7753 !isConstantFPBuildVectorOrConstantFP(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007754 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007755
Owen Andersonb5f167c2012-05-02 21:32:35 +00007756 // fold (fmul A, 1.0) -> A
7757 if (N1CFP && N1CFP->isExactlyValue(1.0))
7758 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00007759
Sanjay Patel394c3332014-09-08 20:16:42 +00007760 if (Options.UnsafeFPMath) {
7761 // fold (fmul A, 0) -> 0
7762 if (N1CFP && N1CFP->getValueAPF().isZero())
7763 return N1;
7764
7765 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007766 if (N0.getOpcode() == ISD::FMUL) {
7767 // Fold scalars or any vector constants (not just splats).
7768 // This fold is done in general by InstCombine, but extra fmul insts
7769 // may have been generated during lowering.
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007770 SDValue N00 = N0.getOperand(0);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007771 SDValue N01 = N0.getOperand(1);
7772 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007773 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007774 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007775
7776 // Check 1: Make sure that the first operand of the inner multiply is NOT
7777 // a constant. Otherwise, we may induce infinite looping.
7778 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7779 // Check 2: Make sure that the second operand of the inner multiply and
7780 // the second operand of the outer multiply are constants.
7781 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7782 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7783 SDLoc SL(N);
7784 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7785 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7786 }
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007787 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007788 }
7789
Sanjay Patel394c3332014-09-08 20:16:42 +00007790 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007791 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7792 // during an early run of DAGCombiner can prevent folding with fmuls
7793 // inserted during lowering.
7794 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7795 SDLoc SL(N);
7796 const SDValue Two = DAG.getConstantFP(2.0, VT);
7797 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7798 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7799 }
7800 }
7801
Nate Begemanec48a1b2005-10-17 20:40:11 +00007802 // fold (fmul X, 2.0) -> (fadd X, X)
7803 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007804 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007805
Dan Gohmanb7170912009-08-10 16:50:32 +00007806 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00007807 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00007808 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007809 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007810
Bill Wendling3dc5d242009-01-30 22:57:07 +00007811 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007812 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7813 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007814 // Both can be negated for free, check to see if at least one is cheaper
7815 // negated.
7816 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007817 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007818 GetNegatedExpression(N0, DAG, LegalOperations),
7819 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007820 }
7821 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007822
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007823 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007824}
7825
Owen Anderson41b06652012-05-02 22:17:40 +00007826SDValue DAGCombiner::visitFMA(SDNode *N) {
7827 SDValue N0 = N->getOperand(0);
7828 SDValue N1 = N->getOperand(1);
7829 SDValue N2 = N->getOperand(2);
7830 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7831 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7832 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007833 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007834 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007835
7836 // Constant fold FMA.
7837 if (isa<ConstantFPSDNode>(N0) &&
7838 isa<ConstantFPSDNode>(N1) &&
7839 isa<ConstantFPSDNode>(N2)) {
7840 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7841 }
7842
Sanjay Patel78614bf2014-08-28 15:53:16 +00007843 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00007844 if (N0CFP && N0CFP->isZero())
7845 return N2;
7846 if (N1CFP && N1CFP->isZero())
7847 return N2;
7848 }
Owen Anderson41b06652012-05-02 22:17:40 +00007849 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007850 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007851 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007852 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007853
Owen Andersonc7aaf522012-05-30 18:50:39 +00007854 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00007855 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007856 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00007857
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007858 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007859 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007860 N2.getOpcode() == ISD::FMUL &&
7861 N0 == N2.getOperand(0) &&
7862 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7863 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7864 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7865 }
7866
7867
7868 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007869 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007870 N0.getOpcode() == ISD::FMUL && N1CFP &&
7871 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7872 return DAG.getNode(ISD::FMA, dl, VT,
7873 N0.getOperand(0),
7874 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7875 N2);
7876 }
7877
7878 // (fma x, 1, y) -> (fadd x, y)
7879 // (fma x, -1, y) -> (fadd (fneg x), y)
7880 if (N1CFP) {
7881 if (N1CFP->isExactlyValue(1.0))
7882 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7883
7884 if (N1CFP->isExactlyValue(-1.0) &&
7885 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7886 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007887 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007888 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7889 }
7890 }
7891
7892 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007893 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00007894 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007895 DAG.getNode(ISD::FADD, dl, VT,
7896 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007897
7898 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007899 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00007900 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7901 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007902 DAG.getNode(ISD::FADD, dl, VT,
7903 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007904
7905
Owen Anderson41b06652012-05-02 22:17:40 +00007906 return SDValue();
7907}
7908
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007909SDValue DAGCombiner::visitFDIV(SDNode *N) {
7910 SDValue N0 = N->getOperand(0);
7911 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007912 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7913 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007914 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007915 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007916 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007917
Dan Gohmana8665142007-06-25 16:23:39 +00007918 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007919 if (VT.isVector())
7920 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7921 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007922
Nate Begeman569c4392006-01-18 22:35:16 +00007923 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007924 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007925 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007926
Sanjay Patelb67bd262014-09-21 15:19:15 +00007927 if (Options.UnsafeFPMath) {
7928 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7929 if (N1CFP) {
7930 // Compute the reciprocal 1.0 / c2.
7931 APFloat N1APF = N1CFP->getValueAPF();
7932 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7933 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7934 // Only do the transform if the reciprocal is a legal fp immediate that
7935 // isn't too nasty (eg NaN, denormal, ...).
7936 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7937 (!LegalOperations ||
7938 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7939 // backend)... we should handle this gracefully after Legalize.
7940 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7941 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7942 TLI.isFPImmLegal(Recip, VT)))
7943 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7944 DAG.getConstantFP(Recip, VT));
7945 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007946
Sanjay Patelb67bd262014-09-21 15:19:15 +00007947 // If this FDIV is part of a reciprocal square root, it may be folded
7948 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007949 if (N1.getOpcode() == ISD::FSQRT) {
7950 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007951 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7952 }
7953 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7954 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7955 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007956 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7957 AddToWorklist(RV.getNode());
7958 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7959 }
7960 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7961 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7962 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007963 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7964 AddToWorklist(RV.getNode());
7965 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7966 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00007967 } else if (N1.getOpcode() == ISD::FMUL) {
7968 // Look through an FMUL. Even though this won't remove the FDIV directly,
7969 // it's still worthwhile to get rid of the FSQRT if possible.
7970 SDValue SqrtOp;
7971 SDValue OtherOp;
7972 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7973 SqrtOp = N1.getOperand(0);
7974 OtherOp = N1.getOperand(1);
7975 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7976 SqrtOp = N1.getOperand(1);
7977 OtherOp = N1.getOperand(0);
7978 }
7979 if (SqrtOp.getNode()) {
7980 // We found a FSQRT, so try to make this fold:
7981 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7982 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00007983 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7984 AddToWorklist(RV.getNode());
7985 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7986 }
7987 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007988 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007989
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007990 // Fold into a reciprocal estimate and multiply instead of a real divide.
7991 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7992 AddToWorklist(RV.getNode());
7993 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7994 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00007995 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007996
Bill Wendling3dc5d242009-01-30 22:57:07 +00007997 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007998 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7999 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00008000 // Both can be negated for free, check to see if at least one is cheaper
8001 // negated.
8002 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008003 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008004 GetNegatedExpression(N0, DAG, LegalOperations),
8005 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00008006 }
8007 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008008
Hao Liu44e5d7a2014-11-21 06:39:58 +00008009 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8010 // reciprocal.
8011 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8012 // Notice that this is not always beneficial. One reason is different target
8013 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8014 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8015 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8016 if (Options.UnsafeFPMath) {
8017 // Skip if current node is a reciprocal.
8018 if (N0CFP && N0CFP->isExactlyValue(1.0))
8019 return SDValue();
8020
8021 SmallVector<SDNode *, 4> Users;
8022 // Find all FDIV users of the same divisor.
8023 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8024 UE = N1.getNode()->use_end();
8025 UI != UE; ++UI) {
8026 SDNode *User = UI.getUse().getUser();
8027 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8028 Users.push_back(User);
8029 }
8030
8031 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8032 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
8033 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
8034
8035 // Dividend / Divisor -> Dividend * Reciprocal
8036 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8037 if ((*I)->getOperand(0) != FPOne) {
8038 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8039 (*I)->getOperand(0), Reciprocal);
8040 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8041 }
8042 }
8043 return SDValue();
8044 }
8045 }
8046
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008047 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008048}
8049
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008050SDValue DAGCombiner::visitFREM(SDNode *N) {
8051 SDValue N0 = N->getOperand(0);
8052 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008053 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8054 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008055 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00008056
Nate Begeman569c4392006-01-18 22:35:16 +00008057 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008058 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008059 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00008060
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008061 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008062}
8063
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008064SDValue DAGCombiner::visitFSQRT(SDNode *N) {
Matt Arsenaultbf0db912015-01-13 20:53:23 +00008065 if (DAG.getTarget().Options.UnsafeFPMath &&
8066 !TLI.isFsqrtCheap()) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008067 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008068 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008069 EVT VT = RV.getValueType();
8070 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
8071 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008072
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008073 // Unfortunately, RV is now NaN if the input was exactly 0.
8074 // Select out this case and force the answer to 0.
8075 SDValue Zero = DAG.getConstantFP(0.0, VT);
8076 SDValue ZeroCmp =
8077 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
8078 N->getOperand(0), Zero, ISD::SETEQ);
8079 AddToWorklist(ZeroCmp.getNode());
8080 AddToWorklist(RV.getNode());
8081
8082 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8083 SDLoc(N), VT, ZeroCmp, Zero, RV);
8084 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008085 }
8086 }
8087 return SDValue();
8088}
8089
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008090SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8091 SDValue N0 = N->getOperand(0);
8092 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00008093 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8094 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008095 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00008096
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008097 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00008098 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008099
Chris Lattner3bc40502006-03-05 05:30:57 +00008100 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00008101 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00008102 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8103 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00008104 if (!V.isNegative()) {
8105 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008106 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00008107 } else {
8108 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008109 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8110 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00008111 }
Chris Lattner3bc40502006-03-05 05:30:57 +00008112 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008113
Chris Lattner3bc40502006-03-05 05:30:57 +00008114 // copysign(fabs(x), y) -> copysign(x, y)
8115 // copysign(fneg(x), y) -> copysign(x, y)
8116 // copysign(copysign(x,z), y) -> copysign(x, y)
8117 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8118 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008119 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008120 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00008121
8122 // copysign(x, abs(y)) -> abs(x)
8123 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008124 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008125
Chris Lattner3bc40502006-03-05 05:30:57 +00008126 // copysign(x, copysign(y,z)) -> copysign(x, z)
8127 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008128 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008129 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008130
Chris Lattner3bc40502006-03-05 05:30:57 +00008131 // copysign(x, fp_extend(y)) -> copysign(x, y)
8132 // copysign(x, fp_round(y)) -> copysign(x, y)
8133 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008134 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008135 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008136
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008137 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00008138}
8139
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008140SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8141 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008142 EVT VT = N->getValueType(0);
8143 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008144
Nate Begeman21158fc2005-09-01 00:19:25 +00008145 // fold (sint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008146 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008147 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008148 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008149 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008150 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008151
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008152 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8153 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008154 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8155 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008156 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008157 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008158 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008159 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008160
Alp Tokercb402912014-01-24 17:20:08 +00008161 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008162 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008163 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8164 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8165 !VT.isVector() &&
8166 (!LegalOperations ||
8167 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8168 SDValue Ops[] =
8169 { N0.getOperand(0), N0.getOperand(1),
8170 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
8171 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00008172 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008173 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008174
Nadav Rotem90560762012-07-23 07:59:50 +00008175 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8176 // (select_cc x, y, 1.0, 0.0,, cc)
8177 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8178 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8179 (!LegalOperations ||
8180 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8181 SDValue Ops[] =
8182 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8183 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
8184 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00008185 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008186 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008187 }
8188
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008189 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008190}
8191
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008192SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8193 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008194 EVT VT = N->getValueType(0);
8195 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00008196
Nate Begeman21158fc2005-09-01 00:19:25 +00008197 // fold (uint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008198 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008199 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008200 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008201 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008202 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008203
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008204 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8205 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008206 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8207 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008208 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008209 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008210 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008211 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008212
Alp Tokercb402912014-01-24 17:20:08 +00008213 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008214 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008215 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00008216
Nadav Rotem90560762012-07-23 07:59:50 +00008217 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8218 (!LegalOperations ||
8219 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8220 SDValue Ops[] =
8221 { N0.getOperand(0), N0.getOperand(1),
8222 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8223 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00008224 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008225 }
8226 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008227
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008228 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008229}
8230
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008231// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8232static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8233 SDValue N0 = N->getOperand(0);
8234 EVT VT = N->getValueType(0);
8235
8236 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8237 return SDValue();
8238
8239 SDValue Src = N0.getOperand(0);
8240 EVT SrcVT = Src.getValueType();
8241 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8242 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8243
8244 // We can safely assume the conversion won't overflow the output range,
8245 // because (for example) (uint8_t)18293.f is undefined behavior.
8246
8247 // Since we can assume the conversion won't overflow, our decision as to
8248 // whether the input will fit in the float should depend on the minimum
8249 // of the input range and output range.
8250
8251 // This means this is also safe for a signed input and unsigned output, since
8252 // a negative input would lead to undefined behavior.
8253 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8254 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8255 unsigned ActualSize = std::min(InputSize, OutputSize);
8256 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8257
8258 // We can only fold away the float conversion if the input range can be
8259 // represented exactly in the float range.
8260 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8261 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8262 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8263 : ISD::ZERO_EXTEND;
8264 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8265 }
8266 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8267 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8268 if (SrcVT == VT)
8269 return Src;
8270 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8271 }
8272 return SDValue();
8273}
8274
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008275SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8276 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008277 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008278 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008279
Nate Begeman21158fc2005-09-01 00:19:25 +00008280 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008281 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008282 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008283
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008284 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008285}
8286
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008287SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8288 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008289 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008290 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008291
Nate Begeman21158fc2005-09-01 00:19:25 +00008292 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008293 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008294 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008295
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008296 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008297}
8298
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008299SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8300 SDValue N0 = N->getOperand(0);
8301 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008302 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008303 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008304
Nate Begeman21158fc2005-09-01 00:19:25 +00008305 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008306 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008307 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008308
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008309 // fold (fp_round (fp_extend x)) -> x
8310 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8311 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008312
Chris Lattner0feb1b02008-01-24 06:45:35 +00008313 // fold (fp_round (fp_round x)) -> (fp_round x)
8314 if (N0.getOpcode() == ISD::FP_ROUND) {
Ahmed Bougacha24433a72015-02-12 06:15:29 +00008315 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8316 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8317 // If the first fp_round isn't a value preserving truncation, it might
8318 // introduce a tie in the second fp_round, that wouldn't occur in the
8319 // single-step fp_round we want to fold to.
8320 // In other words, double rounding isn't the same as rounding.
8321 // Also, this is a value preserving truncation iff both fp_round's are.
8322 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8323 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8324 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
Chris Lattner0feb1b02008-01-24 06:45:35 +00008325 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008326
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008327 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00008328 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008329 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008330 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008331 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008332 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008333 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008334 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008335
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008336 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008337}
8338
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008339SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8340 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008341 EVT VT = N->getValueType(0);
8342 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008343 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008344
Nate Begeman21158fc2005-09-01 00:19:25 +00008345 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00008346 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00008347 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008348 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00008349 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008350
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008351 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008352}
8353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008354SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8355 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008356 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008357
Chris Lattner5919b482007-12-29 06:55:23 +00008358 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008359 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00008360 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008361 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00008362
Nate Begeman21158fc2005-09-01 00:19:25 +00008363 // fold (fp_extend c1fp) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008364 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008365 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00008366
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +00008367 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8368 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8369 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8370 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8371
Chris Lattner72733e52008-01-17 07:00:52 +00008372 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8373 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00008374 if (N0.getOpcode() == ISD::FP_ROUND
8375 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008376 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00008377 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00008378 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008379 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008380 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008381 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00008382 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008383
Chris Lattner72733e52008-01-17 07:00:52 +00008384 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00008385 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00008386 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008387 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008388 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008389 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008390 LN0->getBasePtr(), N0.getValueType(),
8391 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00008392 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00008393 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008394 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00008395 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00008396 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008397 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00008398 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00008399
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008400 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008401}
8402
Sanjay Patelccd26762014-08-28 21:51:37 +00008403SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8404 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008405 EVT VT = N->getValueType(0);
8406
8407 // fold (fceil c1) -> fceil(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008408 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008409 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8410
8411 return SDValue();
8412}
8413
8414SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8415 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008416 EVT VT = N->getValueType(0);
8417
8418 // fold (ftrunc c1) -> ftrunc(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008419 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008420 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8421
8422 return SDValue();
8423}
8424
8425SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8426 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008427 EVT VT = N->getValueType(0);
8428
8429 // fold (ffloor c1) -> ffloor(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008430 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008431 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8432
8433 return SDValue();
8434}
8435
8436// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008437SDValue DAGCombiner::visitFNEG(SDNode *N) {
8438 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00008439 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008440
Sanjay Patelccd26762014-08-28 21:51:37 +00008441 // Constant fold FNEG.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008442 if (isConstantFPBuildVectorOrConstantFP(N0))
8443 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008444
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00008445 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8446 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008447 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00008448
Sanjay Patel35d31332014-08-14 15:15:28 +00008449 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008450 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00008451 if (!TLI.isFNegFree(VT) &&
8452 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00008453 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008454 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008455 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008456 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00008457 APInt SignMask;
8458 if (N0.getValueType().isVector()) {
8459 // For a vector, get a mask such as 0x80... per scalar element
8460 // and splat it.
8461 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8462 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8463 } else {
8464 // For a scalar, just generate 0x80...
8465 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8466 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008467 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00008468 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008469 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00008470 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008471 }
8472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008473
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008474 // (fneg (fmul c, x)) -> (fmul -c, x)
8475 if (N0.getOpcode() == ISD::FMUL) {
8476 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00008477 if (CFP1) {
8478 APFloat CVal = CFP1->getValueAPF();
8479 CVal.changeSign();
8480 if (Level >= AfterLegalizeDAG &&
8481 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8482 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8483 return DAG.getNode(
8484 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8485 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8486 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008487 }
8488
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008489 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008490}
8491
Matt Arsenault7c936902014-10-21 23:01:01 +00008492SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8493 SDValue N0 = N->getOperand(0);
8494 SDValue N1 = N->getOperand(1);
8495 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8496 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8497
8498 if (N0CFP && N1CFP) {
8499 const APFloat &C0 = N0CFP->getValueAPF();
8500 const APFloat &C1 = N1CFP->getValueAPF();
8501 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8502 }
8503
8504 if (N0CFP) {
8505 EVT VT = N->getValueType(0);
8506 // Canonicalize to constant on RHS.
8507 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8508 }
8509
8510 return SDValue();
8511}
8512
8513SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8514 SDValue N0 = N->getOperand(0);
8515 SDValue N1 = N->getOperand(1);
8516 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8517 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8518
8519 if (N0CFP && N1CFP) {
8520 const APFloat &C0 = N0CFP->getValueAPF();
8521 const APFloat &C1 = N1CFP->getValueAPF();
8522 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8523 }
8524
8525 if (N0CFP) {
8526 EVT VT = N->getValueType(0);
8527 // Canonicalize to constant on RHS.
8528 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8529 }
8530
8531 return SDValue();
8532}
8533
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008534SDValue DAGCombiner::visitFABS(SDNode *N) {
8535 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008536 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008537
Nate Begeman21158fc2005-09-01 00:19:25 +00008538 // fold (fabs c1) -> fabs(c1)
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008539 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008540 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008541
Nate Begeman21158fc2005-09-01 00:19:25 +00008542 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008543 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00008544 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008545
Nate Begeman21158fc2005-09-01 00:19:25 +00008546 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008547 // fold (fabs (fcopysign x, y)) -> (fabs x)
8548 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008549 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008550
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008551 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008552 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00008553 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008554 N0.getOpcode() == ISD::BITCAST &&
8555 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008556 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008557 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008558 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008559 APInt SignMask;
8560 if (N0.getValueType().isVector()) {
8561 // For a vector, get a mask such as 0x7f... per scalar element
8562 // and splat it.
8563 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8564 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8565 } else {
8566 // For a scalar, just generate 0x7f...
8567 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8568 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008569 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008570 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008571 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008572 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008573 }
8574 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008576 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008577}
8578
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008579SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8580 SDValue Chain = N->getOperand(0);
8581 SDValue N1 = N->getOperand(1);
8582 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008583
Dan Gohman82e80012009-11-17 00:47:23 +00008584 // If N is a constant we could fold this into a fallthrough or unconditional
8585 // branch. However that doesn't happen very often in normal code, because
8586 // Instcombine/SimplifyCFG should have handled the available opportunities.
8587 // If we did this folding here, it would be necessary to update the
8588 // MachineBasicBlock CFG, which is awkward.
8589
Nate Begeman7e7f4392006-02-01 07:19:44 +00008590 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8591 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008592 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00008593 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8594 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008595 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008596 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00008597 N1.getOperand(0), N1.getOperand(1), N2);
8598 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008599
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008600 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8601 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8602 (N1.getOperand(0).hasOneUse() &&
8603 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00008604 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008605 if (N1.getOpcode() == ISD::TRUNCATE) {
8606 // Look pass the truncate.
8607 Trunc = N1.getNode();
8608 N1 = N1.getOperand(0);
8609 }
Evan Cheng166a4e62010-01-06 19:38:29 +00008610
Bill Wendlingaa28be62009-03-26 06:14:09 +00008611 // Match this pattern so that we can generate simpler code:
8612 //
8613 // %a = ...
8614 // %b = and i32 %a, 2
8615 // %c = srl i32 %b, 1
8616 // brcond i32 %c ...
8617 //
8618 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00008619 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00008620 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00008621 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00008622 // %c = setcc eq %b, 0
8623 // brcond %c ...
8624 //
8625 // This applies only when the AND constant value has one bit set and the
8626 // SRL constant is equal to the log2 of the AND constant. The back-end is
8627 // smart enough to convert the result into a TEST/JMP sequence.
8628 SDValue Op0 = N1.getOperand(0);
8629 SDValue Op1 = N1.getOperand(1);
8630
8631 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00008632 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00008633 SDValue AndOp1 = Op0.getOperand(1);
8634
8635 if (AndOp1.getOpcode() == ISD::Constant) {
8636 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8637
8638 if (AndConst.isPowerOf2() &&
8639 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8640 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008641 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00008642 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00008643 Op0, DAG.getConstant(0, Op0.getValueType()),
8644 ISD::SETNE);
8645
Andrew Trickef9de2a2013-05-25 02:42:55 +00008646 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00008647 MVT::Other, Chain, SetCC, N2);
8648 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8649 // will convert it back to (X & C1) >> C2.
8650 CombineTo(N, NewBRCond, false);
8651 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00008652 if (Trunc)
8653 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008654 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008655 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008656 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008657 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00008658 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00008659 }
8660 }
8661 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008662
8663 if (Trunc)
8664 // Restore N1 if the above transformation doesn't match.
8665 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008666 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008667
Evan Cheng228c31f2010-02-27 07:36:59 +00008668 // Transform br(xor(x, y)) -> br(x != y)
8669 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8670 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8671 SDNode *TheXor = N1.getNode();
8672 SDValue Op0 = TheXor->getOperand(0);
8673 SDValue Op1 = TheXor->getOperand(1);
8674 if (Op0.getOpcode() == Op1.getOpcode()) {
8675 // Avoid missing important xor optimizations.
8676 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008677 if (Tmp.getNode()) {
8678 if (Tmp.getNode() != TheXor) {
8679 DEBUG(dbgs() << "\nReplacing.8 ";
8680 TheXor->dump(&DAG);
8681 dbgs() << "\nWith: ";
8682 Tmp.getNode()->dump(&DAG);
8683 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008684 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008685 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00008686 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008687 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00008688 MVT::Other, Chain, Tmp, N2);
8689 }
8690
Benjamin Kramer93354432013-03-30 21:28:18 +00008691 // visitXOR has changed XOR's operands or replaced the XOR completely,
8692 // bail out.
8693 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00008694 }
8695 }
8696
8697 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8698 bool Equal = false;
8699 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8700 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8701 Op0.getOpcode() == ISD::XOR) {
8702 TheXor = Op0.getNode();
8703 Equal = true;
8704 }
8705
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008706 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00008707 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00008708 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008709 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00008710 SetCCVT,
8711 Op0, Op1,
8712 Equal ? ISD::SETEQ : ISD::SETNE);
8713 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008714 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008715 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008716 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008717 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00008718 MVT::Other, Chain, SetCC, N2);
8719 }
8720 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00008721
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008722 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008723}
8724
Chris Lattnera49e16f2005-10-05 06:47:48 +00008725// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8726//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008727SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00008728 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008729 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008730
Dan Gohman82e80012009-11-17 00:47:23 +00008731 // If N is a constant we could fold this into a fallthrough or unconditional
8732 // branch. However that doesn't happen very often in normal code, because
8733 // Instcombine/SimplifyCFG should have handled the available opportunities.
8734 // If we did this folding here, it would be necessary to update the
8735 // MachineBasicBlock CFG, which is awkward.
8736
Duncan Sands93b66092008-06-09 11:32:28 +00008737 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00008738 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008739 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00008740 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008741 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00008742
Nate Begemanbd7df032005-10-05 21:43:42 +00008743 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00008744 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008745 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008746 N->getOperand(0), Simp.getOperand(2),
8747 Simp.getOperand(0), Simp.getOperand(1),
8748 N->getOperand(4));
8749
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008750 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008751}
8752
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008753/// Return true if 'Use' is a load or a store that uses N as its base pointer
8754/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00008755static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8756 SelectionDAG &DAG,
8757 const TargetLowering &TLI) {
8758 EVT VT;
8759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8760 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8761 return false;
8762 VT = Use->getValueType(0);
8763 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8764 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8765 return false;
8766 VT = ST->getValue().getValueType();
8767 } else
8768 return false;
8769
Chandler Carruth95f83e02013-01-07 15:14:13 +00008770 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00008771 if (N->getOpcode() == ISD::ADD) {
8772 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8773 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008774 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008775 AM.BaseOffs = Offset->getSExtValue();
8776 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008777 // [reg +/- reg]
8778 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008779 } else if (N->getOpcode() == ISD::SUB) {
8780 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8781 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008782 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008783 AM.BaseOffs = -Offset->getSExtValue();
8784 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008785 // [reg +/- reg]
8786 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008787 } else
8788 return false;
8789
8790 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8791}
8792
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008793/// Try turning a load/store into a pre-indexed load/store when the base
8794/// pointer is an add or subtract and it has other uses besides the load/store.
8795/// After the transformation, the new indexed load/store has effectively folded
8796/// the add/subtract in and all of its other uses are redirected to the
8797/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008798bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008799 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008800 return false;
8801
8802 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008803 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008804 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008806 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008807 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008808 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00008809 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00008810 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8811 return false;
8812 Ptr = LD->getBasePtr();
8813 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008814 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008815 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008816 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008817 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8818 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8819 return false;
8820 Ptr = ST->getBasePtr();
8821 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008822 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008823 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008824 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008825
Chris Lattnereabc15c2006-11-11 00:56:29 +00008826 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8827 // out. There is no reason to make this a preinc/predec.
8828 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00008829 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008830 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008831
Chris Lattnereabc15c2006-11-11 00:56:29 +00008832 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008833 SDValue BasePtr;
8834 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008835 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8836 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8837 return false;
Hal Finkel25819052013-02-08 21:35:47 +00008838
8839 // Backends without true r+i pre-indexed forms may need to pass a
8840 // constant base with a variable offset so that constant coercion
8841 // will work with the patterns in canonical form.
8842 bool Swapped = false;
8843 if (isa<ConstantSDNode>(BasePtr)) {
8844 std::swap(BasePtr, Offset);
8845 Swapped = true;
8846 }
8847
Evan Cheng044a0a82007-05-03 23:52:19 +00008848 // Don't create a indexed load / store with zero offset.
8849 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008850 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008851 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008852
Chris Lattnera0a80032006-11-11 01:00:15 +00008853 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00008854 // 1) The new base ptr is a frame index.
8855 // 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 +00008856 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00008857 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00008858 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00008859 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00008860
Chris Lattnera0a80032006-11-11 01:00:15 +00008861 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8862 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00008863 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00008864 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008865
Chris Lattnera0a80032006-11-11 01:00:15 +00008866 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008867 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008868 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00008869 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008870 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008871 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008872
Hal Finkel25819052013-02-08 21:35:47 +00008873 // If the offset is a constant, there may be other adds of constants that
8874 // can be folded with this one. We should do this to avoid having to keep
8875 // a copy of the original base pointer.
8876 SmallVector<SDNode *, 16> OtherUses;
8877 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00008878 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00008879 if (Use == Ptr.getNode())
8880 continue;
8881
8882 if (Use->isPredecessorOf(N))
8883 continue;
8884
8885 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8886 OtherUses.clear();
8887 break;
8888 }
8889
8890 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8891 if (Op1.getNode() == BasePtr.getNode())
8892 std::swap(Op0, Op1);
8893 assert(Op0.getNode() == BasePtr.getNode() &&
8894 "Use of ADD/SUB but not an operand");
8895
8896 if (!isa<ConstantSDNode>(Op1)) {
8897 OtherUses.clear();
8898 break;
8899 }
8900
8901 // FIXME: In some cases, we can be smarter about this.
8902 if (Op1.getValueType() != Offset.getValueType()) {
8903 OtherUses.clear();
8904 break;
8905 }
8906
8907 OtherUses.push_back(Use);
8908 }
8909
8910 if (Swapped)
8911 std::swap(BasePtr, Offset);
8912
Evan Chenga4d187b2007-05-24 02:35:39 +00008913 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008914 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00008915
8916 // Caches for hasPredecessorHelper
8917 SmallPtrSet<const SDNode *, 32> Visited;
8918 SmallVector<const SDNode *, 16> Worklist;
8919
Jim Grosbache8160032014-04-11 01:13:13 +00008920 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008921 if (Use == N)
8922 continue;
Lang Hames5a004992011-07-07 04:31:51 +00008923 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008924 return false;
8925
Evan Chengfa832632012-01-13 01:37:24 +00008926 // If Ptr may be folded in addressing mode of other use, then it's
8927 // not profitable to do this transformation.
8928 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008929 RealUse = true;
8930 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008931
Chris Lattnereabc15c2006-11-11 00:56:29 +00008932 if (!RealUse)
8933 return false;
8934
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008935 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008936 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008937 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008938 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008939 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00008940 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008941 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008942 ++PreIndexedNodes;
8943 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008944 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008945 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008946 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008947 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008948 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008949 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008950 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008951 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8952 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008953 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008954 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008955 }
8956
Chris Lattnereabc15c2006-11-11 00:56:29 +00008957 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008958 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008959
Hal Finkel25819052013-02-08 21:35:47 +00008960 if (Swapped)
8961 std::swap(BasePtr, Offset);
8962
8963 // Replace other uses of BasePtr that can be updated to use Ptr
8964 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8965 unsigned OffsetIdx = 1;
8966 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8967 OffsetIdx = 0;
8968 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8969 BasePtr.getNode() && "Expected BasePtr operand");
8970
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008971 // We need to replace ptr0 in the following expression:
8972 // x0 * offset0 + y0 * ptr0 = t0
8973 // knowing that
8974 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00008975 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008976 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8977 // indexed load/store and the expresion that needs to be re-written.
8978 //
8979 // Therefore, we have:
8980 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00008981
8982 ConstantSDNode *CN =
8983 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008984 int X0, X1, Y0, Y1;
8985 APInt Offset0 = CN->getAPIntValue();
8986 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00008987
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008988 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8989 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8990 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8991 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00008992
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008993 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8994
8995 APInt CNV = Offset0;
8996 if (X0 < 0) CNV = -CNV;
8997 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8998 else CNV = CNV - Offset1;
8999
9000 // We can now generate the new expression.
9001 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
9002 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9003
9004 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00009005 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00009006 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9007 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00009008 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00009009 }
9010
Chris Lattnereabc15c2006-11-11 00:56:29 +00009011 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009012 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00009013 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00009014
9015 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00009016}
9017
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009018/// Try to combine a load/store with a add/sub of the base pointer node into a
9019/// post-indexed load/store. The transformation folded the add/subtract into the
9020/// new indexed load/store effectively and all of its uses are redirected to the
9021/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00009022bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00009023 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00009024 return false;
9025
9026 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009027 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009028 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00009029 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009030 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009031 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009032 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009033 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9034 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9035 return false;
9036 Ptr = LD->getBasePtr();
9037 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009038 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009039 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009040 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009041 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9042 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9043 return false;
9044 Ptr = ST->getBasePtr();
9045 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009046 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00009047 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009048 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009049
Gabor Greiff304a7a2008-08-28 21:40:38 +00009050 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00009051 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009052
Jim Grosbache8160032014-04-11 01:13:13 +00009053 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00009054 if (Op == N ||
9055 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9056 continue;
9057
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009058 SDValue BasePtr;
9059 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00009060 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9061 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00009062 // Don't create a indexed load / store with zero offset.
9063 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00009064 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00009065 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00009066
Chris Lattnereabc15c2006-11-11 00:56:29 +00009067 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00009068 // 1) All uses are load / store ops that use it as base ptr (and
9069 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00009070 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9071 // nor a successor of N. Otherwise, if Op is folded that would
9072 // create a cycle.
9073
Evan Chengcfc05132009-05-06 18:25:01 +00009074 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9075 continue;
9076
Chris Lattnereabc15c2006-11-11 00:56:29 +00009077 // Check for #1.
9078 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00009079 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009080 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00009081 continue;
9082
Chris Lattnereabc15c2006-11-11 00:56:29 +00009083 // If all the uses are load / store addresses, then don't do the
9084 // transformation.
9085 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9086 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00009087 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00009088 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009089 RealUse = true;
9090 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009091
Chris Lattnereabc15c2006-11-11 00:56:29 +00009092 if (!RealUse) {
9093 TryNext = true;
9094 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00009095 }
9096 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009097 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009098
Chris Lattnereabc15c2006-11-11 00:56:29 +00009099 if (TryNext)
9100 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00009101
Chris Lattnereabc15c2006-11-11 00:56:29 +00009102 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00009103 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009104 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00009105 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009106 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009107 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009108 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009109 ++PostIndexedNodes;
9110 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00009111 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009112 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009113 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009114 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009115 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009116 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009117 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009118 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9119 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009120 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009121 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00009122 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009123
Chris Lattnereabc15c2006-11-11 00:56:29 +00009124 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00009125 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009126
9127 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009128 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009129 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00009130 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009131 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00009132 }
9133 }
9134 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009135
Chris Lattnerffad2162006-11-11 00:39:41 +00009136 return false;
9137}
9138
Hal Finkel51e6fa22014-09-02 06:24:04 +00009139/// \brief Return the base-pointer arithmetic from an indexed \p LD.
9140SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9141 ISD::MemIndexedMode AM = LD->getAddressingMode();
9142 assert(AM != ISD::UNINDEXED);
9143 SDValue BP = LD->getOperand(1);
9144 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00009145
9146 // Some backends use TargetConstants for load offsets, but don't expect
9147 // TargetConstants in general ADD nodes. We can convert these constants into
9148 // regular Constants (if the constant is not opaque).
9149 assert((Inc.getOpcode() != ISD::TargetConstant ||
9150 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9151 "Cannot split out indexing using opaque target constants");
9152 if (Inc.getOpcode() == ISD::TargetConstant) {
9153 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9154 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
9155 ConstInc->getValueType(0));
9156 }
9157
Hal Finkel51e6fa22014-09-02 06:24:04 +00009158 unsigned Opc =
9159 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9160 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9161}
9162
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009163SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00009164 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009165 SDValue Chain = LD->getChain();
9166 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009167
Evan Chenga684cd22007-05-01 00:38:21 +00009168 // If load is not volatile and there are no uses of the loaded value (and
9169 // the updated indexed value in case of indexed loads), change uses of the
9170 // chain value into uses of the chain input (i.e. delete the dead load).
9171 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00009172 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00009173 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00009174 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00009175 // It's not safe to use the two value CombineTo variant here. e.g.
9176 // v1, chain2 = load chain1, loc
9177 // v2, chain3 = load chain2, loc
9178 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00009179 // Now we replace use of chain2 with chain1. This makes the second load
9180 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00009181 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009182 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009183 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009184 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009185 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009186 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009187 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00009188
Chandler Carruth18066972014-08-02 10:02:07 +00009189 if (N->use_empty())
9190 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00009191
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009192 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00009193 }
Evan Chengb68343c2007-05-01 08:53:39 +00009194 } else {
9195 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00009196 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00009197
Hal Finkele19006e2014-09-02 16:05:23 +00009198 // If this load has an opaque TargetConstant offset, then we cannot split
9199 // the indexing into an add/sub directly (that TargetConstant may not be
9200 // valid for a different type of node, and we cannot convert an opaque
9201 // target constant into a regular constant).
9202 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9203 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00009204
9205 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00009206 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00009207 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00009208 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00009209 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00009210 Index = SplitIndexingFromLoad(LD);
9211 // Try to fold the base pointer arithmetic into subsequent loads and
9212 // stores.
9213 AddUsersToWorklist(N);
9214 } else
9215 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00009216 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009217 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009218 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009219 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009220 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009221 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009222 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00009223 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009224 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00009225 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009226 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00009227 }
Evan Chenga684cd22007-05-01 00:38:21 +00009228 }
9229 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009230
Chris Lattnere260ed82005-10-10 22:04:48 +00009231 // If this load is directly stored, replace the load value with the stored
9232 // value.
9233 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009234 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00009235 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009236 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00009237 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9238 if (PrevST->getBasePtr() == Ptr &&
9239 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00009240 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00009241 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00009242 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009243
Evan Cheng43cd9e32010-04-01 06:04:33 +00009244 // Try to infer better alignment information than the load already has.
9245 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009246 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00009247 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9248 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00009249 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00009250 LD->getValueType(0),
9251 Chain, Ptr, LD->getPointerInfo(),
9252 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00009253 LD->isVolatile(), LD->isNonTemporal(),
9254 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +00009255 if (NewLoad.getNode() != N)
9256 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
Owen Andersonde89ecf2013-02-05 19:24:39 +00009257 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00009258 }
9259 }
9260
Eric Christopherf55d4712014-10-08 23:38:39 +00009261 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9262 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009263#ifndef NDEBUG
9264 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9265 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9266 UseAA = false;
9267#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009268 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009269 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009270 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009271
Jim Laskey708d0db2006-10-04 16:53:27 +00009272 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009273 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009274 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00009275
Jim Laskeyd07be232006-09-25 16:29:54 +00009276 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009277 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009278 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009279 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009280 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009281 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00009282 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009283 BetterChain, Ptr, LD->getMemoryVT(),
9284 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009285 }
Jim Laskeyd07be232006-09-25 16:29:54 +00009286
Jim Laskey708d0db2006-10-04 16:53:27 +00009287 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009288 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009289 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00009290
Nate Begeman879d8f12009-09-15 00:18:30 +00009291 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009292 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00009293
Jim Laskeydcf983c2006-10-13 23:32:28 +00009294 // Replace uses with load result and token factor. Don't add users
9295 // to work list.
9296 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009297 }
9298 }
9299
Evan Cheng357017f2006-11-03 03:06:21 +00009300 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00009301 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009302 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00009303
Quentin Colombetde0e0622013-10-11 18:29:42 +00009304 // Try to slice up N to more direct loads if the slices are mapped to
9305 // different register banks or pairing can take place.
9306 if (SliceUpLoad(N))
9307 return SDValue(N, 0);
9308
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009309 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00009310}
9311
Quentin Colombetde0e0622013-10-11 18:29:42 +00009312namespace {
9313/// \brief Helper structure used to slice a load in smaller loads.
9314/// Basically a slice is obtained from the following sequence:
9315/// Origin = load Ty1, Base
9316/// Shift = srl Ty1 Origin, CstTy Amount
9317/// Inst = trunc Shift to Ty2
9318///
9319/// Then, it will be rewriten into:
9320/// Slice = load SliceTy, Base + SliceOffset
9321/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9322///
9323/// SliceTy is deduced from the number of bits that are actually used to
9324/// build Inst.
9325struct LoadedSlice {
9326 /// \brief Helper structure used to compute the cost of a slice.
9327 struct Cost {
9328 /// Are we optimizing for code size.
9329 bool ForCodeSize;
9330 /// Various cost.
9331 unsigned Loads;
9332 unsigned Truncates;
9333 unsigned CrossRegisterBanksCopies;
9334 unsigned ZExts;
9335 unsigned Shift;
9336
9337 Cost(bool ForCodeSize = false)
9338 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9339 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9340
9341 /// \brief Get the cost of one isolated slice.
9342 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9343 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9344 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9345 EVT TruncType = LS.Inst->getValueType(0);
9346 EVT LoadedType = LS.getLoadedType();
9347 if (TruncType != LoadedType &&
9348 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9349 ZExts = 1;
9350 }
9351
9352 /// \brief Account for slicing gain in the current cost.
9353 /// Slicing provide a few gains like removing a shift or a
9354 /// truncate. This method allows to grow the cost of the original
9355 /// load with the gain from this slice.
9356 void addSliceGain(const LoadedSlice &LS) {
9357 // Each slice saves a truncate.
9358 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9359 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9360 LS.Inst->getOperand(0).getValueType()))
9361 ++Truncates;
9362 // If there is a shift amount, this slice gets rid of it.
9363 if (LS.Shift)
9364 ++Shift;
9365 // If this slice can merge a cross register bank copy, account for it.
9366 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9367 ++CrossRegisterBanksCopies;
9368 }
9369
9370 Cost &operator+=(const Cost &RHS) {
9371 Loads += RHS.Loads;
9372 Truncates += RHS.Truncates;
9373 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9374 ZExts += RHS.ZExts;
9375 Shift += RHS.Shift;
9376 return *this;
9377 }
9378
9379 bool operator==(const Cost &RHS) const {
9380 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9381 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9382 ZExts == RHS.ZExts && Shift == RHS.Shift;
9383 }
9384
9385 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9386
9387 bool operator<(const Cost &RHS) const {
9388 // Assume cross register banks copies are as expensive as loads.
9389 // FIXME: Do we want some more target hooks?
9390 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9391 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9392 // Unless we are optimizing for code size, consider the
9393 // expensive operation first.
9394 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9395 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9396 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9397 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9398 }
9399
9400 bool operator>(const Cost &RHS) const { return RHS < *this; }
9401
9402 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9403
9404 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9405 };
9406 // The last instruction that represent the slice. This should be a
9407 // truncate instruction.
9408 SDNode *Inst;
9409 // The original load instruction.
9410 LoadSDNode *Origin;
9411 // The right shift amount in bits from the original load.
9412 unsigned Shift;
9413 // The DAG from which Origin came from.
9414 // This is used to get some contextual information about legal types, etc.
9415 SelectionDAG *DAG;
9416
Craig Topperc0196b12014-04-14 00:51:57 +00009417 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9418 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00009419 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9420
Quentin Colombetde0e0622013-10-11 18:29:42 +00009421 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9422 /// \return Result is \p BitWidth and has used bits set to 1 and
9423 /// not used bits set to 0.
9424 APInt getUsedBits() const {
9425 // Reproduce the trunc(lshr) sequence:
9426 // - Start from the truncated value.
9427 // - Zero extend to the desired bit width.
9428 // - Shift left.
9429 assert(Origin && "No original load to compare against.");
9430 unsigned BitWidth = Origin->getValueSizeInBits(0);
9431 assert(Inst && "This slice is not bound to an instruction");
9432 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9433 "Extracted slice is bigger than the whole type!");
9434 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9435 UsedBits.setAllBits();
9436 UsedBits = UsedBits.zext(BitWidth);
9437 UsedBits <<= Shift;
9438 return UsedBits;
9439 }
9440
9441 /// \brief Get the size of the slice to be loaded in bytes.
9442 unsigned getLoadedSize() const {
9443 unsigned SliceSize = getUsedBits().countPopulation();
9444 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9445 return SliceSize / 8;
9446 }
9447
9448 /// \brief Get the type that will be loaded for this slice.
9449 /// Note: This may not be the final type for the slice.
9450 EVT getLoadedType() const {
9451 assert(DAG && "Missing context");
9452 LLVMContext &Ctxt = *DAG->getContext();
9453 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9454 }
9455
9456 /// \brief Get the alignment of the load used for this slice.
9457 unsigned getAlignment() const {
9458 unsigned Alignment = Origin->getAlignment();
9459 unsigned Offset = getOffsetFromBase();
9460 if (Offset != 0)
9461 Alignment = MinAlign(Alignment, Alignment + Offset);
9462 return Alignment;
9463 }
9464
9465 /// \brief Check if this slice can be rewritten with legal operations.
9466 bool isLegal() const {
9467 // An invalid slice is not legal.
9468 if (!Origin || !Inst || !DAG)
9469 return false;
9470
9471 // Offsets are for indexed load only, we do not handle that.
9472 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9473 return false;
9474
9475 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9476
9477 // Check that the type is legal.
9478 EVT SliceType = getLoadedType();
9479 if (!TLI.isTypeLegal(SliceType))
9480 return false;
9481
9482 // Check that the load is legal for this type.
9483 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9484 return false;
9485
9486 // Check that the offset can be computed.
9487 // 1. Check its type.
9488 EVT PtrType = Origin->getBasePtr().getValueType();
9489 if (PtrType == MVT::Untyped || PtrType.isExtended())
9490 return false;
9491
9492 // 2. Check that it fits in the immediate.
9493 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9494 return false;
9495
9496 // 3. Check that the computation is legal.
9497 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9498 return false;
9499
9500 // Check that the zext is legal if it needs one.
9501 EVT TruncateType = Inst->getValueType(0);
9502 if (TruncateType != SliceType &&
9503 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9504 return false;
9505
9506 return true;
9507 }
9508
9509 /// \brief Get the offset in bytes of this slice in the original chunk of
9510 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00009511 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009512 uint64_t getOffsetFromBase() const {
9513 assert(DAG && "Missing context.");
9514 bool IsBigEndian =
9515 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9516 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9517 uint64_t Offset = Shift / 8;
9518 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9519 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9520 "The size of the original loaded type is not a multiple of a"
9521 " byte.");
9522 // If Offset is bigger than TySizeInBytes, it means we are loading all
9523 // zeros. This should have been optimized before in the process.
9524 assert(TySizeInBytes > Offset &&
9525 "Invalid shift amount for given loaded size");
9526 if (IsBigEndian)
9527 Offset = TySizeInBytes - Offset - getLoadedSize();
9528 return Offset;
9529 }
9530
9531 /// \brief Generate the sequence of instructions to load the slice
9532 /// represented by this object and redirect the uses of this slice to
9533 /// this new sequence of instructions.
9534 /// \pre this->Inst && this->Origin are valid Instructions and this
9535 /// object passed the legal check: LoadedSlice::isLegal returned true.
9536 /// \return The last instruction of the sequence used to load the slice.
9537 SDValue loadSlice() const {
9538 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9539 const SDValue &OldBaseAddr = Origin->getBasePtr();
9540 SDValue BaseAddr = OldBaseAddr;
9541 // Get the offset in that chunk of bytes w.r.t. the endianess.
9542 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9543 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9544 if (Offset) {
9545 // BaseAddr = BaseAddr + Offset.
9546 EVT ArithType = BaseAddr.getValueType();
9547 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9548 DAG->getConstant(Offset, ArithType));
9549 }
9550
9551 // Create the type of the loaded slice according to its size.
9552 EVT SliceType = getLoadedType();
9553
9554 // Create the load for the slice.
9555 SDValue LastInst = DAG->getLoad(
9556 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9557 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9558 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9559 // If the final type is not the same as the loaded type, this means that
9560 // we have to pad with zero. Create a zero extend for that.
9561 EVT FinalType = Inst->getValueType(0);
9562 if (SliceType != FinalType)
9563 LastInst =
9564 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9565 return LastInst;
9566 }
9567
9568 /// \brief Check if this slice can be merged with an expensive cross register
9569 /// bank copy. E.g.,
9570 /// i = load i32
9571 /// f = bitcast i32 i to float
9572 bool canMergeExpensiveCrossRegisterBankCopy() const {
9573 if (!Inst || !Inst->hasOneUse())
9574 return false;
9575 SDNode *Use = *Inst->use_begin();
9576 if (Use->getOpcode() != ISD::BITCAST)
9577 return false;
9578 assert(DAG && "Missing context");
9579 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9580 EVT ResVT = Use->getValueType(0);
9581 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9582 const TargetRegisterClass *ArgRC =
9583 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9584 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9585 return false;
9586
9587 // At this point, we know that we perform a cross-register-bank copy.
9588 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00009589 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00009590 // Assume bitcasts are cheap, unless both register classes do not
9591 // explicitly share a common sub class.
9592 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9593 return false;
9594
9595 // Check if it will be merged with the load.
9596 // 1. Check the alignment constraint.
9597 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9598 ResVT.getTypeForEVT(*DAG->getContext()));
9599
9600 if (RequiredAlignment > getAlignment())
9601 return false;
9602
9603 // 2. Check that the load is a legal operation for that type.
9604 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9605 return false;
9606
9607 // 3. Check that we do not have a zext in the way.
9608 if (Inst->getValueType(0) != getLoadedType())
9609 return false;
9610
9611 return true;
9612 }
9613};
9614}
9615
Quentin Colombetde0e0622013-10-11 18:29:42 +00009616/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9617/// \p UsedBits looks like 0..0 1..1 0..0.
9618static bool areUsedBitsDense(const APInt &UsedBits) {
9619 // If all the bits are one, this is dense!
9620 if (UsedBits.isAllOnesValue())
9621 return true;
9622
9623 // Get rid of the unused bits on the right.
9624 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9625 // Get rid of the unused bits on the left.
9626 if (NarrowedUsedBits.countLeadingZeros())
9627 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9628 // Check that the chunk of bits is completely used.
9629 return NarrowedUsedBits.isAllOnesValue();
9630}
9631
9632/// \brief Check whether or not \p First and \p Second are next to each other
9633/// in memory. This means that there is no hole between the bits loaded
9634/// by \p First and the bits loaded by \p Second.
9635static bool areSlicesNextToEachOther(const LoadedSlice &First,
9636 const LoadedSlice &Second) {
9637 assert(First.Origin == Second.Origin && First.Origin &&
9638 "Unable to match different memory origins.");
9639 APInt UsedBits = First.getUsedBits();
9640 assert((UsedBits & Second.getUsedBits()) == 0 &&
9641 "Slices are not supposed to overlap.");
9642 UsedBits |= Second.getUsedBits();
9643 return areUsedBitsDense(UsedBits);
9644}
9645
9646/// \brief Adjust the \p GlobalLSCost according to the target
9647/// paring capabilities and the layout of the slices.
9648/// \pre \p GlobalLSCost should account for at least as many loads as
9649/// there is in the slices in \p LoadedSlices.
9650static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9651 LoadedSlice::Cost &GlobalLSCost) {
9652 unsigned NumberOfSlices = LoadedSlices.size();
9653 // If there is less than 2 elements, no pairing is possible.
9654 if (NumberOfSlices < 2)
9655 return;
9656
9657 // Sort the slices so that elements that are likely to be next to each
9658 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009659 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9660 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9661 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9662 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9663 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00009664 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9665 // First (resp. Second) is the first (resp. Second) potentially candidate
9666 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00009667 const LoadedSlice *First = nullptr;
9668 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009669 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9670 // Set the beginning of the pair.
9671 First = Second) {
9672
9673 Second = &LoadedSlices[CurrSlice];
9674
9675 // If First is NULL, it means we start a new pair.
9676 // Get to the next slice.
9677 if (!First)
9678 continue;
9679
9680 EVT LoadedType = First->getLoadedType();
9681
9682 // If the types of the slices are different, we cannot pair them.
9683 if (LoadedType != Second->getLoadedType())
9684 continue;
9685
9686 // Check if the target supplies paired loads for this type.
9687 unsigned RequiredAlignment = 0;
9688 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9689 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00009690 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009691 continue;
9692 }
9693 // Check if we meet the alignment requirement.
9694 if (RequiredAlignment > First->getAlignment())
9695 continue;
9696
9697 // Check that both loads are next to each other in memory.
9698 if (!areSlicesNextToEachOther(*First, *Second))
9699 continue;
9700
9701 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9702 --GlobalLSCost.Loads;
9703 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00009704 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009705 }
9706}
9707
9708/// \brief Check the profitability of all involved LoadedSlice.
9709/// Currently, it is considered profitable if there is exactly two
9710/// involved slices (1) which are (2) next to each other in memory, and
9711/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9712///
9713/// Note: The order of the elements in \p LoadedSlices may be modified, but not
9714/// the elements themselves.
9715///
9716/// FIXME: When the cost model will be mature enough, we can relax
9717/// constraints (1) and (2).
9718static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9719 const APInt &UsedBits, bool ForCodeSize) {
9720 unsigned NumberOfSlices = LoadedSlices.size();
9721 if (StressLoadSlicing)
9722 return NumberOfSlices > 1;
9723
9724 // Check (1).
9725 if (NumberOfSlices != 2)
9726 return false;
9727
9728 // Check (2).
9729 if (!areUsedBitsDense(UsedBits))
9730 return false;
9731
9732 // Check (3).
9733 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9734 // The original code has one big load.
9735 OrigCost.Loads = 1;
9736 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9737 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9738 // Accumulate the cost of all the slices.
9739 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9740 GlobalSlicingCost += SliceCost;
9741
9742 // Account as cost in the original configuration the gain obtained
9743 // with the current slices.
9744 OrigCost.addSliceGain(LS);
9745 }
9746
9747 // If the target supports paired load, adjust the cost accordingly.
9748 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9749 return OrigCost > GlobalSlicingCost;
9750}
9751
9752/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9753/// operations, split it in the various pieces being extracted.
9754///
9755/// This sort of thing is introduced by SROA.
9756/// This slicing takes care not to insert overlapping loads.
9757/// \pre LI is a simple load (i.e., not an atomic or volatile load).
9758bool DAGCombiner::SliceUpLoad(SDNode *N) {
9759 if (Level < AfterLegalizeDAG)
9760 return false;
9761
9762 LoadSDNode *LD = cast<LoadSDNode>(N);
9763 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9764 !LD->getValueType(0).isInteger())
9765 return false;
9766
9767 // Keep track of already used bits to detect overlapping values.
9768 // In that case, we will just abort the transformation.
9769 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9770
9771 SmallVector<LoadedSlice, 4> LoadedSlices;
9772
9773 // Check if this load is used as several smaller chunks of bits.
9774 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9775 // of computation for each trunc.
9776 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9777 UI != UIEnd; ++UI) {
9778 // Skip the uses of the chain.
9779 if (UI.getUse().getResNo() != 0)
9780 continue;
9781
9782 SDNode *User = *UI;
9783 unsigned Shift = 0;
9784
9785 // Check if this is a trunc(lshr).
9786 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9787 isa<ConstantSDNode>(User->getOperand(1))) {
9788 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9789 User = *User->use_begin();
9790 }
9791
9792 // At this point, User is a Truncate, iff we encountered, trunc or
9793 // trunc(lshr).
9794 if (User->getOpcode() != ISD::TRUNCATE)
9795 return false;
9796
9797 // The width of the type must be a power of 2 and greater than 8-bits.
9798 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00009799 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00009800 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009801 unsigned Width = User->getValueSizeInBits(0);
9802 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9803 return 0;
9804
9805 // Build the slice for this chain of computations.
9806 LoadedSlice LS(User, LD, Shift, &DAG);
9807 APInt CurrentUsedBits = LS.getUsedBits();
9808
9809 // Check if this slice overlaps with another.
9810 if ((CurrentUsedBits & UsedBits) != 0)
9811 return false;
9812 // Update the bits used globally.
9813 UsedBits |= CurrentUsedBits;
9814
9815 // Check if the new slice would be legal.
9816 if (!LS.isLegal())
9817 return false;
9818
9819 // Record the slice.
9820 LoadedSlices.push_back(LS);
9821 }
9822
9823 // Abort slicing if it does not seem to be profitable.
9824 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9825 return false;
9826
9827 ++SlicedLoads;
9828
9829 // Rewrite each chain to use an independent load.
9830 // By construction, each chain can be represented by a unique load.
9831
9832 // Prepare the argument for the new token factor for all the slices.
9833 SmallVector<SDValue, 8> ArgChains;
9834 for (SmallVectorImpl<LoadedSlice>::const_iterator
9835 LSIt = LoadedSlices.begin(),
9836 LSItEnd = LoadedSlices.end();
9837 LSIt != LSItEnd; ++LSIt) {
9838 SDValue SliceInst = LSIt->loadSlice();
9839 CombineTo(LSIt->Inst, SliceInst, true);
9840 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9841 SliceInst = SliceInst.getOperand(0);
9842 assert(SliceInst->getOpcode() == ISD::LOAD &&
9843 "It takes more than a zext to get to the loaded slice!!");
9844 ArgChains.push_back(SliceInst.getValue(1));
9845 }
9846
9847 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00009848 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00009849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9850 return true;
9851}
9852
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009853/// Check to see if V is (and load (ptr), imm), where the load is having
9854/// specific bytes cleared out. If so, return the byte size being masked out
9855/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00009856static std::pair<unsigned, unsigned>
9857CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9858 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009859
Chris Lattner4041ab62010-04-15 04:48:01 +00009860 // Check for the structure we're looking for.
9861 if (V->getOpcode() != ISD::AND ||
9862 !isa<ConstantSDNode>(V->getOperand(1)) ||
9863 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9864 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009865
Chris Lattner3245afd2010-04-15 06:10:49 +00009866 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00009867 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00009868 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00009869
Chris Lattner3245afd2010-04-15 06:10:49 +00009870 // The store should be chained directly to the load or be an operand of a
9871 // tokenfactor.
9872 if (LD == Chain.getNode())
9873 ; // ok.
9874 else if (Chain->getOpcode() != ISD::TokenFactor)
9875 return Result; // Fail.
9876 else {
9877 bool isOk = false;
9878 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9879 if (Chain->getOperand(i).getNode() == LD) {
9880 isOk = true;
9881 break;
9882 }
9883 if (!isOk) return Result;
9884 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009885
Chris Lattner4041ab62010-04-15 04:48:01 +00009886 // This only handles simple types.
9887 if (V.getValueType() != MVT::i16 &&
9888 V.getValueType() != MVT::i32 &&
9889 V.getValueType() != MVT::i64)
9890 return Result;
9891
9892 // Check the constant mask. Invert it so that the bits being masked out are
9893 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9894 // follow the sign bit for uniformity.
9895 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009896 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009897 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009898 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009899 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9900 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00009901
Chris Lattner4041ab62010-04-15 04:48:01 +00009902 // See if we have a continuous run of bits. If so, we have 0*1+0*
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00009903 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
Chris Lattner4041ab62010-04-15 04:48:01 +00009904 return Result;
9905
9906 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9907 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9908 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00009909
Chris Lattner4041ab62010-04-15 04:48:01 +00009910 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9911 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00009912 case 1:
9913 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00009914 case 4: break;
9915 default: return Result; // All one mask, or 5-byte mask.
9916 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009917
Chris Lattner4041ab62010-04-15 04:48:01 +00009918 // Verify that the first bit starts at a multiple of mask so that the access
9919 // is aligned the same as the access width.
9920 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009921
Chris Lattner4041ab62010-04-15 04:48:01 +00009922 Result.first = MaskedBytes;
9923 Result.second = NotMaskTZ/8;
9924 return Result;
9925}
9926
9927
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009928/// Check to see if IVal is something that provides a value as specified by
9929/// MaskInfo. If so, replace the specified store with a narrower store of
9930/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00009931static SDNode *
9932ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9933 SDValue IVal, StoreSDNode *St,
9934 DAGCombiner *DC) {
9935 unsigned NumBytes = MaskInfo.first;
9936 unsigned ByteShift = MaskInfo.second;
9937 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00009938
Chris Lattner4041ab62010-04-15 04:48:01 +00009939 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9940 // that uses this. If not, this is not a replacement.
9941 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9942 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00009943 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009944
Chris Lattner4041ab62010-04-15 04:48:01 +00009945 // Check that it is legal on the target to do this. It is legal if the new
9946 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9947 // legalization.
9948 MVT VT = MVT::getIntegerVT(NumBytes*8);
9949 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00009950 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009951
Chris Lattner4041ab62010-04-15 04:48:01 +00009952 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9953 // shifted by ByteShift and truncated down to NumBytes.
9954 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009955 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00009956 DAG.getConstant(ByteShift*8,
9957 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00009958
9959 // Figure out the offset for the store and the alignment of the access.
9960 unsigned StOffset;
9961 unsigned NewAlign = St->getAlignment();
9962
9963 if (DAG.getTargetLoweringInfo().isLittleEndian())
9964 StOffset = ByteShift;
9965 else
9966 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00009967
Chris Lattner4041ab62010-04-15 04:48:01 +00009968 SDValue Ptr = St->getBasePtr();
9969 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009970 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00009971 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9972 NewAlign = MinAlign(NewAlign, StOffset);
9973 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009974
Chris Lattner4041ab62010-04-15 04:48:01 +00009975 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009976 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00009977
Chris Lattner4041ab62010-04-15 04:48:01 +00009978 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009979 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00009980 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00009981 false, false, NewAlign).getNode();
9982}
9983
Evan Chenga9cda8a2009-05-28 00:35:15 +00009984
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009985/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9986/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9987/// narrowing the load and store if it would end up being a win for performance
9988/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009989SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9990 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00009991 if (ST->isVolatile())
9992 return SDValue();
9993
Evan Chenga9cda8a2009-05-28 00:35:15 +00009994 SDValue Chain = ST->getChain();
9995 SDValue Value = ST->getValue();
9996 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009997 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009998
9999 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +000010000 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010001
10002 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +000010003
Chris Lattner4041ab62010-04-15 04:48:01 +000010004 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10005 // is a byte mask indicating a consecutive number of bytes, check to see if
10006 // Y is known to provide just those bytes. If so, we try to replace the
10007 // load + replace + store sequence with a single (narrower) store, which makes
10008 // the load dead.
10009 if (Opc == ISD::OR) {
10010 std::pair<unsigned, unsigned> MaskedLoad;
10011 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10012 if (MaskedLoad.first)
10013 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10014 Value.getOperand(1), ST,this))
10015 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +000010016
Chris Lattner4041ab62010-04-15 04:48:01 +000010017 // Or is commutative, so try swapping X and Y.
10018 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10019 if (MaskedLoad.first)
10020 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10021 Value.getOperand(0), ST,this))
10022 return SDValue(NewST, 0);
10023 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010024
Evan Chenga9cda8a2009-05-28 00:35:15 +000010025 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10026 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +000010027 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010028
10029 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +000010030 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10031 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +000010032 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010033 if (LD->getBasePtr() != Ptr ||
10034 LD->getPointerInfo().getAddrSpace() !=
10035 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +000010036 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010037
10038 // Find the type to narrow it the load / op / store to.
10039 SDValue N1 = Value.getOperand(1);
10040 unsigned BitWidth = N1.getValueSizeInBits();
10041 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10042 if (Opc == ISD::AND)
10043 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +000010044 if (Imm == 0 || Imm.isAllOnesValue())
10045 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010046 unsigned ShAmt = Imm.countTrailingZeros();
10047 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10048 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +000010049 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Elena Demikhovsky150d9f32015-01-22 12:07:59 +000010050 // The narrowing should be profitable, the load/store operation should be
Elena Demikhovsky9c264622015-01-22 09:39:08 +000010051 // legal (or custom) and the store size should be equal to the NewVT width.
Evan Chenga9cda8a2009-05-28 00:35:15 +000010052 while (NewBW < BitWidth &&
Elena Demikhovsky9c264622015-01-22 09:39:08 +000010053 (NewVT.getStoreSizeInBits() != NewBW ||
10054 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10055 !TLI.isNarrowingProfitable(VT, NewVT))) {
Evan Chenga9cda8a2009-05-28 00:35:15 +000010056 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +000010057 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +000010058 }
Evan Cheng6673ff02009-05-28 18:41:02 +000010059 if (NewBW >= BitWidth)
10060 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010061
10062 // If the lsb changed does not start at the type bitwidth boundary,
10063 // start at the previous one.
10064 if (ShAmt % NewBW)
10065 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +000010066 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10067 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +000010068 if ((Imm & Mask) == Imm) {
10069 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10070 if (Opc == ISD::AND)
10071 NewImm ^= APInt::getAllOnesValue(NewBW);
10072 uint64_t PtrOff = ShAmt / 8;
10073 // For big endian targets, we need to adjust the offset to the pointer to
10074 // load the correct bytes.
10075 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +000010076 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +000010077
10078 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +000010079 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010080 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +000010081 return SDValue();
10082
Andrew Trickef9de2a2013-05-25 02:42:55 +000010083 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010084 Ptr.getValueType(), Ptr,
10085 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010086 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010087 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010088 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +000010089 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010090 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010091 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010092 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +000010093 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010094 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010095 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010096 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +000010097 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +000010098
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010099 AddToWorklist(NewPtr.getNode());
10100 AddToWorklist(NewLD.getNode());
10101 AddToWorklist(NewVal.getNode());
10102 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +000010103 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +000010104 ++OpsNarrowed;
10105 return NewST;
10106 }
10107 }
10108
Evan Cheng6673ff02009-05-28 18:41:02 +000010109 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010110}
10111
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010112/// For a given floating point load / store pair, if the load value isn't used
10113/// by any other operations, then consider transforming the pair to integer
10114/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +000010115SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10116 StoreSDNode *ST = cast<StoreSDNode>(N);
10117 SDValue Chain = ST->getChain();
10118 SDValue Value = ST->getValue();
10119 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10120 Value.hasOneUse() &&
10121 Chain == SDValue(Value.getNode(), 1)) {
10122 LoadSDNode *LD = cast<LoadSDNode>(Value);
10123 EVT VT = LD->getMemoryVT();
10124 if (!VT.isFloatingPoint() ||
10125 VT != ST->getMemoryVT() ||
10126 LD->isNonTemporal() ||
10127 ST->isNonTemporal() ||
10128 LD->getPointerInfo().getAddrSpace() != 0 ||
10129 ST->getPointerInfo().getAddrSpace() != 0)
10130 return SDValue();
10131
10132 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10133 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10134 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10135 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10136 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10137 return SDValue();
10138
10139 unsigned LDAlign = LD->getAlignment();
10140 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +000010141 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010142 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +000010143 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10144 return SDValue();
10145
Andrew Trickef9de2a2013-05-25 02:42:55 +000010146 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +000010147 LD->getChain(), LD->getBasePtr(),
10148 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010149 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +000010150
Andrew Trickef9de2a2013-05-25 02:42:55 +000010151 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +000010152 NewLD, ST->getBasePtr(),
10153 ST->getPointerInfo(),
10154 false, false, STAlign);
10155
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010156 AddToWorklist(NewLD.getNode());
10157 AddToWorklist(NewST.getNode());
10158 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +000010159 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +000010160 ++LdStFP2Int;
10161 return NewST;
10162 }
10163
10164 return SDValue();
10165}
10166
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010167namespace {
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010168/// Helper struct to parse and store a memory address as base + index + offset.
10169/// We ignore sign extensions when it is safe to do so.
10170/// The following two expressions are not equivalent. To differentiate we need
10171/// to store whether there was a sign extension involved in the index
10172/// computation.
10173/// (load (i64 add (i64 copyfromreg %c)
10174/// (i64 signextend (add (i8 load %index)
10175/// (i8 1))))
10176/// vs
10177///
10178/// (load (i64 add (i64 copyfromreg %c)
10179/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10180/// (i32 1)))))
10181struct BaseIndexOffset {
10182 SDValue Base;
10183 SDValue Index;
10184 int64_t Offset;
10185 bool IsIndexSignExt;
10186
10187 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10188
10189 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10190 bool IsIndexSignExt) :
10191 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10192
10193 bool equalBaseIndex(const BaseIndexOffset &Other) {
10194 return Other.Base == Base && Other.Index == Index &&
10195 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010196 }
10197
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010198 /// Parses tree in Ptr for base, index, offset addresses.
10199 static BaseIndexOffset match(SDValue Ptr) {
10200 bool IsIndexSignExt = false;
10201
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010202 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10203 // instruction, then it could be just the BASE or everything else we don't
10204 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010205 if (Ptr->getOpcode() != ISD::ADD)
10206 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10207
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010208 // We know that we have at least an ADD instruction. Try to pattern match
10209 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010210 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10211 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10212 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10213 IsIndexSignExt);
10214 }
10215
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010216 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010217 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010218 // (i64 add (i64 %array_ptr)
10219 // (i64 mul (i64 %induction_var)
10220 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010221 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010222 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010223
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010224 // Look at Base + Index + Offset cases.
10225 SDValue Base = Ptr->getOperand(0);
10226 SDValue IndexOffset = Ptr->getOperand(1);
10227
10228 // Skip signextends.
10229 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10230 IndexOffset = IndexOffset->getOperand(0);
10231 IsIndexSignExt = true;
10232 }
10233
10234 // Either the case of Base + Index (no offset) or something else.
10235 if (IndexOffset->getOpcode() != ISD::ADD)
10236 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10237
10238 // Now we have the case of Base + Index + offset.
10239 SDValue Index = IndexOffset->getOperand(0);
10240 SDValue Offset = IndexOffset->getOperand(1);
10241
10242 if (!isa<ConstantSDNode>(Offset))
10243 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10244
10245 // Ignore signextends.
10246 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10247 Index = Index->getOperand(0);
10248 IsIndexSignExt = true;
10249 } else IsIndexSignExt = false;
10250
10251 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10252 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10253 }
10254};
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010255} // namespace
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010256
Sanjay Patel37c41c12015-01-22 18:21:26 +000010257bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10258 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
Quentin Colombet308b1712015-01-27 23:58:01 +000010259 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010260 // Make sure we have something to merge.
Quentin Colombet308b1712015-01-27 23:58:01 +000010261 if (NumElem < 2)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010262 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010263
Sanjay Patel37c41c12015-01-22 18:21:26 +000010264 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10265 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
Akira Hatanakac6fab802015-04-08 20:34:53 +000010266 unsigned LatestNodeUsed = 0;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010267
Quentin Colombet308b1712015-01-27 23:58:01 +000010268 for (unsigned i=0; i < NumElem; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010269 // Find a chain for the new wide-store operand. Notice that some
10270 // of the store nodes that we found may not be selected for inclusion
10271 // in the wide store. The chain we use needs to be the chain of the
Akira Hatanakac6fab802015-04-08 20:34:53 +000010272 // latest store node which is *used* and replaced by the wide store.
10273 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10274 LatestNodeUsed = i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010275 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010276
Akira Hatanakac6fab802015-04-08 20:34:53 +000010277 // The latest Node in the DAG.
10278 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010279 SDLoc DL(StoreNodes[0].MemNode);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010280
Sanjay Patel37c41c12015-01-22 18:21:26 +000010281 SDValue StoredVal;
10282 if (UseVector) {
Quentin Colombet308b1712015-01-27 23:58:01 +000010283 // Find a legal type for the vector store.
10284 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010285 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10286 if (IsConstantSrc) {
10287 // A vector store with a constant source implies that the constant is
10288 // zero; we only handle merging stores of constant zeros because the zero
10289 // can be materialized without a load.
10290 // It may be beneficial to loosen this restriction to allow non-zero
10291 // store merging.
10292 StoredVal = DAG.getConstant(0, Ty);
10293 } else {
10294 SmallVector<SDValue, 8> Ops;
Quentin Colombet308b1712015-01-27 23:58:01 +000010295 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010296 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10297 SDValue Val = St->getValue();
Quentin Colombet308b1712015-01-27 23:58:01 +000010298 // All of the operands of a BUILD_VECTOR must have the same type.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010299 if (Val.getValueType() != MemVT)
10300 return false;
10301 Ops.push_back(Val);
10302 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010303
Sanjay Patel37c41c12015-01-22 18:21:26 +000010304 // Build the extracted vector elements back into a vector.
Quentin Colombet308b1712015-01-27 23:58:01 +000010305 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010306 }
10307 } else {
10308 // We should always use a vector store when merging extracted vector
10309 // elements, so this path implies a store of constants.
10310 assert(IsConstantSrc && "Merged vector elements should use vector store");
10311
Quentin Colombet308b1712015-01-27 23:58:01 +000010312 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010313 APInt StoreInt(StoreBW, 0);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010314
Sanjay Patel37c41c12015-01-22 18:21:26 +000010315 // Construct a single integer constant which is made of the smaller
10316 // constant inputs.
10317 bool IsLE = TLI.isLittleEndian();
Quentin Colombet308b1712015-01-27 23:58:01 +000010318 for (unsigned i = 0; i < NumElem ; ++i) {
10319 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010320 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10321 SDValue Val = St->getValue();
10322 StoreInt <<= ElementSizeBytes*8;
10323 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10324 StoreInt |= C->getAPIntValue().zext(StoreBW);
10325 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10326 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10327 } else {
10328 llvm_unreachable("Invalid constant element type");
10329 }
10330 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010331
Sanjay Patel37c41c12015-01-22 18:21:26 +000010332 // Create the new Load and Store operations.
10333 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10334 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10335 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010336
Akira Hatanakac6fab802015-04-08 20:34:53 +000010337 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010338 FirstInChain->getBasePtr(),
10339 FirstInChain->getPointerInfo(),
10340 false, false,
10341 FirstInChain->getAlignment());
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010342
Akira Hatanakac6fab802015-04-08 20:34:53 +000010343 // Replace the last store with the new store
10344 CombineTo(LatestOp, NewStore);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010345 // Erase all other stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010346 for (unsigned i = 0; i < NumElem ; ++i) {
Akira Hatanakac6fab802015-04-08 20:34:53 +000010347 if (StoreNodes[i].MemNode == LatestOp)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010348 continue;
10349 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10350 // ReplaceAllUsesWith will replace all uses that existed when it was
10351 // called, but graph optimizations may cause new ones to appear. For
10352 // example, the case in pr14333 looks like
10353 //
10354 // St's chain -> St -> another store -> X
10355 //
10356 // And the only difference from St to the other store is the chain.
10357 // When we change it's chain to be St's chain they become identical,
10358 // get CSEed and the net result is that X is now a use of St.
10359 // Since we know that St is redundant, just iterate.
10360 while (!St->use_empty())
10361 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10362 deleteAndRecombine(St);
10363 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010364
Sanjay Patel37c41c12015-01-22 18:21:26 +000010365 return true;
10366}
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010367
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010368bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
Paul Robinson093d6e12015-02-26 18:47:57 +000010369 if (OptLevel == CodeGenOpt::None)
10370 return false;
10371
Quentin Colombet308b1712015-01-27 23:58:01 +000010372 EVT MemVT = St->getMemoryVT();
10373 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +000010374 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10375 Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010376
Quentin Colombet308b1712015-01-27 23:58:01 +000010377 // Don't merge vectors into wider inputs.
10378 if (MemVT.isVector() || !MemVT.isSimple())
10379 return false;
10380
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010381 // Perform an early exit check. Do not bother looking at stored values that
Sanjay Patel37c41c12015-01-22 18:21:26 +000010382 // are not constants, loads, or extracted vector elements.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010383 SDValue StoredVal = St->getValue();
10384 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010385 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10386 isa<ConstantFPSDNode>(StoredVal);
Quentin Colombet308b1712015-01-27 23:58:01 +000010387 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010388
Quentin Colombet308b1712015-01-27 23:58:01 +000010389 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010390 return false;
10391
10392 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +000010393 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010394 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10395 return false;
10396
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010397 // This holds the base pointer, index, and the offset in bytes from the base
10398 // pointer.
10399 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010400
10401 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010402 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010403 return false;
10404
10405 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010406 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010407 return false;
10408
Nadav Rotem307d7672012-11-29 00:00:08 +000010409 // Save the LoadSDNodes that we find in the chain.
10410 // We need to make sure that these nodes do not interfere with
10411 // any of the store nodes.
10412 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10413
10414 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010415 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +000010416
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010417 // Walk up the chain and look for nodes with offsets from the same
10418 // base pointer. Stop when reaching an instruction with a different kind
10419 // or instruction which has a different base pointer.
10420 unsigned Seq = 0;
10421 StoreSDNode *Index = St;
10422 while (Index) {
10423 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +000010424 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010425 break;
10426
10427 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010428 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010429
10430 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010431 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010432 break;
10433
10434 // Check that the alignment is the same.
10435 if (Index->getAlignment() != St->getAlignment())
10436 break;
10437
10438 // The memory operands must not be volatile.
10439 if (Index->isVolatile() || Index->isIndexed())
10440 break;
10441
10442 // No truncation.
10443 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10444 if (St->isTruncatingStore())
10445 break;
10446
10447 // The stored memory type must be the same.
10448 if (Index->getMemoryVT() != MemVT)
10449 break;
10450
10451 // We do not allow unaligned stores because we want to prevent overriding
10452 // stores.
10453 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10454 break;
10455
10456 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010457 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010458
Nadav Rotem307d7672012-11-29 00:00:08 +000010459 // Find the next memory operand in the chain. If the next operand in the
10460 // chain is a store then move up and continue the scan with the next
10461 // memory operand. If the next operand is a load save it and use alias
10462 // information to check if it interferes with anything.
10463 SDNode *NextInChain = Index->getChain().getNode();
10464 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +000010465 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +000010466 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +000010467 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +000010468 break;
10469 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +000010470 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +000010471 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +000010472 break;
10473 }
10474
Nadav Rotem307d7672012-11-29 00:00:08 +000010475 // Save the load node for later. Continue the scan.
10476 AliasLoadNodes.push_back(Ldn);
10477 NextInChain = Ldn->getChain().getNode();
10478 continue;
10479 } else {
Craig Topperc0196b12014-04-14 00:51:57 +000010480 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +000010481 break;
10482 }
10483 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010484 }
10485
10486 // Check if there is anything to merge.
10487 if (StoreNodes.size() < 2)
10488 return false;
10489
10490 // Sort the memory operands according to their distance from the base pointer.
10491 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +000010492 [](MemOpLink LHS, MemOpLink RHS) {
10493 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10494 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10495 LHS.SequenceNum > RHS.SequenceNum);
10496 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010497
10498 // Scan the memory operations on the chain and find the first non-consecutive
10499 // store memory address.
10500 unsigned LastConsecutiveStore = 0;
10501 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +000010502 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10503
10504 // Check that the addresses are consecutive starting from the second
10505 // element in the list of stores.
10506 if (i > 0) {
10507 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10508 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10509 break;
10510 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010511
Nadav Rotem307d7672012-11-29 00:00:08 +000010512 bool Alias = false;
10513 // Check if this store interferes with any of the loads that we found.
10514 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10515 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10516 Alias = true;
10517 break;
10518 }
Nadav Rotem307d7672012-11-29 00:00:08 +000010519 // We found a load that alias with this store. Stop the sequence.
10520 if (Alias)
10521 break;
10522
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010523 // Mark this node as useful.
10524 LastConsecutiveStore = i;
10525 }
10526
10527 // The node with the lowest store address.
10528 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10529
10530 // Store the constants into memory as one consecutive store.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010531 if (IsConstantSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010532 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010533 unsigned LastLegalVectorType = 0;
10534 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010535 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10536 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10537 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010538
10539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010540 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010541 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010542 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010543 } else {
Alp Tokerf907b892013-12-05 05:44:44 +000010544 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010545 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010546 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010547
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010548 // Find a legal type for the constant store.
10549 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10550 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10551 if (TLI.isTypeLegal(StoreTy))
10552 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010553 // Or check whether a truncstore is legal.
10554 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10555 TargetLowering::TypePromoteInteger) {
10556 EVT LegalizedStoredValueTy =
10557 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10558 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10559 LastLegalType = i+1;
10560 }
Nadav Rotemb27777f2012-10-04 22:35:15 +000010561
10562 // Find a legal type for the vector store.
10563 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10564 if (TLI.isTypeLegal(Ty))
10565 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010566 }
10567
Bob Wilson3365b802012-12-20 01:36:20 +000010568 // We only use vectors if the constant is known to be zero and the
10569 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010570 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +000010571 LastLegalVectorType = 0;
10572
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010573 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +000010574 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010575 return false;
10576
Nadav Rotem495b1a42013-02-14 18:28:52 +000010577 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010578 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10579
Sanjay Patel37c41c12015-01-22 18:21:26 +000010580 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10581 true, UseVector);
10582 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010583
Sanjay Patel37c41c12015-01-22 18:21:26 +000010584 // When extracting multiple vector elements, try to store them
10585 // in one vector store rather than a sequence of scalar stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010586 if (IsExtractVecEltSrc) {
10587 unsigned NumElem = 0;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010588 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10589 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Quentin Colombet308b1712015-01-27 23:58:01 +000010590 SDValue StoredVal = St->getValue();
Sanjay Patel37c41c12015-01-22 18:21:26 +000010591 // This restriction could be loosened.
10592 // Bail out if any stored values are not elements extracted from a vector.
10593 // It should be possible to handle mixed sources, but load sources need
10594 // more careful handling (see the block of code below that handles
10595 // consecutive loads).
Quentin Colombet308b1712015-01-27 23:58:01 +000010596 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010597 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010598
Nadav Rotemb27777f2012-10-04 22:35:15 +000010599 // Find a legal type for the vector store.
Quentin Colombet308b1712015-01-27 23:58:01 +000010600 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10601 if (TLI.isTypeLegal(Ty))
10602 NumElem = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010603 }
10604
Quentin Colombet308b1712015-01-27 23:58:01 +000010605 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010606 false, true);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010607 }
10608
10609 // Below we handle the case of multiple consecutive stores that
10610 // come from multiple consecutive loads. We merge them into a single
10611 // wide load and a single wide store.
10612
10613 // Look for load nodes which are used by the stored values.
10614 SmallVector<MemOpLink, 8> LoadNodes;
10615
10616 // Find acceptable loads. Loads need to have the same chain (token factor),
10617 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010618 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010619 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10620 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10621 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10622 if (!Ld) break;
10623
10624 // Loads must only have one use.
10625 if (!Ld->hasNUsesOfValue(1, 0))
10626 break;
10627
10628 // Check that the alignment is the same as the stores.
10629 if (Ld->getAlignment() != St->getAlignment())
10630 break;
10631
10632 // The memory operands must not be volatile.
10633 if (Ld->isVolatile() || Ld->isIndexed())
10634 break;
10635
10636 // We do not accept ext loads.
10637 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10638 break;
10639
10640 // The stored memory type must be the same.
10641 if (Ld->getMemoryVT() != MemVT)
10642 break;
10643
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010644 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010645 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010646 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010647 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010648 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010649 break;
10650 } else {
10651 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010652 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010653 }
10654
10655 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010656 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010657 }
10658
10659 if (LoadNodes.size() < 2)
10660 return false;
10661
James Molloyce45be02014-08-02 14:51:24 +000010662 // If we have load/store pair instructions and we only have two values,
10663 // don't bother.
10664 unsigned RequiredAlignment;
10665 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10666 St->getAlignment() >= RequiredAlignment)
10667 return false;
10668
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010669 // Scan the memory operations on the chain and find the first non-consecutive
10670 // load memory address. These variables hold the index in the store node
10671 // array.
10672 unsigned LastConsecutiveLoad = 0;
10673 // This variable refers to the size and not index in the array.
10674 unsigned LastLegalVectorType = 0;
10675 unsigned LastLegalIntegerType = 0;
10676 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +000010677 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10678 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10679 // All loads much share the same chain.
10680 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10681 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +000010682
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010683 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10684 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10685 break;
10686 LastConsecutiveLoad = i;
10687
10688 // Find a legal type for the vector store.
10689 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10690 if (TLI.isTypeLegal(StoreTy))
10691 LastLegalVectorType = i + 1;
10692
10693 // Find a legal type for the integer store.
10694 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10695 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10696 if (TLI.isTypeLegal(StoreTy))
10697 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010698 // Or check whether a truncstore and extload is legal.
10699 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10700 TargetLowering::TypePromoteInteger) {
10701 EVT LegalizedStoredValueTy =
10702 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10703 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010704 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10705 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10706 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010707 LastLegalIntegerType = i+1;
10708 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010709 }
10710
10711 // Only use vector types if the vector type is larger than the integer type.
10712 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010713 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010714 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10715
10716 // We add +1 here because the LastXXX variables refer to location while
10717 // the NumElem refers to array/index size.
10718 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10719 NumElem = std::min(LastLegalType, NumElem);
10720
10721 if (NumElem < 2)
10722 return false;
10723
Akira Hatanakac6fab802015-04-08 20:34:53 +000010724 // The latest Node in the DAG.
10725 unsigned LatestNodeUsed = 0;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010726 for (unsigned i=1; i<NumElem; ++i) {
10727 // Find a chain for the new wide-store operand. Notice that some
10728 // of the store nodes that we found may not be selected for inclusion
10729 // in the wide store. The chain we use needs to be the chain of the
Akira Hatanakac6fab802015-04-08 20:34:53 +000010730 // latest store node which is *used* and replaced by the wide store.
10731 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10732 LatestNodeUsed = i;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010733 }
10734
Akira Hatanakac6fab802015-04-08 20:34:53 +000010735 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10736
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010737 // Find if it is better to use vectors or integers to load and store
10738 // to memory.
10739 EVT JointMemOpVT;
10740 if (UseVectorTy) {
10741 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10742 } else {
10743 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10744 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10745 }
10746
Andrew Trickef9de2a2013-05-25 02:42:55 +000010747 SDLoc LoadDL(LoadNodes[0].MemNode);
10748 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010749
10750 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10751 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10752 FirstLoad->getChain(),
10753 FirstLoad->getBasePtr(),
10754 FirstLoad->getPointerInfo(),
10755 false, false, false,
10756 FirstLoad->getAlignment());
10757
Akira Hatanakac6fab802015-04-08 20:34:53 +000010758 SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010759 FirstInChain->getBasePtr(),
10760 FirstInChain->getPointerInfo(), false, false,
10761 FirstInChain->getAlignment());
10762
Nadav Rotemac920662012-10-03 19:30:31 +000010763 // Replace one of the loads with the new load.
10764 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10765 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10766 SDValue(NewLoad.getNode(), 1));
10767
10768 // Remove the rest of the load chains.
10769 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010770 // Replace all chain users of the old load nodes with the chain of the new
10771 // load node.
10772 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +000010773 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10774 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010775
Akira Hatanakac6fab802015-04-08 20:34:53 +000010776 // Replace the last store with the new store.
10777 CombineTo(LatestOp, NewStore);
Nadav Rotemac920662012-10-03 19:30:31 +000010778 // Erase all other stores.
10779 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010780 // Remove all Store nodes.
Akira Hatanakac6fab802015-04-08 20:34:53 +000010781 if (StoreNodes[i].MemNode == LatestOp)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010782 continue;
10783 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10784 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +000010785 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010786 }
10787
10788 return true;
10789}
10790
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010791SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +000010792 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010793 SDValue Chain = ST->getChain();
10794 SDValue Value = ST->getValue();
10795 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010796
Evan Chenga4cf58a2007-05-07 21:27:48 +000010797 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +000010798 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +000010799 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010800 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +000010801 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010802 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010803 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +000010804 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +000010805 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010806 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +000010807 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010808 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +000010809 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010810 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010811 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +000010812 }
Owen Andersona5192842011-04-14 17:30:49 +000010813
Chris Lattner41c80e82011-04-09 02:32:02 +000010814 // Turn 'store undef, Ptr' -> nothing.
10815 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10816 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +000010817
Nate Begeman8e20c762006-12-11 02:23:46 +000010818 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +000010819 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +000010820 // NOTE: If the original store is volatile, this transform must not increase
10821 // the number of stores. For example, on x86-32 an f64 can be stored in one
10822 // processor operation but an i64 (which is not legal) requires two. So the
10823 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +000010824 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010825 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +000010826 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +000010827 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +000010828 case MVT::f16: // We don't do this for these yet.
10829 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +000010830 case MVT::f128:
10831 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +000010832 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010833 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +000010834 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010835 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +000010836 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +000010837 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010838 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010839 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000010840 }
10841 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010842 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000010843 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000010844 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010845 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +000010846 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +000010847 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010848 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010849 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000010850 }
Owen Andersona5192842011-04-14 17:30:49 +000010851
Chris Lattner41c80e82011-04-09 02:32:02 +000010852 if (!ST->isVolatile() &&
10853 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000010854 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000010855 // argument passing. Since this is so common, custom legalize the
10856 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000010857 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +000010858 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10859 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000010860 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010861
Dan Gohman2af30632007-07-09 22:18:38 +000010862 unsigned Alignment = ST->getAlignment();
10863 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000010864 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000010865 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000010866
Andrew Trickef9de2a2013-05-25 02:42:55 +000010867 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000010868 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000010869 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010870 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010871 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +000010872 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000010873 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010874 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000010875 Ptr, ST->getPointerInfo().getWithOffset(4),
10876 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010877 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010878 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000010879 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010880 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010881
Chris Lattnerb7524b62006-12-12 04:16:14 +000010882 break;
Evan Cheng21836982006-12-11 17:25:19 +000010883 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010884 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010885 }
10886
Evan Cheng43cd9e32010-04-01 06:04:33 +000010887 // Try to infer better alignment information than the store already has.
10888 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000010889 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersondb420122015-03-19 22:48:57 +000010890 if (Align > ST->getAlignment()) {
10891 SDValue NewStore =
10892 DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000010893 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010894 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000010895 ST->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +000010896 if (NewStore.getNode() != N)
10897 return CombineTo(ST, NewStore, true);
10898 }
Evan Cheng43cd9e32010-04-01 06:04:33 +000010899 }
10900 }
10901
Evan Chengd42641c2011-02-02 01:06:55 +000010902 // Try transforming a pair floating point load / store ops to integer
10903 // load / store ops.
10904 SDValue NewST = TransformFPLoadStorePair(N);
10905 if (NewST.getNode())
10906 return NewST;
10907
Eric Christopherf55d4712014-10-08 23:38:39 +000010908 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10909 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000010910#ifndef NDEBUG
10911 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10912 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10913 UseAA = false;
10914#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000010915 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000010916 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010917 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010918
Jim Laskey708d0db2006-10-04 16:53:27 +000010919 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000010920 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010921 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000010922
10923 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010924 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010925 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010926 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010927 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010928 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010929 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010930 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010931
Jim Laskeyd07be232006-09-25 16:29:54 +000010932 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010933 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000010934 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010935
Nate Begeman879d8f12009-09-15 00:18:30 +000010936 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010937 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000010938
Jim Laskeydcf983c2006-10-13 23:32:28 +000010939 // Don't add users to work list.
10940 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000010941 }
Jim Laskey5d19d592006-09-21 16:28:59 +000010942 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010943
Evan Cheng33157702006-11-05 09:31:14 +000010944 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000010945 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010946 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000010947
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010948 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010949 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010950 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000010951 // See if we can simplify the input to this truncstore with knowledge that
10952 // only the low bits are being used. For example:
10953 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000010954 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000010955 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010956 APInt::getLowBitsSet(
10957 Value.getValueType().getScalarType().getSizeInBits(),
10958 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010959 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000010960 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010961 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010962 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000010963
Chris Lattnerf47e3062007-10-13 06:58:48 +000010964 // Otherwise, see if we can simplify the operation with
10965 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000010966 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000010967 APInt::getLowBitsSet(
10968 Value.getValueType().getScalarType().getSizeInBits(),
10969 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010970 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000010971 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010972
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010973 // If this is a load followed by a store to the same location, then the store
10974 // is dead/noop.
10975 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010976 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010977 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000010978 // There can't be any side effects between the load and store, such as
10979 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010980 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010981 // The store is dead, remove it.
10982 return Chain;
10983 }
10984 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010985
James Molloy463db9a2014-09-27 17:02:54 +000010986 // If this is a store followed by a store with the same value to the same
10987 // location, then the store is dead/noop.
10988 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10989 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10990 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10991 ST1->isUnindexed() && !ST1->isVolatile()) {
10992 // The store is dead, remove it.
10993 return Chain;
10994 }
10995 }
10996
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010997 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10998 // truncating store. We can do this even if this is already a truncstore.
10999 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011000 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011001 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000011002 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011003 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011004 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011005 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000011006
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011007 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000011008 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000011009 if (!LegalTypes) {
11010 bool EverChanged = false;
11011
11012 do {
11013 // There can be multiple store sequences on the same chain.
11014 // Keep trying to merge store sequences until we are unable to do so
11015 // or until we merge the last store on the chain.
11016 bool Changed = MergeConsecutiveStores(ST);
11017 EverChanged |= Changed;
11018 if (!Changed) break;
11019 } while (ST->getOpcode() != ISD::DELETED_NODE);
11020
11021 if (EverChanged)
11022 return SDValue(N, 0);
11023 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011024
Evan Chenga9cda8a2009-05-28 00:35:15 +000011025 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000011026}
11027
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011028SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11029 SDValue InVec = N->getOperand(0);
11030 SDValue InVal = N->getOperand(1);
11031 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011032 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011033
Bob Wilson42603952010-05-19 23:42:58 +000011034 // If the inserted element is an UNDEF, just use the input vector.
11035 if (InVal.getOpcode() == ISD::UNDEF)
11036 return InVec;
11037
Nadav Rotemdb2f5482011-02-12 14:40:33 +000011038 EVT VT = InVec.getValueType();
11039
Owen Andersonb2c80da2011-02-25 21:41:48 +000011040 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000011041 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11042 return SDValue();
11043
Eli Friedmanb7910b72011-09-09 21:04:06 +000011044 // Check that we know which element is being inserted
11045 if (!isa<ConstantSDNode>(EltNo))
11046 return SDValue();
11047 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011048
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000011049 // Canonicalize insert_vector_elt dag nodes.
11050 // Example:
11051 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11052 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11053 //
11054 // Do this only if the child insert_vector node has one use; also
11055 // do this only if indices are both constants and Idx1 < Idx0.
11056 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11057 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11058 unsigned OtherElt =
11059 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11060 if (Elt < OtherElt) {
11061 // Swap nodes.
11062 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11063 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011064 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000011065 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11066 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11067 }
11068 }
11069
Eli Friedmanb7910b72011-09-09 21:04:06 +000011070 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11071 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11072 // vector elements.
11073 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000011074 // Do not combine these two vectors if the output vector will not replace
11075 // the input vector.
11076 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000011077 Ops.append(InVec.getNode()->op_begin(),
11078 InVec.getNode()->op_end());
11079 } else if (InVec.getOpcode() == ISD::UNDEF) {
11080 unsigned NElts = VT.getVectorNumElements();
11081 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11082 } else {
11083 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011084 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000011085
11086 // Insert the element
11087 if (Elt < Ops.size()) {
11088 // All the operands of BUILD_VECTOR must have the same type;
11089 // we enforce that here.
11090 EVT OpVT = Ops[0].getValueType();
11091 if (InVal.getValueType() != OpVT)
11092 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11093 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11094 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11095 Ops[Elt] = InVal;
11096 }
11097
11098 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000011099 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000011100}
11101
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011102SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11103 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11104 EVT ResultVT = EVE->getValueType(0);
11105 EVT VecEltVT = InVecVT.getVectorElementType();
11106 unsigned Align = OriginalLoad->getAlignment();
11107 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11108 VecEltVT.getTypeForEVT(*DAG.getContext()));
11109
11110 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11111 return SDValue();
11112
11113 Align = NewAlign;
11114
11115 SDValue NewPtr = OriginalLoad->getBasePtr();
11116 SDValue Offset;
11117 EVT PtrType = NewPtr.getValueType();
11118 MachinePointerInfo MPI;
11119 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11120 int Elt = ConstEltNo->getZExtValue();
11121 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11122 if (TLI.isBigEndian())
11123 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11124 Offset = DAG.getConstant(PtrOff, PtrType);
11125 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11126 } else {
11127 Offset = DAG.getNode(
11128 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
11129 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
11130 if (TLI.isBigEndian())
11131 Offset = DAG.getNode(
11132 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
11133 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
11134 MPI = OriginalLoad->getPointerInfo();
11135 }
11136 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
11137
11138 // The replacement we need to do here is a little tricky: we need to
11139 // replace an extractelement of a load with a load.
11140 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11141 // Note that this replacement assumes that the extractvalue is the only
11142 // use of the load; that's okay because we don't want to perform this
11143 // transformation in other cases anyway.
11144 SDValue Load;
11145 SDValue Chain;
11146 if (ResultVT.bitsGT(VecEltVT)) {
11147 // If the result type of vextract is wider than the load, then issue an
11148 // extending load instead.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000011149 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11150 VecEltVT)
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011151 ? ISD::ZEXTLOAD
11152 : ISD::EXTLOAD;
11153 Load = DAG.getExtLoad(
11154 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11155 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11156 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11157 Chain = Load.getValue(1);
11158 } else {
11159 Load = DAG.getLoad(
11160 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11161 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11162 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11163 Chain = Load.getValue(1);
11164 if (ResultVT.bitsLT(VecEltVT))
11165 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11166 else
11167 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11168 }
11169 WorklistRemover DeadNodes(*this);
11170 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11171 SDValue To[] = { Load, Chain };
11172 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11173 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11174 // worklist explicitly as well.
11175 AddToWorklist(Load.getNode());
11176 AddUsersToWorklist(Load.getNode()); // Add users too
11177 // Make sure to revisit this node to clean it up; it will usually be dead.
11178 AddToWorklist(EVE);
11179 ++OpsNarrowed;
11180 return SDValue(EVE, 0);
11181}
11182
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011183SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000011184 // (vextract (scalar_to_vector val, 0) -> val
11185 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011186 EVT VT = InVec.getValueType();
11187 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000011188
Duncan Sands6be291a2011-05-09 08:03:33 +000011189 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11190 // Check if the result type doesn't match the inserted element type. A
11191 // SCALAR_TO_VECTOR may truncate the inserted element and the
11192 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11193 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000011194 if (InOp.getValueType() != NVT) {
11195 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000011196 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000011197 }
11198 return InOp;
11199 }
Evan Cheng1120279a2008-05-13 08:35:03 +000011200
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011201 SDValue EltNo = N->getOperand(1);
11202 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11203
11204 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11205 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000011206 // we may introduce new vector instructions which are not backed by TD
11207 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000011208 // without using extract_subvector. However, if we can find an underlying
11209 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011210 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000011211 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011212 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11213 int NumElem = VT.getVectorNumElements();
11214 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11215 // Find the new index to extract from.
11216 int OrigElt = SVOp->getMaskElt(Elt);
11217
11218 // Extracting an undef index is undef.
11219 if (OrigElt == -1)
11220 return DAG.getUNDEF(NVT);
11221
11222 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000011223 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011224 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000011225 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011226 } else {
Hal Finkel02807592014-03-31 11:43:19 +000011227 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011228 OrigElt -= NumElem;
11229 }
11230
Hal Finkel02807592014-03-31 11:43:19 +000011231 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11232 SDValue InOp = SVInVec.getOperand(OrigElt);
11233 if (InOp.getValueType() != NVT) {
11234 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11235 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11236 }
11237
11238 return InOp;
11239 }
11240
11241 // FIXME: We should handle recursing on other vector shuffles and
11242 // scalar_to_vector here as well.
11243
11244 if (!LegalOperations) {
11245 EVT IndexTy = TLI.getVectorIdxTy();
11246 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11247 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11248 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011249 }
11250
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011251 bool BCNumEltsChanged = false;
11252 EVT ExtVT = VT.getVectorElementType();
11253 EVT LVT = ExtVT;
11254
11255 // If the result of load has to be truncated, then it's not necessarily
11256 // profitable.
11257 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11258 return SDValue();
11259
11260 if (InVec.getOpcode() == ISD::BITCAST) {
11261 // Don't duplicate a load with other uses.
11262 if (!InVec.hasOneUse())
11263 return SDValue();
11264
11265 EVT BCVT = InVec.getOperand(0).getValueType();
11266 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11267 return SDValue();
11268 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11269 BCNumEltsChanged = true;
11270 InVec = InVec.getOperand(0);
11271 ExtVT = BCVT.getVectorElementType();
11272 }
11273
11274 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11275 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11276 ISD::isNormalLoad(InVec.getNode()) &&
11277 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11278 SDValue Index = N->getOperand(1);
11279 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11280 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11281 OrigLoad);
11282 }
11283
Evan Cheng1120279a2008-05-13 08:35:03 +000011284 // Perform only after legalization to ensure build_vector / vector_shuffle
11285 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011286 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011287
Mon P Wangca6d6de2009-01-17 00:07:25 +000011288 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11289 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11290 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000011291
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011292 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000011293 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011294
Craig Topperc0196b12014-04-14 00:51:57 +000011295 LoadSDNode *LN0 = nullptr;
11296 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000011297 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011298 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000011299 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000011300 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000011301 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000011302 // Don't duplicate a load with other uses.
11303 if (!InVec.hasOneUse())
11304 return SDValue();
11305
Evan Cheng1120279a2008-05-13 08:35:03 +000011306 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000011307 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011308 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11309 // =>
11310 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000011311
Eli Friedmane96286c2011-12-26 22:49:32 +000011312 // Don't duplicate a load with other uses.
11313 if (!InVec.hasOneUse())
11314 return SDValue();
11315
Mon P Wangb5eb7202008-12-11 00:26:16 +000011316 // If the bit convert changed the number of elements, it is unsafe
11317 // to examine the mask.
11318 if (BCNumEltsChanged)
11319 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000011320
11321 // Select the input vector, guarding against out of range extract vector.
11322 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000011323 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000011324 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11325
Eli Friedmane96286c2011-12-26 22:49:32 +000011326 if (InVec.getOpcode() == ISD::BITCAST) {
11327 // Don't duplicate a load with other uses.
11328 if (!InVec.hasOneUse())
11329 return SDValue();
11330
Evan Cheng1120279a2008-05-13 08:35:03 +000011331 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000011332 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000011333 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011334 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000011335 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011336 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000011337 }
11338 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011339
Eli Friedmane96286c2011-12-26 22:49:32 +000011340 // Make sure we found a non-volatile load and the extractelement is
11341 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000011342 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011343 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011344
Eric Christopherc6418b12010-11-03 20:44:42 +000011345 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11346 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000011347 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000011348
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011349 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000011350 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011351
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011352 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011353}
Evan Cheng0de312d2007-10-06 08:19:55 +000011354
Michael Liao6d106b72012-10-23 23:06:52 +000011355// Simplify (build_vec (ext )) to (bitcast (build_vec ))
11356SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11357 // We perform this optimization post type-legalization because
11358 // the type-legalizer often scalarizes integer-promoted vectors.
11359 // Performing this optimization before may create bit-casts which
11360 // will be type-legalized to complex code sequences.
11361 // We perform this optimization only before the operation legalizer because we
11362 // may introduce illegal operations.
11363 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11364 return SDValue();
11365
Dan Gohmana8665142007-06-25 16:23:39 +000011366 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011367 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000011368 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011369
Nadav Rotembf6568b2011-10-29 21:23:04 +000011370 // Check to see if this is a BUILD_VECTOR of a bunch of values
11371 // which come from any_extend or zero_extend nodes. If so, we can create
11372 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000011373 // optimizations. We do not handle sign-extend because we can't fill the sign
11374 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011375 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000011376 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000011377
Craig Topper02cb0fb2012-01-17 09:09:48 +000011378 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000011379 SDValue In = N->getOperand(i);
11380 // Ignore undef inputs.
11381 if (In.getOpcode() == ISD::UNDEF) continue;
11382
11383 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11384 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11385
Nadav Rotemf3103612011-10-31 20:08:25 +000011386 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011387 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000011388 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011389 break;
11390 }
11391
11392 // The input is a ZeroExt or AnyExt. Check the original type.
11393 EVT InTy = In.getOperand(0).getValueType();
11394
11395 // Check that all of the widened source types are the same.
11396 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000011397 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011398 SourceType = InTy;
11399 else if (InTy != SourceType) {
11400 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000011401 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011402 break;
11403 }
11404
11405 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000011406 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011407 }
11408
Nadav Rotemf3103612011-10-31 20:08:25 +000011409 // In order to have valid types, all of the inputs must be extended from the
11410 // same source type and all of the inputs must be any or zero extend.
11411 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000011412 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011413 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000011414 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11415 isPowerOf2_32(SourceType.getSizeInBits());
11416
Nadav Rotem6fd1d322012-03-15 08:49:06 +000011417 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11418 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000011419 if (!ValidTypes)
11420 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000011421
Michael Liao6d106b72012-10-23 23:06:52 +000011422 bool isLE = TLI.isLittleEndian();
11423 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11424 assert(ElemRatio > 1 && "Invalid element size ratio");
11425 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11426 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011427
Michael Liao6d106b72012-10-23 23:06:52 +000011428 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11429 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011430
Michael Liao6d106b72012-10-23 23:06:52 +000011431 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000011432 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000011433 SDValue Cast = N->getOperand(i);
11434 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11435 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11436 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11437 SDValue In;
11438 if (Cast.getOpcode() == ISD::UNDEF)
11439 In = DAG.getUNDEF(SourceType);
11440 else
11441 In = Cast->getOperand(0);
11442 unsigned Index = isLE ? (i * ElemRatio) :
11443 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000011444
Michael Liao6d106b72012-10-23 23:06:52 +000011445 assert(Index < Ops.size() && "Invalid index");
11446 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011447 }
Chris Lattner5336a592006-03-19 01:27:56 +000011448
Michael Liao6d106b72012-10-23 23:06:52 +000011449 // The type of the new BUILD_VECTOR node.
11450 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11451 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11452 "Invalid vector size");
11453 // Check if the new vector type is legal.
11454 if (!isTypeLegal(VecVT)) return SDValue();
11455
11456 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000011457 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000011458
11459 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011460 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000011461 // Bitcast to the desired type.
11462 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11463}
11464
Michael Liao59229792012-10-24 04:14:18 +000011465SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11466 EVT VT = N->getValueType(0);
11467
11468 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011469 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000011470
11471 EVT SrcVT = MVT::Other;
11472 unsigned Opcode = ISD::DELETED_NODE;
11473 unsigned NumDefs = 0;
11474
11475 for (unsigned i = 0; i != NumInScalars; ++i) {
11476 SDValue In = N->getOperand(i);
11477 unsigned Opc = In.getOpcode();
11478
11479 if (Opc == ISD::UNDEF)
11480 continue;
11481
11482 // If all scalar values are floats and converted from integers.
11483 if (Opcode == ISD::DELETED_NODE &&
11484 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11485 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000011486 }
Tom Stellard567f8862013-01-02 22:13:01 +000011487
Michael Liao59229792012-10-24 04:14:18 +000011488 if (Opc != Opcode)
11489 return SDValue();
11490
11491 EVT InVT = In.getOperand(0).getValueType();
11492
11493 // If all scalar values are typed differently, bail out. It's chosen to
11494 // simplify BUILD_VECTOR of integer types.
11495 if (SrcVT == MVT::Other)
11496 SrcVT = InVT;
11497 if (SrcVT != InVT)
11498 return SDValue();
11499 NumDefs++;
11500 }
11501
11502 // If the vector has just one element defined, it's not worth to fold it into
11503 // a vectorized one.
11504 if (NumDefs < 2)
11505 return SDValue();
11506
11507 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11508 && "Should only handle conversion from integer to float.");
11509 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11510
11511 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000011512
11513 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11514 return SDValue();
11515
Hal Finkele2dd84e2015-02-22 16:10:22 +000011516 // Just because the floating-point vector type is legal does not necessarily
11517 // mean that the corresponding integer vector type is.
11518 if (!isTypeLegal(NVT))
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011519 return SDValue();
Hal Finkele2dd84e2015-02-22 16:10:22 +000011520
Michael Liao59229792012-10-24 04:14:18 +000011521 SmallVector<SDValue, 8> Opnds;
11522 for (unsigned i = 0; i != NumInScalars; ++i) {
11523 SDValue In = N->getOperand(i);
11524
11525 if (In.getOpcode() == ISD::UNDEF)
11526 Opnds.push_back(DAG.getUNDEF(SrcVT));
11527 else
11528 Opnds.push_back(In.getOperand(0));
11529 }
Craig Topper48d114b2014-04-26 18:35:24 +000011530 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011531 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000011532
11533 return DAG.getNode(Opcode, dl, VT, BV);
11534}
11535
Michael Liao6d106b72012-10-23 23:06:52 +000011536SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11537 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011538 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000011539 EVT VT = N->getValueType(0);
11540
11541 // A vector built entirely of undefs is undef.
11542 if (ISD::allOperandsUndef(N))
11543 return DAG.getUNDEF(VT);
11544
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011545 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
Michael Liao6d106b72012-10-23 23:06:52 +000011546 return V;
11547
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011548 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
Michael Liao59229792012-10-24 04:14:18 +000011549 return V;
11550
Dan Gohmana8665142007-06-25 16:23:39 +000011551 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11552 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11553 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011554
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000011555 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11556 if (!isTypeLegal(VT))
11557 return SDValue();
11558
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011559 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000011560 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011561 return SDValue();
11562
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011563 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011564 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000011565 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011566 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000011567 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011568 if (Op.getOpcode() == ISD::UNDEF) continue;
11569
11570 // See if we can combine this build_vector into a blend with a zero vector.
11571 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11572 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11573 (Op.getOpcode() == ISD::ConstantFP &&
11574 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11575 UsesZeroVector = true;
11576 continue;
11577 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011578
Dan Gohmana8665142007-06-25 16:23:39 +000011579 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000011580 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011581 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11582 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000011583 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011584 break;
11585 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011586
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011587 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011588 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011589 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11590 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011591
Craig Topperc0196b12014-04-14 00:51:57 +000011592 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011593 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011594 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011595 VecIn2 = ExtractedFromVec;
11596 } else {
11597 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000011598 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011599 break;
11600 }
11601 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011602
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000011603 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011604 if (VecIn1.getNode()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011605 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011606 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000011607 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011608 unsigned Opcode = N->getOperand(i).getOpcode();
11609 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011610 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000011611 continue;
11612 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011613
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011614 // Operands can also be zero.
11615 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11616 assert(UsesZeroVector &&
11617 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11618 "Unexpected node found!");
11619 Mask.push_back(NumInScalars+i);
11620 continue;
11621 }
11622
Rafael Espindolab93db662009-04-24 12:40:33 +000011623 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011624 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000011625 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011626 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011627 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000011628 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011629 continue;
11630 }
11631
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011632 // Otherwise, use InIdx + InputVecSize
11633 Mask.push_back(InNumElements + ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011634 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011635
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011636 // Avoid introducing illegal shuffles with zero.
11637 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11638 return SDValue();
11639
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011640 // We can't generate a shuffle node with mismatched input and output types.
11641 // Attempt to transform a single input vector to the correct type.
11642 if ((VT != VecIn1.getValueType())) {
James Molloy1e5c6112012-09-10 14:01:21 +000011643 // If the input vector type has a different base type to the output
11644 // vector type, bail out.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011645 EVT VTElemType = VT.getVectorElementType();
11646 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11647 (VecIn2.getNode() &&
11648 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
James Molloy1e5c6112012-09-10 14:01:21 +000011649 return SDValue();
11650
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011651 // If the input vector is too small, widen it.
11652 // We only support widening of vectors which are half the size of the
11653 // output registers. For example XMM->YMM widening on X86 with AVX.
11654 EVT VecInT = VecIn1.getValueType();
11655 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011656 // If we only have one small input, widen it by adding undef values.
11657 if (!VecIn2.getNode())
11658 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11659 DAG.getUNDEF(VecIn1.getValueType()));
11660 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11661 // If we have two small inputs of the same type, try to concat them.
11662 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11663 VecIn2 = SDValue(nullptr, 0);
11664 } else
11665 return SDValue();
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011666 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11667 // If the input vector is too large, try to split it.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011668 // We don't support having two input vectors that are too large.
Michael Kupersteinfb956972015-03-04 07:27:39 +000011669 // If the zero vector was used, we can not split the vector,
11670 // since we'd need 3 inputs.
11671 if (UsesZeroVector || VecIn2.getNode())
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011672 return SDValue();
11673
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011674 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11675 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011676
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011677 // Try to replace VecIn1 with two extract_subvectors
11678 // No need to update the masks, they should still be correct.
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011679 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011680 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11681 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11682 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011683 } else
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011684 return SDValue();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011685 }
11686
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011687 if (UsesZeroVector)
11688 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11689 DAG.getConstantFP(0.0, VT);
11690 else
11691 // If VecIn2 is unused then change it to undef.
11692 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011693
Nadav Rotem841c9a82012-09-20 08:53:31 +000011694 // Check that we were able to transform all incoming values to the same
11695 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000011696 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11697 VecIn1.getValueType() != VT)
11698 return SDValue();
11699
Dan Gohmana8665142007-06-25 16:23:39 +000011700 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011701 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000011702 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011703 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000011704 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000011705 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011706
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011707 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011708}
11709
Ahmed Bougachac984b902015-04-16 02:39:14 +000011710static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11712 EVT OpVT = N->getOperand(0).getValueType();
11713
11714 // If the operands are legal vectors, leave them alone.
11715 if (TLI.isTypeLegal(OpVT))
11716 return SDValue();
11717
11718 SDLoc DL(N);
11719 EVT VT = N->getValueType(0);
11720 SmallVector<SDValue, 8> Ops;
11721
11722 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11723 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11724
11725 // Keep track of what we encounter.
11726 bool AnyInteger = false;
11727 bool AnyFP = false;
11728 for (const SDValue &Op : N->ops()) {
11729 if (ISD::BITCAST == Op.getOpcode() &&
11730 !Op.getOperand(0).getValueType().isVector())
11731 Ops.push_back(Op.getOperand(0));
11732 else if (ISD::UNDEF == Op.getOpcode())
11733 Ops.push_back(ScalarUndef);
11734 else
11735 return SDValue();
11736
11737 // Note whether we encounter an integer or floating point scalar.
11738 // If it's neither, bail out, it could be something weird like x86mmx.
11739 EVT LastOpVT = Ops.back().getValueType();
11740 if (LastOpVT.isFloatingPoint())
11741 AnyFP = true;
11742 else if (LastOpVT.isInteger())
11743 AnyInteger = true;
11744 else
11745 return SDValue();
11746 }
11747
11748 // If any of the operands is a floating point scalar bitcast to a vector,
11749 // use floating point types throughout, and bitcast everything.
11750 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11751 if (AnyFP) {
11752 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11753 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11754 if (AnyInteger) {
11755 for (SDValue &Op : Ops) {
11756 if (Op.getValueType() == SVT)
11757 continue;
11758 if (Op.getOpcode() == ISD::UNDEF)
11759 Op = ScalarUndef;
11760 else
11761 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11762 }
11763 }
11764 }
11765
11766 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11767 VT.getSizeInBits() / SVT.getSizeInBits());
11768 return DAG.getNode(ISD::BITCAST, DL, VT,
11769 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11770}
11771
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011772SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000011773 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11774 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11775 // inputs come from at most two distinct vectors, turn this into a shuffle
11776 // node.
11777
11778 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000011779 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000011780 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011781
Nadav Rotem01892102012-07-14 21:30:27 +000011782 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011783 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011784 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011785 return DAG.getUNDEF(VT);
11786
Ahmed Bougachadf437372015-04-09 20:04:47 +000011787 // Optimize concat_vectors where all but the first of the vectors are undef.
11788 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11789 return Op.getOpcode() == ISD::UNDEF;
11790 })) {
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011791 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000011792 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011793
11794 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11795 if (In->getOpcode() == ISD::BITCAST &&
11796 !In->getOperand(0)->getValueType(0).isVector()) {
11797 SDValue Scalar = In->getOperand(0);
Ahmed Bougachadf437372015-04-09 20:04:47 +000011798
11799 // If the bitcast type isn't legal, it might be a trunc of a legal type;
11800 // look through the trunc so we can still do the transform:
11801 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11802 if (Scalar->getOpcode() == ISD::TRUNCATE &&
11803 !TLI.isTypeLegal(Scalar.getValueType()) &&
11804 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11805 Scalar = Scalar->getOperand(0);
11806
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011807 EVT SclTy = Scalar->getValueType(0);
11808
11809 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11810 return SDValue();
11811
11812 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11813 VT.getSizeInBits() / SclTy.getSizeInBits());
11814 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11815 return SDValue();
11816
11817 SDLoc dl = SDLoc(N);
11818 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11819 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11820 }
11821 }
Nadav Rotem01892102012-07-14 21:30:27 +000011822
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011823 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11824 // We have already tested above for an UNDEF only concatenation.
Robert Lougher7d9084f2014-02-11 15:42:46 +000011825 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11826 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011827 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11828 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11829 };
11830 bool AllBuildVectorsOrUndefs =
11831 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11832 if (AllBuildVectorsOrUndefs) {
Robert Lougher7d9084f2014-02-11 15:42:46 +000011833 SmallVector<SDValue, 8> Opnds;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011834 EVT SVT = VT.getScalarType();
Robert Lougher7d9084f2014-02-11 15:42:46 +000011835
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011836 EVT MinVT = SVT;
11837 if (!SVT.isFloatingPoint()) {
Hao Liu71224b02014-07-10 03:41:50 +000011838 // If BUILD_VECTOR are from built from integer, they may have different
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011839 // operand types. Get the smallest type and truncate all operands to it.
11840 bool FoundMinVT = false;
11841 for (const SDValue &Op : N->ops())
11842 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11843 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11844 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11845 FoundMinVT = true;
11846 }
11847 assert(FoundMinVT && "Concat vector type mismatch");
Hao Liu71224b02014-07-10 03:41:50 +000011848 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000011849
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011850 for (const SDValue &Op : N->ops()) {
11851 EVT OpVT = Op.getValueType();
11852 unsigned NumElts = OpVT.getVectorNumElements();
11853
11854 if (ISD::UNDEF == Op.getOpcode())
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000011855 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011856
11857 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11858 if (SVT.isFloatingPoint()) {
11859 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000011860 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011861 } else {
11862 for (unsigned i = 0; i != NumElts; ++i)
11863 Opnds.push_back(
11864 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11865 }
11866 }
11867 }
11868
11869 assert(VT.getVectorNumElements() == Opnds.size() &&
11870 "Concat vector type mismatch");
Craig Topper48d114b2014-04-26 18:35:24 +000011871 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000011872 }
11873
Ahmed Bougachac984b902015-04-16 02:39:14 +000011874 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
11875 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
11876 return V;
11877
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011878 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11879 // nodes often generate nop CONCAT_VECTOR nodes.
11880 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11881 // place the incoming vectors at the exact same location.
11882 SDValue SingleSource = SDValue();
11883 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11884
11885 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11886 SDValue Op = N->getOperand(i);
11887
11888 if (Op.getOpcode() == ISD::UNDEF)
11889 continue;
11890
11891 // Check if this is the identity extract:
11892 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11893 return SDValue();
11894
11895 // Find the single incoming vector for the extract_subvector.
11896 if (SingleSource.getNode()) {
11897 if (Op.getOperand(0) != SingleSource)
11898 return SDValue();
11899 } else {
11900 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000011901
11902 // Check the source type is the same as the type of the result.
11903 // If not, this concat may extend the vector, so we can not
11904 // optimize it away.
11905 if (SingleSource.getValueType() != N->getValueType(0))
11906 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011907 }
11908
11909 unsigned IdentityIndex = i * PartNumElem;
11910 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11911 // The extract index must be constant.
11912 if (!CS)
11913 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000011914
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011915 // Check that we are reading from the identity index.
11916 if (CS->getZExtValue() != IdentityIndex)
11917 return SDValue();
11918 }
11919
11920 if (SingleSource.getNode())
11921 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000011922
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011923 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000011924}
11925
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011926SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11927 EVT NVT = N->getValueType(0);
11928 SDValue V = N->getOperand(0);
11929
Michael Liao7a442c802012-10-17 20:48:33 +000011930 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11931 // Combine:
11932 // (extract_subvec (concat V1, V2, ...), i)
11933 // Into:
11934 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000011935 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11936 // type.
Michael Liao2c235802012-10-19 03:17:00 +000011937 if (V->getOperand(0).getValueType() != NVT)
11938 return SDValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +000011939 unsigned Idx = N->getConstantOperandVal(1);
Michael Liao7a442c802012-10-17 20:48:33 +000011940 unsigned NumElems = NVT.getVectorNumElements();
11941 assert((Idx % NumElems) == 0 &&
11942 "IDX in concat is not a multiple of the result vector length.");
11943 return V->getOperand(Idx / NumElems);
11944 }
11945
Michael Liaobb05a1d2013-03-25 23:47:35 +000011946 // Skip bitcasting
11947 if (V->getOpcode() == ISD::BITCAST)
11948 V = V.getOperand(0);
11949
11950 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011951 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000011952 // Handle only simple case where vector being inserted and vector
11953 // being extracted are of same type, and are half size of larger vectors.
11954 EVT BigVT = V->getOperand(0).getValueType();
11955 EVT SmallVT = V->getOperand(1).getValueType();
11956 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11957 return SDValue();
11958
11959 // Only handle cases where both indexes are constants with the same type.
11960 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11961 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11962
11963 if (InsIdx && ExtIdx &&
11964 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11965 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11966 // Combine:
11967 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11968 // Into:
11969 // indices are equal or bit offsets are equal => V1
11970 // otherwise => (extract_subvec V1, ExtIdx)
11971 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11972 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11973 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11974 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11975 DAG.getNode(ISD::BITCAST, dl,
11976 N->getOperand(0).getValueType(),
11977 V->getOperand(0)), N->getOperand(1));
11978 }
11979 }
11980
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011981 return SDValue();
11982}
11983
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011984static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11985 SDValue V, SelectionDAG &DAG) {
11986 SDLoc DL(V);
11987 EVT VT = V.getValueType();
11988
11989 switch (V.getOpcode()) {
11990 default:
11991 return V;
11992
11993 case ISD::CONCAT_VECTORS: {
11994 EVT OpVT = V->getOperand(0).getValueType();
11995 int OpSize = OpVT.getVectorNumElements();
11996 SmallBitVector OpUsedElements(OpSize, false);
11997 bool FoundSimplification = false;
11998 SmallVector<SDValue, 4> NewOps;
11999 NewOps.reserve(V->getNumOperands());
12000 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12001 SDValue Op = V->getOperand(i);
12002 bool OpUsed = false;
12003 for (int j = 0; j < OpSize; ++j)
12004 if (UsedElements[i * OpSize + j]) {
12005 OpUsedElements[j] = true;
12006 OpUsed = true;
12007 }
12008 NewOps.push_back(
12009 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12010 : DAG.getUNDEF(OpVT));
12011 FoundSimplification |= Op == NewOps.back();
12012 OpUsedElements.reset();
12013 }
12014 if (FoundSimplification)
12015 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12016 return V;
12017 }
12018
12019 case ISD::INSERT_SUBVECTOR: {
12020 SDValue BaseV = V->getOperand(0);
12021 SDValue SubV = V->getOperand(1);
12022 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12023 if (!IdxN)
12024 return V;
12025
12026 int SubSize = SubV.getValueType().getVectorNumElements();
12027 int Idx = IdxN->getZExtValue();
12028 bool SubVectorUsed = false;
12029 SmallBitVector SubUsedElements(SubSize, false);
12030 for (int i = 0; i < SubSize; ++i)
12031 if (UsedElements[i + Idx]) {
12032 SubVectorUsed = true;
12033 SubUsedElements[i] = true;
12034 UsedElements[i + Idx] = false;
12035 }
12036
12037 // Now recurse on both the base and sub vectors.
12038 SDValue SimplifiedSubV =
12039 SubVectorUsed
12040 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12041 : DAG.getUNDEF(SubV.getValueType());
12042 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12043 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12044 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12045 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12046 return V;
12047 }
12048 }
12049}
12050
12051static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12052 SDValue N1, SelectionDAG &DAG) {
12053 EVT VT = SVN->getValueType(0);
12054 int NumElts = VT.getVectorNumElements();
12055 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12056 for (int M : SVN->getMask())
12057 if (M >= 0 && M < NumElts)
12058 N0UsedElements[M] = true;
12059 else if (M >= NumElts)
12060 N1UsedElements[M - NumElts] = true;
12061
12062 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12063 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12064 if (S0 == N0 && S1 == N1)
12065 return SDValue();
12066
12067 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12068}
12069
Mehdi Amini37f316a2015-01-17 01:35:56 +000012070// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12071// or turn a shuffle of a single concat into simpler shuffle then concat.
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012072static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12073 EVT VT = N->getValueType(0);
12074 unsigned NumElts = VT.getVectorNumElements();
12075
12076 SDValue N0 = N->getOperand(0);
12077 SDValue N1 = N->getOperand(1);
12078 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12079
12080 SmallVector<SDValue, 4> Ops;
12081 EVT ConcatVT = N0.getOperand(0).getValueType();
12082 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12083 unsigned NumConcats = NumElts / NumElemsPerConcat;
12084
Mehdi Amini37f316a2015-01-17 01:35:56 +000012085 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12086 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12087 // half vector elements.
12088 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12089 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12090 SVN->getMask().end(), [](int i) { return i == -1; })) {
12091 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12092 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12093 N1 = DAG.getUNDEF(ConcatVT);
12094 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12095 }
12096
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012097 // Look at every vector that's inserted. We're looking for exact
12098 // subvector-sized copies from a concatenated vector
12099 for (unsigned I = 0; I != NumConcats; ++I) {
12100 // Make sure we're dealing with a copy.
12101 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000012102 bool AllUndef = true, NoUndef = true;
12103 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12104 if (SVN->getMaskElt(J) >= 0)
12105 AllUndef = false;
12106 else
12107 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012108 }
12109
Hao Liubc601962013-05-13 02:07:05 +000012110 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000012111 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12112 return SDValue();
12113
12114 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12115 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12116 return SDValue();
12117
12118 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12119 if (FirstElt < N0.getNumOperands())
12120 Ops.push_back(N0.getOperand(FirstElt));
12121 else
12122 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12123
12124 } else if (AllUndef) {
12125 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12126 } else { // Mixed with general masks and undefs, can't do optimization.
12127 return SDValue();
12128 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012129 }
12130
Craig Topper48d114b2014-04-26 18:35:24 +000012131 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012132}
12133
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012134SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012135 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012136 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012137
Mon P Wang25f01062008-11-10 04:46:22 +000012138 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000012139 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000012140
Craig Topper5894fe42012-04-09 05:16:56 +000012141 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000012142
Craig Topper279c77b2012-01-04 08:07:43 +000012143 // Canonicalize shuffle undef, undef -> undef
12144 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12145 return DAG.getUNDEF(VT);
12146
12147 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12148
12149 // Canonicalize shuffle v, v -> v, undef
12150 if (N0 == N1) {
12151 SmallVector<int, 8> NewMask;
12152 for (unsigned i = 0; i != NumElts; ++i) {
12153 int Idx = SVN->getMaskElt(i);
12154 if (Idx >= (int)NumElts) Idx -= NumElts;
12155 NewMask.push_back(Idx);
12156 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012157 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000012158 &NewMask[0]);
12159 }
12160
12161 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12162 if (N0.getOpcode() == ISD::UNDEF) {
12163 SmallVector<int, 8> NewMask;
12164 for (unsigned i = 0; i != NumElts; ++i) {
12165 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000012166 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000012167 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000012168 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000012169 else
12170 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000012171 }
12172 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000012173 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012174 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000012175 &NewMask[0]);
12176 }
12177
12178 // Remove references to rhs if it is undef
12179 if (N1.getOpcode() == ISD::UNDEF) {
12180 bool Changed = false;
12181 SmallVector<int, 8> NewMask;
12182 for (unsigned i = 0; i != NumElts; ++i) {
12183 int Idx = SVN->getMaskElt(i);
12184 if (Idx >= (int)NumElts) {
12185 Idx = -1;
12186 Changed = true;
12187 }
12188 NewMask.push_back(Idx);
12189 }
12190 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000012191 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000012192 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000012193
Bob Wilsonf63da122010-10-28 17:06:14 +000012194 // If it is a splat, check if the argument vector is another splat or a
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012195 // build_vector.
Bob Wilsonf63da122010-10-28 17:06:14 +000012196 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000012197 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000012198
Dan Gohmana8665142007-06-25 16:23:39 +000012199 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000012200 // not the number of vector elements, look through it. Be careful not to
12201 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000012202 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012203 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000012204 if (ConvInput.getValueType().isVector() &&
12205 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000012206 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000012207 }
12208
Dan Gohmana8665142007-06-25 16:23:39 +000012209 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000012210 assert(V->getNumOperands() == NumElts &&
12211 "BUILD_VECTOR has wrong number of operands");
12212 SDValue Base;
12213 bool AllSame = true;
12214 for (unsigned i = 0; i != NumElts; ++i) {
12215 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12216 Base = V->getOperand(i);
12217 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000012218 }
Evan Cheng7c970b92006-07-21 08:25:53 +000012219 }
Bob Wilsonf63da122010-10-28 17:06:14 +000012220 // Splat of <u, u, u, u>, return <u, u, u, u>
12221 if (!Base.getNode())
12222 return N0;
12223 for (unsigned i = 0; i != NumElts; ++i) {
12224 if (V->getOperand(i) != Base) {
12225 AllSame = false;
12226 break;
12227 }
12228 }
12229 // Splat of <x, x, x, x>, return <x, x, x, x>
12230 if (AllSame)
12231 return N0;
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012232
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012233 // Canonicalize any other splat as a build_vector.
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012234 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012235 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12236 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12237 V->getValueType(0), Ops);
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012238
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012239 // We may have jumped through bitcasts, so the type of the
12240 // BUILD_VECTOR may not match the type of the shuffle.
12241 if (V->getValueType(0) != VT)
Sanjay Pateld95dd9e2015-03-26 16:55:17 +000012242 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012243 return NewBV;
Evan Cheng7c970b92006-07-21 08:25:53 +000012244 }
12245 }
Nadav Rotemb0783502012-04-01 19:31:22 +000012246
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000012247 // There are various patterns used to build up a vector from smaller vectors,
12248 // subvectors, or elements. Scan chains of these and replace unused insertions
12249 // or components with undef.
12250 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12251 return S;
12252
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012253 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12254 Level < AfterLegalizeVectorOps &&
12255 (N1.getOpcode() == ISD::UNDEF ||
12256 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12257 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12258 SDValue V = partitionShuffleOfConcats(N, DAG);
12259
12260 if (V.getNode())
12261 return V;
12262 }
12263
Simon Pilgrimed2ba33ba2015-04-03 10:02:21 +000012264 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12265 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12266 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12267 SmallVector<SDValue, 8> Ops;
12268 for (int M : SVN->getMask()) {
12269 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12270 if (M >= 0) {
12271 int Idx = M % NumElts;
12272 SDValue &S = (M < (int)NumElts ? N0 : N1);
12273 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12274 Op = S.getOperand(Idx);
12275 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12276 if (Idx == 0)
12277 Op = S.getOperand(0);
12278 } else {
12279 // Operand can't be combined - bail out.
12280 break;
12281 }
12282 }
12283 Ops.push_back(Op);
12284 }
12285 if (Ops.size() == VT.getVectorNumElements()) {
12286 // BUILD_VECTOR requires all inputs to be of the same type, find the
12287 // maximum type and extend them all.
12288 EVT SVT = VT.getScalarType();
12289 if (SVT.isInteger())
12290 for (SDValue &Op : Ops)
12291 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12292 if (SVT != VT.getScalarType())
12293 for (SDValue &Op : Ops)
12294 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12295 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12296 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12297 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12298 }
12299 }
12300
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012301 // If this shuffle only has a single input that is a bitcasted shuffle,
12302 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12303 // back to their original types.
12304 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12305 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12306 TLI.isTypeLegal(VT)) {
12307
12308 // Peek through the bitcast only if there is one user.
12309 SDValue BC0 = N0;
12310 while (BC0.getOpcode() == ISD::BITCAST) {
12311 if (!BC0.hasOneUse())
12312 break;
12313 BC0 = BC0.getOperand(0);
12314 }
12315
12316 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12317 if (Scale == 1)
12318 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12319
12320 SmallVector<int, 8> NewMask;
12321 for (int M : Mask)
12322 for (int s = 0; s != Scale; ++s)
12323 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12324 return NewMask;
12325 };
12326
12327 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12328 EVT SVT = VT.getScalarType();
12329 EVT InnerVT = BC0->getValueType(0);
12330 EVT InnerSVT = InnerVT.getScalarType();
12331
12332 // Determine which shuffle works with the smaller scalar type.
12333 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12334 EVT ScaleSVT = ScaleVT.getScalarType();
12335
12336 if (TLI.isTypeLegal(ScaleVT) &&
12337 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12338 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12339
12340 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12341 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12342
12343 // Scale the shuffle masks to the smaller scalar type.
12344 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12345 SmallVector<int, 8> InnerMask =
12346 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12347 SmallVector<int, 8> OuterMask =
12348 ScaleShuffleMask(SVN->getMask(), OuterScale);
12349
12350 // Merge the shuffle masks.
12351 SmallVector<int, 8> NewMask;
12352 for (int M : OuterMask)
12353 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12354
12355 // Test for shuffle mask legality over both commutations.
12356 SDValue SV0 = BC0->getOperand(0);
12357 SDValue SV1 = BC0->getOperand(1);
12358 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12359 if (!LegalMask) {
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012360 std::swap(SV0, SV1);
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012361 ShuffleVectorSDNode::commuteMask(NewMask);
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012362 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12363 }
12364
12365 if (LegalMask) {
12366 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12367 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12368 return DAG.getNode(
12369 ISD::BITCAST, SDLoc(N), VT,
12370 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12371 }
12372 }
12373 }
12374 }
12375
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012376 // Canonicalize shuffles according to rules:
12377 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12378 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12379 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012380 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012381 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12382 TLI.isTypeLegal(VT)) {
12383 // The incoming shuffle must be of the same type as the result of the
12384 // current shuffle.
12385 assert(N1->getOperand(0).getValueType() == VT &&
12386 "Shuffle types don't match");
12387
12388 SDValue SV0 = N1->getOperand(0);
12389 SDValue SV1 = N1->getOperand(1);
12390 bool HasSameOp0 = N0 == SV0;
12391 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12392 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12393 // Commute the operands of this shuffle so that next rule
12394 // will trigger.
12395 return DAG.getCommutedVectorShuffle(*SVN);
12396 }
12397
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012398 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012399 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12400 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12401 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012402 // Don't try to fold shuffles with illegal type.
Chandler Carruth499d7332015-02-15 07:01:10 +000012403 // Only fold if this shuffle is the only user of the other shuffle.
12404 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12405 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012406 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12407
12408 // The incoming shuffle must be of the same type as the result of the
12409 // current shuffle.
12410 assert(OtherSV->getOperand(0).getValueType() == VT &&
12411 "Shuffle types don't match");
12412
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012413 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012414 SmallVector<int, 4> Mask;
12415 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12416 // operand, and SV1 as the second operand.
12417 for (unsigned i = 0; i != NumElts; ++i) {
12418 int Idx = SVN->getMaskElt(i);
12419 if (Idx < 0) {
12420 // Propagate Undef.
12421 Mask.push_back(Idx);
12422 continue;
12423 }
12424
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012425 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012426 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012427 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12428 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012429 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012430 if (Idx < 0) {
12431 // Propagate Undef.
12432 Mask.push_back(Idx);
12433 continue;
12434 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012435
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012436 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12437 : OtherSV->getOperand(1);
12438 } else {
12439 // This shuffle index references an element within N1.
12440 CurrentVec = N1;
12441 }
12442
12443 // Simple case where 'CurrentVec' is UNDEF.
12444 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12445 Mask.push_back(-1);
12446 continue;
12447 }
12448
12449 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12450 // will be the first or second operand of the combined shuffle.
12451 Idx = Idx % NumElts;
12452 if (!SV0.getNode() || SV0 == CurrentVec) {
12453 // Ok. CurrentVec is the left hand side.
12454 // Update the mask accordingly.
12455 SV0 = CurrentVec;
12456 Mask.push_back(Idx);
12457 continue;
12458 }
12459
12460 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12461 if (SV1.getNode() && SV1 != CurrentVec)
12462 return SDValue();
12463
12464 // Ok. CurrentVec is the right hand side.
12465 // Update the mask accordingly.
12466 SV1 = CurrentVec;
12467 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012468 }
12469
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000012470 // Check if all indices in Mask are Undef. In case, propagate Undef.
12471 bool isUndefMask = true;
12472 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12473 isUndefMask &= Mask[i] < 0;
12474
12475 if (isUndefMask)
12476 return DAG.getUNDEF(VT);
12477
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012478 if (!SV0.getNode())
12479 SV0 = DAG.getUNDEF(VT);
12480 if (!SV1.getNode())
12481 SV1 = DAG.getUNDEF(VT);
12482
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012483 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012484 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012485 ShuffleVectorSDNode::commuteMask(Mask);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012486
12487 if (!TLI.isShuffleMaskLegal(Mask, VT))
12488 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012489
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012490 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12491 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12492 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12493 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012494 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000012495
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012496 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12497 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12498 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12499 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012500 }
12501
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012502 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012503}
12504
Simon Pilgrimbede80a2015-03-07 05:52:42 +000012505SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12506 SDValue InVal = N->getOperand(0);
12507 EVT VT = N->getValueType(0);
12508
12509 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12510 // with a VECTOR_SHUFFLE.
12511 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12512 SDValue InVec = InVal->getOperand(0);
12513 SDValue EltNo = InVal->getOperand(1);
12514
12515 // FIXME: We could support implicit truncation if the shuffle can be
12516 // scaled to a smaller vector scalar type.
12517 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12518 if (C0 && VT == InVec.getValueType() &&
12519 VT.getScalarType() == InVal.getValueType()) {
12520 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12521 int Elt = C0->getZExtValue();
12522 NewMask[0] = Elt;
12523
12524 if (TLI.isShuffleMaskLegal(NewMask, VT))
12525 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12526 NewMask);
12527 }
12528 }
12529
12530 return SDValue();
12531}
12532
Manman Ren413a6cb2014-01-31 01:10:35 +000012533SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12534 SDValue N0 = N->getOperand(0);
12535 SDValue N2 = N->getOperand(2);
12536
12537 // If the input vector is a concatenation, and the insert replaces
12538 // one of the halves, we can optimize into a single concat_vectors.
12539 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12540 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12541 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12542 EVT VT = N->getValueType(0);
12543
12544 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12545 // (concat_vectors Z, Y)
12546 if (InsIdx == 0)
12547 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12548 N->getOperand(1), N0.getOperand(1));
12549
12550 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12551 // (concat_vectors X, Z)
12552 if (InsIdx == VT.getVectorNumElements()/2)
12553 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12554 N0.getOperand(0), N->getOperand(1));
12555 }
12556
12557 return SDValue();
12558}
12559
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +000012560SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12561 SDValue N0 = N->getOperand(0);
12562
12563 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12564 if (N0->getOpcode() == ISD::FP16_TO_FP)
12565 return N0->getOperand(0);
12566
12567 return SDValue();
12568}
12569
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012570/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12571/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000012572/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000012573/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012574SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012575 EVT VT = N->getValueType(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012576 SDValue LHS = N->getOperand(0);
12577 SDValue RHS = N->getOperand(1);
Simon Pilgrim257849f2015-03-17 22:19:08 +000012578 SDLoc dl(N);
Craig Toppere5893f62012-04-09 05:59:53 +000012579
Simon Pilgrim257849f2015-03-17 22:19:08 +000012580 // Make sure we're not running after operation legalization where it
12581 // may have custom lowered the vector shuffles.
12582 if (LegalOperations)
12583 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012584
Simon Pilgrim257849f2015-03-17 22:19:08 +000012585 if (N->getOpcode() != ISD::AND)
12586 return SDValue();
12587
12588 if (RHS.getOpcode() == ISD::BITCAST)
12589 RHS = RHS.getOperand(0);
12590
12591 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12592 SmallVector<int, 8> Indices;
12593 unsigned NumElts = RHS.getNumOperands();
12594
12595 for (unsigned i = 0; i != NumElts; ++i) {
12596 SDValue Elt = RHS.getOperand(i);
12597 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012598 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012599
Simon Pilgrim257849f2015-03-17 22:19:08 +000012600 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12601 Indices.push_back(i);
12602 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12603 Indices.push_back(NumElts+i);
12604 else
12605 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012606 }
Simon Pilgrim257849f2015-03-17 22:19:08 +000012607
12608 // Let's see if the target supports this vector_shuffle.
12609 EVT RVT = RHS.getValueType();
12610 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12611 return SDValue();
12612
12613 // Return the new VECTOR_SHUFFLE node.
12614 EVT EltVT = RVT.getVectorElementType();
12615 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12616 DAG.getConstant(0, EltVT));
12617 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12618 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12619 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12620 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000012621 }
Bill Wendling31b50992009-01-30 23:59:18 +000012622
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012623 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012624}
12625
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012626/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012627SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000012628 assert(N->getValueType(0).isVector() &&
12629 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000012630
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012631 SDValue LHS = N->getOperand(0);
12632 SDValue RHS = N->getOperand(1);
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000012633
12634 if (SDValue Shuffle = XformToShuffleWithZero(N))
12635 return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000012636
Dan Gohmana8665142007-06-25 16:23:39 +000012637 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000012638 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012639 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000012640 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000012641 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000012642 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12643 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000012644 return SDValue();
12645
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012646 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000012647 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012648 SDValue LHSOp = LHS.getOperand(i);
12649 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000012650
Evan Cheng64d28462006-05-31 06:08:35 +000012651 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000012652 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12653 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000012654 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012655 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000012656 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012657 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000012658 break;
12659 }
Bill Wendling31b50992009-01-30 23:59:18 +000012660
Bob Wilson54081442010-12-17 23:06:49 +000012661 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000012662 EVT RVT = RHSOp.getValueType();
12663 if (RVT != VT) {
12664 // Integer BUILD_VECTOR operands may have types larger than the element
12665 // size (e.g., when the element type is not legal). Prior to type
12666 // legalization, the types may not match between the two BUILD_VECTORS.
12667 // Truncate one of the operands to make them match.
12668 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012669 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012670 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012671 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012672 VT = RVT;
12673 }
12674 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012675 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000012676 LHSOp, RHSOp);
12677 if (FoldOp.getOpcode() != ISD::UNDEF &&
12678 FoldOp.getOpcode() != ISD::Constant &&
12679 FoldOp.getOpcode() != ISD::ConstantFP)
12680 break;
12681 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012682 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000012683 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012684
Bob Wilson54081442010-12-17 23:06:49 +000012685 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000012686 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000012687 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012688
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012689 // Type legalization might introduce new shuffles in the DAG.
12690 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12691 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12692 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12693 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12694 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12695 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12696 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12697 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12698
12699 if (SVN0->getMask().equals(SVN1->getMask())) {
12700 EVT VT = N->getValueType(0);
12701 SDValue UndefVector = LHS.getOperand(1);
12702 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12703 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012704 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012705 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12706 &SVN0->getMask()[0]);
12707 }
12708 }
12709
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012710 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000012711}
12712
Andrew Trickef9de2a2013-05-25 02:42:55 +000012713SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012714 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000012715 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000012716
Bill Wendling31b50992009-01-30 23:59:18 +000012717 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000012718 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000012719
Nate Begeman2042aa52005-10-08 00:29:44 +000012720 // If we got a simplified select_cc node back from SimplifySelectCC, then
12721 // break it down into a new SETCC node, and a new SELECT node, and then return
12722 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000012723 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012724 // Check to see if we got a select_cc back (to turn into setcc/select).
12725 // Otherwise, just return whatever node we got back, like fabs.
12726 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012727 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012728 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000012729 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000012730 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012731 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000012732 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12733 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000012734 }
Bill Wendling31b50992009-01-30 23:59:18 +000012735
Nate Begeman2042aa52005-10-08 00:29:44 +000012736 return SCC;
12737 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012738 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012739}
12740
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012741/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12742/// being selected between, see if we can simplify the select. Callers of this
12743/// should assume that TheSelect is deleted if this returns true. As such, they
12744/// should return the appropriate thing (e.g. the node) back to the top-level of
12745/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012746bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012747 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012748
Tom Stellard69a7b912015-04-20 19:38:27 +000012749 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12750 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12751 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12752 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12753 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12754 SDValue Sqrt = RHS;
12755 ISD::CondCode CC;
12756 SDValue CmpLHS;
12757 const ConstantFPSDNode *NegZero = nullptr;
12758
12759 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12760 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12761 CmpLHS = TheSelect->getOperand(0);
12762 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12763 } else {
12764 // SELECT or VSELECT
12765 SDValue Cmp = TheSelect->getOperand(0);
12766 if (Cmp.getOpcode() == ISD::SETCC) {
12767 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12768 CmpLHS = Cmp.getOperand(0);
12769 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12770 }
12771 }
12772 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12773 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12774 CC == ISD::SETULT || CC == ISD::SETLT)) {
12775 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12776 CombineTo(TheSelect, Sqrt);
12777 return true;
12778 }
12779 }
12780 }
Nadav Rotema49a02a2011-02-11 19:57:47 +000012781 // Cannot simplify select with vector condition
12782 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12783
Chris Lattner6c14c352005-10-18 06:04:22 +000012784 // If this is a select from two identical things, try to pull the operation
12785 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000012786 if (LHS.getOpcode() != RHS.getOpcode() ||
12787 !LHS.hasOneUse() || !RHS.hasOneUse())
12788 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012789
Chris Lattner254c4452010-09-21 15:46:59 +000012790 // If this is a load and the token chain is identical, replace the select
12791 // of two loads with a load through a select of the address to load from.
12792 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12793 // constants have been dropped into the constant pool.
12794 if (LHS.getOpcode() == ISD::LOAD) {
12795 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12796 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000012797
Chris Lattner254c4452010-09-21 15:46:59 +000012798 // Token chains must be identical.
12799 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000012800 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000012801 LLD->isVolatile() || RLD->isVolatile() ||
12802 // If this is an EXTLOAD, the VT's must match.
12803 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000012804 // If this is an EXTLOAD, the kind of extension must match.
12805 (LLD->getExtensionType() != RLD->getExtensionType() &&
12806 // The only exception is if one of the extensions is anyext.
12807 LLD->getExtensionType() != ISD::EXTLOAD &&
12808 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000012809 // FIXME: this discards src value information. This is
12810 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000012811 // both potential memory locations. Since we are discarding
12812 // src value info, don't do the transformation if the memory
12813 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000012814 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000012815 RLD->getPointerInfo().getAddrSpace() != 0 ||
12816 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12817 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000012818 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012819
Chris Lattnere3267522010-09-21 15:58:55 +000012820 // Check that the select condition doesn't reach either load. If so,
12821 // folding this will induce a cycle into the DAG. If not, this is safe to
12822 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000012823 SDValue Addr;
12824 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000012825 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12826 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12827 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12828 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000012829 // The loads must not depend on one another.
12830 if (LLD->isPredecessorOf(RLD) ||
12831 RLD->isPredecessorOf(LLD))
12832 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012833 Addr = DAG.getSelect(SDLoc(TheSelect),
12834 LLD->getBasePtr().getValueType(),
12835 TheSelect->getOperand(0), LLD->getBasePtr(),
12836 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000012837 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000012838 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12839 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12840
12841 if ((LLD->hasAnyUseOfValue(1) &&
12842 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000012843 (RLD->hasAnyUseOfValue(1) &&
12844 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000012845 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012846
Andrew Trickef9de2a2013-05-25 02:42:55 +000012847 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000012848 LLD->getBasePtr().getValueType(),
12849 TheSelect->getOperand(0),
12850 TheSelect->getOperand(1),
12851 LLD->getBasePtr(), RLD->getBasePtr(),
12852 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000012853 }
12854
Chris Lattnere3267522010-09-21 15:58:55 +000012855 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000012856 // It is safe to replace the two loads if they have different alignments,
12857 // but the new load must be the minimum (most restrictive) alignment of the
12858 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000012859 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000012860 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000012861 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12862 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012863 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000012864 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012865 LLD->getChain(), Addr, MachinePointerInfo(),
12866 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012867 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000012868 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000012869 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12870 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012871 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000012872 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000012873 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012874 LLD->getChain(), Addr, MachinePointerInfo(),
12875 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012876 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000012877 }
Chris Lattnere3267522010-09-21 15:58:55 +000012878
12879 // Users of the select now use the result of the load.
12880 CombineTo(TheSelect, Load);
12881
12882 // Users of the old loads now use the new load's chain. We know the
12883 // old-load value is dead now.
12884 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12885 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12886 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000012887 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012888
Chris Lattner6c14c352005-10-18 06:04:22 +000012889 return false;
12890}
12891
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012892/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000012893/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000012894SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012895 SDValue N2, SDValue N3,
12896 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000012897 // (x ? y : y) -> y.
12898 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000012899
Owen Anderson53aa7a92009-08-10 22:56:29 +000012900 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000012901 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12902 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12903 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012904
12905 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000012906 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000012907 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012908 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000012909 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012910
12911 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000012912 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012913 return N2;
12914 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000012915 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012916 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012917
Nate Begeman2042aa52005-10-08 00:29:44 +000012918 // Check to see if we can simplify the select into an fabs node
12919 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12920 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000012921 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012922 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12923 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12924 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12925 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000012926 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012927
Nate Begeman2042aa52005-10-08 00:29:44 +000012928 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12929 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12930 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12931 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000012932 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000012933 }
12934 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012935
Chris Lattner43d63772009-03-11 05:08:08 +000012936 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12937 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12938 // in it. This is a win when the constant is not otherwise available because
12939 // it replaces two constant pool loads with one. We only do this if the FP
12940 // type is known to be legal, because if it isn't, then we are before legalize
12941 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000012942 // messing with soft float) and if the ConstantFP is not legal, because if
12943 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000012944 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12945 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12946 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000012947 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000012948 TargetLowering::Legal &&
12949 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12950 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000012951 // If both constants have multiple uses, then we won't need to do an
12952 // extra load, they are likely around in registers for other users.
12953 (TV->hasOneUse() || FV->hasOneUse())) {
12954 Constant *Elts[] = {
12955 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12956 const_cast<ConstantFP*>(TV->getConstantFPValue())
12957 };
Chris Lattner229907c2011-07-18 04:54:35 +000012958 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000012959 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000012960
Chris Lattner43d63772009-03-11 05:08:08 +000012961 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000012962 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000012963 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12964 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000012965 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000012966
12967 // Get the offsets to the 0 and 1 element of the array so that we can
12968 // select between them.
12969 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000012970 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000012971 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000012972
Chris Lattner43d63772009-03-11 05:08:08 +000012973 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000012974 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000012975 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012976 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012977 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12978 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012979 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000012980 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000012981 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012982 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000012983 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000012984 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000012985 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000012986
12987 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012988 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012989
Nate Begeman2042aa52005-10-08 00:29:44 +000012990 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000012991 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000012992 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000012993 (N1C->isNullValue() || // (a < 0) ? b : 0
12994 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000012995 EVT XType = N0.getValueType();
12996 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000012997 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000012998 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000012999 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000013000 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
13001 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000013002 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000013003 SDValue ShCt = DAG.getConstant(ShCtV,
13004 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013005 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013006 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013007 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000013008
Duncan Sands11dd4242008-06-08 20:54:56 +000013009 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000013010 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013011 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013012 }
Bill Wendling31b50992009-01-30 23:59:18 +000013013
13014 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000013015 }
Bill Wendling31b50992009-01-30 23:59:18 +000013016
Andrew Trickef9de2a2013-05-25 02:42:55 +000013017 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013018 XType, N0,
13019 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013020 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013021 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000013022
Duncan Sands11dd4242008-06-08 20:54:56 +000013023 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000013024 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013025 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013026 }
Bill Wendling31b50992009-01-30 23:59:18 +000013027
13028 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000013029 }
13030 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013031
Owen Anderson3231d132010-09-22 22:58:22 +000013032 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13033 // where y is has a single bit set.
13034 // A plaintext description would be, we can turn the SELECT_CC into an AND
13035 // when the condition can be materialized as an all-ones register. Any
13036 // single bit-test can be materialized as an all-ones register with
13037 // shift-left and shift-right-arith.
13038 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13039 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000013040 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000013041 N2C && N2C->isNullValue()) {
13042 SDValue AndLHS = N0->getOperand(0);
13043 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13044 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13045 // Shift the tested bit over the sign bit.
13046 APInt AndMask = ConstAndRHS->getAPIntValue();
13047 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000013048 DAG.getConstant(AndMask.countLeadingZeros(),
13049 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013050 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000013051
Owen Anderson3231d132010-09-22 22:58:22 +000013052 // Now arithmetic right shift it all the way over, so the result is either
13053 // all-ones, or zero.
13054 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000013055 DAG.getConstant(AndMask.getBitWidth()-1,
13056 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013057 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000013058
Owen Anderson3231d132010-09-22 22:58:22 +000013059 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13060 }
13061 }
13062
Nate Begeman6828ed92005-10-10 21:26:48 +000013063 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000013064 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000013065 TLI.getBooleanContents(N0.getValueType()) ==
13066 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013067
Chris Lattnera083ffc2007-04-11 06:50:51 +000013068 // If the caller doesn't want us to simplify this into a zext of a compare,
13069 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000013070 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013071 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013072
Nate Begeman6828ed92005-10-10 21:26:48 +000013073 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013074 // NOTE: Don't create a SETCC if it's not legal on this target.
13075 if (!LegalOperations ||
13076 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000013077 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013078 SDValue Temp, SCC;
13079 // cast from setcc result type to select result type
13080 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000013081 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013082 N0, N1, CC);
13083 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000013084 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013085 N2.getValueType());
13086 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000013087 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013088 N2.getValueType(), SCC);
13089 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013090 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13091 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000013092 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013093 }
13094
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013095 AddToWorklist(SCC.getNode());
13096 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013097
13098 if (N2C->getAPIntValue() == 1)
13099 return Temp;
13100
13101 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000013102 return DAG.getNode(
13103 ISD::SHL, DL, N2.getValueType(), Temp,
13104 DAG.getConstant(N2C->getAPIntValue().logBase2(),
13105 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000013106 }
Nate Begeman6828ed92005-10-10 21:26:48 +000013107 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013108
Nate Begeman2042aa52005-10-08 00:29:44 +000013109 // Check to see if this is the equivalent of setcc
13110 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13111 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000013112 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000013113 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000013114 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000013115 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13116 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000013117 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000013118 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000013119 return Res;
13120 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013121
Bill Wendling31b50992009-01-30 23:59:18 +000013122 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000013123 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000013124 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000013125 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013126 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013127 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000013128 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013129 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000013130 }
Bill Wendling31b50992009-01-30 23:59:18 +000013131 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000013132 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013133 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013134 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000013135 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000013136 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000013137 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000013138 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013139 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000013140 }
Bill Wendling31b50992009-01-30 23:59:18 +000013141 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000013142 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013143 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000013144 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013145 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000013146 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000013147 }
13148 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013149
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013150 // Check to see if this is an integer abs.
13151 // select_cc setg[te] X, 0, X, -X ->
13152 // select_cc setgt X, -1, X, -X ->
13153 // select_cc setl[te] X, 0, -X, X ->
13154 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000013155 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013156 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000013157 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013158 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13159 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13160 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13161 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13162 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13163 (N1C->isOne() && CC == ISD::SETLT)) &&
13164 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13165 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13166
Owen Anderson53aa7a92009-08-10 22:56:29 +000013167 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013168 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013169 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013170 N0,
13171 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013172 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013173 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013174 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013175 AddToWorklist(Shift.getNode());
13176 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013177 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000013178 }
13179 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013180
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013181 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000013182}
13183
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013184/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000013185SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013186 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000013187 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013188 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000013189 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000013190 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000013191}
13192
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013193/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000013194/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000013195/// by a magic number.
13196/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013197SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013198 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13199 if (!C)
13200 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013201
13202 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013203 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013204 return SDValue();
13205
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000013206 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013207 SDValue S =
13208 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013209
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013210 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013211 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013212 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000013213}
13214
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013215/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13216/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000013217SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13218 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13219 if (!C)
13220 return SDValue();
13221
13222 // Avoid division by zero.
13223 if (!C->getAPIntValue())
13224 return SDValue();
13225
13226 std::vector<SDNode *> Built;
13227 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13228
13229 for (SDNode *N : Built)
13230 AddToWorklist(N);
13231 return S;
13232}
13233
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013234/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13235/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000013236/// number.
13237/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013238SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013239 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13240 if (!C)
13241 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013242
13243 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013244 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013245 return SDValue();
13246
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000013247 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013248 SDValue S =
13249 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000013250
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013251 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013252 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013253 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000013254}
13255
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013256SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13257 if (Level >= AfterLegalizeDAG)
13258 return SDValue();
13259
Sanjay Patelb67bd262014-09-21 15:19:15 +000013260 // Expose the DAG combiner to the target combiner implementations.
13261 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000013262
Sanjay Patelab7f4602014-09-30 20:44:23 +000013263 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000013264 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000013265 if (Iterations) {
13266 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13267 // For the reciprocal, we need to find the zero of the function:
13268 // F(X) = A X - 1 [which has a zero at X = 1/A]
13269 // =>
13270 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13271 // does not require additional intermediate precision]
13272 EVT VT = Op.getValueType();
13273 SDLoc DL(Op);
13274 SDValue FPOne = DAG.getConstantFP(1.0, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013275
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013276 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013277
Sanjay Patelab7f4602014-09-30 20:44:23 +000013278 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13279 for (unsigned i = 0; i < Iterations; ++i) {
13280 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13281 AddToWorklist(NewEst.getNode());
13282
13283 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13284 AddToWorklist(NewEst.getNode());
13285
13286 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13287 AddToWorklist(NewEst.getNode());
13288
13289 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13290 AddToWorklist(Est.getNode());
13291 }
13292 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013293 return Est;
13294 }
13295
13296 return SDValue();
13297}
13298
Sanjay Patel957efc232014-10-24 17:02:16 +000013299/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13300/// For the reciprocal sqrt, we need to find the zero of the function:
13301/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13302/// =>
13303/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13304/// As a result, we precompute A/2 prior to the iteration loop.
13305SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13306 unsigned Iterations) {
13307 EVT VT = Arg.getValueType();
13308 SDLoc DL(Arg);
13309 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013310
Sanjay Patel957efc232014-10-24 17:02:16 +000013311 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13312 // this entire sequence requires only one FP constant.
13313 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13314 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013315
Sanjay Patel957efc232014-10-24 17:02:16 +000013316 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13317 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013318
Sanjay Patel957efc232014-10-24 17:02:16 +000013319 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13320 for (unsigned i = 0; i < Iterations; ++i) {
13321 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13322 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013323
Sanjay Patel957efc232014-10-24 17:02:16 +000013324 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13325 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013326
Sanjay Patel957efc232014-10-24 17:02:16 +000013327 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13328 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013329
Sanjay Patel957efc232014-10-24 17:02:16 +000013330 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13331 AddToWorklist(Est.getNode());
13332 }
13333 return Est;
13334}
13335
13336/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13337/// For the reciprocal sqrt, we need to find the zero of the function:
13338/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13339/// =>
13340/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13341SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13342 unsigned Iterations) {
13343 EVT VT = Arg.getValueType();
13344 SDLoc DL(Arg);
13345 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13346 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13347
13348 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13349 for (unsigned i = 0; i < Iterations; ++i) {
13350 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13351 AddToWorklist(HalfEst.getNode());
13352
13353 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13354 AddToWorklist(Est.getNode());
13355
13356 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13357 AddToWorklist(Est.getNode());
13358
13359 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13360 AddToWorklist(Est.getNode());
13361
13362 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13363 AddToWorklist(Est.getNode());
13364 }
13365 return Est;
13366}
13367
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013368SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13369 if (Level >= AfterLegalizeDAG)
13370 return SDValue();
13371
13372 // Expose the DAG combiner to the target combiner implementations.
13373 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013374 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000013375 bool UseOneConstNR = false;
13376 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13377 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000013378 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000013379 Est = UseOneConstNR ?
13380 BuildRsqrtNROneConst(Op, Est, Iterations) :
13381 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013382 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013383 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000013384 }
13385
13386 return SDValue();
13387}
13388
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013389/// Return true if base is a frame index, which is known not to alias with
13390/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000013391static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000013392 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000013393 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000013394 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013395
Jim Laskey0463e082006-10-07 23:37:56 +000013396 // If it's an adding a simple constant then integrate the offset.
13397 if (Base.getOpcode() == ISD::ADD) {
13398 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13399 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000013400 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000013401 }
13402 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013403
Nate Begeman18150d52009-09-25 06:05:26 +000013404 // Return the underlying GlobalValue, and update the Offset. Return false
13405 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13406 // by multiple nodes with different offsets.
13407 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13408 GV = G->getGlobal();
13409 Offset += G->getOffset();
13410 return false;
13411 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013412
Nate Begeman18150d52009-09-25 06:05:26 +000013413 // Return the underlying Constant value, and update the Offset. Return false
13414 // for ConstantSDNodes since the same constant pool entry may be represented
13415 // by multiple nodes with different offsets.
13416 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000013417 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13418 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000013419 Offset += C->getOffset();
13420 return false;
13421 }
Jim Laskey0463e082006-10-07 23:37:56 +000013422 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000013423 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000013424}
13425
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013426/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013427bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000013428 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013429 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013430
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013431 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013432 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013433
Jim Laskey0463e082006-10-07 23:37:56 +000013434 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013435 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000013436 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000013437 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000013438 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013439 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13440 Base1, Offset1, GV1, CV1);
13441 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13442 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013443
Nate Begeman18150d52009-09-25 06:05:26 +000013444 // If they have a same base address then check to see if they overlap.
13445 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013446 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13447 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013448
Owen Anderson272ff942010-09-20 20:39:59 +000013449 // It is possible for different frame indices to alias each other, mostly
13450 // when tail call optimization reuses return address slots for arguments.
13451 // To catch this case, look up the actual index of frame indices to compute
13452 // the real alias relationship.
13453 if (isFrameIndex1 && isFrameIndex2) {
13454 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13455 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13456 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013457 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13458 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000013459 }
13460
Wesley Peck527da1b2010-11-23 03:31:01 +000013461 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000013462 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000013463 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13464 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013465
Nate Begeman879d8f12009-09-15 00:18:30 +000013466 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13467 // compared to the size and offset of the access, we may be able to prove they
13468 // do not alias. This check is conservative for now to catch cases created by
13469 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013470 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13471 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13472 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13473 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13474 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13475 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13476 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000013477
Nate Begeman879d8f12009-09-15 00:18:30 +000013478 // There is no overlap between these relatively aligned accesses of similar
13479 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013480 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13481 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000013482 return false;
13483 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013484
Eric Christopherf55d4712014-10-08 23:38:39 +000013485 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13486 ? CombinerGlobalAA
13487 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000013488#ifndef NDEBUG
13489 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13490 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13491 UseAA = false;
13492#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013493 if (UseAA &&
13494 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000013495 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013496 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13497 Op1->getSrcValueOffset());
13498 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13499 Op0->getSrcValueOffset() - MinOffset;
13500 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13501 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013502 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013503 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13504 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000013505 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013506 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13507 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000013508 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000013509 if (AAResult == AliasAnalysis::NoAlias)
13510 return false;
13511 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013512
13513 // Otherwise we have to assume they alias.
13514 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000013515}
13516
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013517/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000013518/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013519void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000013520 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013521 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000013522 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013523
Jim Laskeyd07be232006-09-25 16:29:54 +000013524 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013525 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000013526
Jim Laskey708d0db2006-10-04 16:53:27 +000013527 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000013528 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013529 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000013530
Jim Laskey6549d222006-10-05 15:07:25 +000013531 // Look at each chain and determine if it is an alias. If so, add it to the
13532 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000013533 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000013534 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013535 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000013536 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000013537
13538 // For TokenFactor nodes, look at each operand and only continue up the
13539 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013540 // find more and revert to original chain since the xform is unlikely to be
13541 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000013542 //
13543 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013544 // chain we found before we hit a tokenfactor rather than the original
13545 // chain.
13546 if (Depth > 6 || Aliases.size() == 2) {
13547 Aliases.clear();
13548 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000013549 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013550 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013551
Nate Begeman879d8f12009-09-15 00:18:30 +000013552 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000013553 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000013554 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013555
Jim Laskey6549d222006-10-05 15:07:25 +000013556 switch (Chain.getOpcode()) {
13557 case ISD::EntryToken:
13558 // Entry token is ideal chain operand, but handled in FindBetterChain.
13559 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013560
Jim Laskey6549d222006-10-05 15:07:25 +000013561 case ISD::LOAD:
13562 case ISD::STORE: {
13563 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013564 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13565 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013566
Jim Laskey6549d222006-10-05 15:07:25 +000013567 // If chain is alias then stop here.
13568 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013569 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000013570 Aliases.push_back(Chain);
13571 } else {
13572 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013573 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013574 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000013575 }
Jim Laskey6549d222006-10-05 15:07:25 +000013576 break;
13577 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013578
Jim Laskey6549d222006-10-05 15:07:25 +000013579 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000013580 // We have to check each of the operands of the token factor for "small"
13581 // token factors, so we queue them up. Adding the operands to the queue
13582 // (stack) in reverse order maintains the original order and increases the
13583 // likelihood that getNode will find a matching token factor (CSE.)
13584 if (Chain.getNumOperands() > 16) {
13585 Aliases.push_back(Chain);
13586 break;
13587 }
Jim Laskey6549d222006-10-05 15:07:25 +000013588 for (unsigned n = Chain.getNumOperands(); n;)
13589 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013590 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000013591 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013592
Jim Laskey6549d222006-10-05 15:07:25 +000013593 default:
13594 // For all other instructions we will just have to take what we can get.
13595 Aliases.push_back(Chain);
13596 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000013597 }
13598 }
Hal Finkel51a98382014-01-24 20:12:02 +000013599
13600 // We need to be careful here to also search for aliases through the
13601 // value operand of a store, etc. Consider the following situation:
13602 // Token1 = ...
13603 // L1 = load Token1, %52
13604 // S1 = store Token1, L1, %51
13605 // L2 = load Token1, %52+8
13606 // S2 = store Token1, L2, %51+8
13607 // Token2 = Token(S1, S2)
13608 // L3 = load Token2, %53
13609 // S3 = store Token2, L3, %52
13610 // L4 = load Token2, %53+8
13611 // S4 = store Token2, L4, %52+8
13612 // If we search for aliases of S3 (which loads address %52), and we look
13613 // only through the chain, then we'll miss the trivial dependence on L1
13614 // (which also loads from %52). We then might change all loads and
13615 // stores to use Token1 as their chain operand, which could result in
13616 // copying %53 into %52 before copying %52 into %51 (which should
13617 // happen first).
13618 //
13619 // The problem is, however, that searching for such data dependencies
13620 // can become expensive, and the cost is not directly related to the
13621 // chain depth. Instead, we'll rule out such configurations here by
13622 // insisting that we've visited all chain users (except for users
13623 // of the original chain, which is not necessary). When doing this,
13624 // we need to look through nodes we don't care about (otherwise, things
13625 // like register copies will interfere with trivial cases).
13626
13627 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000013628 for (const SDNode *N : Visited)
13629 if (N != OriginalChain.getNode())
13630 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000013631
13632 while (!Worklist.empty()) {
13633 const SDNode *M = Worklist.pop_back_val();
13634
13635 // We have already visited M, and want to make sure we've visited any uses
13636 // of M that we care about. For uses that we've not visisted, and don't
13637 // care about, queue them to the worklist.
13638
13639 for (SDNode::use_iterator UI = M->use_begin(),
13640 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000013641 if (UI.getUse().getValueType() == MVT::Other &&
13642 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000013643 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13644 // We've not visited this use, and we care about it (it could have an
13645 // ordering dependency with the original node).
13646 Aliases.clear();
13647 Aliases.push_back(OriginalChain);
13648 return;
13649 }
13650
13651 // We've not visited this use, but we don't care about it. Mark it as
13652 // visited and enqueue it to the worklist.
13653 Worklist.push_back(*UI);
13654 }
13655 }
Jim Laskey708d0db2006-10-04 16:53:27 +000013656}
13657
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013658/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13659/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013660SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13661 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013662
Jim Laskey708d0db2006-10-04 16:53:27 +000013663 // Accumulate all the aliases to this node.
13664 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013665
Dan Gohman4298df62011-05-17 22:20:36 +000013666 // If no operands then chain to entry token.
13667 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000013668 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000013669
13670 // If a single operand then chain to it. We don't need to revisit it.
13671 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000013672 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000013673
Jim Laskey708d0db2006-10-04 16:53:27 +000013674 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000013675 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000013676}
13677
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013678/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000013679void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000013680 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013681 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000013682 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000013683}