blob: df721e2d3b5e3fa27bac77e682faae04c7b6f306 [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
Simon Pilgrim86b034b2015-04-23 08:43:13 +00006937 // Remove double bitcasts from shuffles - this is often a legacy of
6938 // XformToShuffleWithZero being used to combine bitmaskings (of
6939 // float vectors bitcast to integer vectors) into shuffles.
6940 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
6941 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
6942 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
6943 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
6944 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
6945 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
6946
6947 // If operands are a bitcast, peek through if it casts the original VT.
6948 // If operands are a UNDEF or constant, just bitcast back to original VT.
6949 auto PeekThroughBitcast = [&](SDValue Op) {
6950 if (Op.getOpcode() == ISD::BITCAST &&
6951 Op.getOperand(0)->getValueType(0) == VT)
6952 return SDValue(Op.getOperand(0));
6953 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
6954 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
6955 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
6956 return SDValue();
6957 };
6958
6959 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
6960 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
6961 if (!(SV0 && SV1))
6962 return SDValue();
6963
6964 int MaskScale =
6965 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
6966 SmallVector<int, 8> NewMask;
6967 for (int M : SVN->getMask())
6968 for (int i = 0; i != MaskScale; ++i)
6969 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
6970
6971 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
6972 if (!LegalMask) {
6973 std::swap(SV0, SV1);
6974 ShuffleVectorSDNode::commuteMask(NewMask);
6975 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
6976 }
6977
6978 if (LegalMask)
6979 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
6980 }
6981
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006982 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006983}
6984
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006985SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006986 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006987 return CombineConsecutiveLoads(N, VT);
6988}
6989
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006990/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6991/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006992SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006993ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006994 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006995
Chris Lattnere4e64b62006-04-02 02:53:43 +00006996 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006997 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006998
Duncan Sands13237ac2008-06-06 12:08:01 +00006999 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7000 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007001
Chris Lattnere4e64b62006-04-02 02:53:43 +00007002 // If this is a conversion of N elements of one type to N elements of another
7003 // type, convert each element. This handles FP<->INT cases.
7004 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00007005 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7006 BV->getValueType(0).getVectorNumElements());
7007
7008 // Due to the FP element handling below calling this routine recursively,
7009 // we can end up with a scalar-to-vector node here.
7010 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007011 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7012 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00007013 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00007014
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007015 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00007016 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00007017 SDValue Op = BV->getOperand(i);
7018 // If the vector element type is not legal, the BUILD_VECTOR operands
7019 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00007020 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007021 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7022 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00007023 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007024 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00007025 }
Craig Topper48d114b2014-04-26 18:35:24 +00007026 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007027 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007028
Chris Lattnere4e64b62006-04-02 02:53:43 +00007029 // Otherwise, we're growing or shrinking the elements. To avoid having to
7030 // handle annoying details of growing/shrinking FP values, we convert them to
7031 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00007032 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007033 // Convert the input float vector to a int vector where the elements are the
7034 // same sizes.
Owen Anderson117c9e82009-08-12 00:36:31 +00007035 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00007036 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00007037 SrcEltVT = IntVT;
7038 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007039
Chris Lattnere4e64b62006-04-02 02:53:43 +00007040 // Now we know the input is an integer vector. If the output is a FP type,
7041 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00007042 if (DstEltVT.isFloatingPoint()) {
Owen Anderson117c9e82009-08-12 00:36:31 +00007043 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00007044 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007045
Chris Lattnere4e64b62006-04-02 02:53:43 +00007046 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00007047 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007048 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007049
Chris Lattnere4e64b62006-04-02 02:53:43 +00007050 // Okay, we know the src/dst types are both integers of differing types.
7051 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00007052 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00007053 if (SrcBitSize < DstBitSize) {
7054 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007055
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007056 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00007057 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00007058 i += NumInputsPerOutput) {
7059 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00007060 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007061 bool EltIsUndef = true;
7062 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7063 // Shift the previously computed bits over.
7064 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007065 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007066 if (Op.getOpcode() == ISD::UNDEF) continue;
7067 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007068
Jay Foad583abbc2010-12-07 08:25:19 +00007069 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00007070 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007071 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007072
Chris Lattnere4e64b62006-04-02 02:53:43 +00007073 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00007074 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007075 else
7076 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
7077 }
7078
Owen Anderson117c9e82009-08-12 00:36:31 +00007079 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00007080 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007081 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007082
Chris Lattnere4e64b62006-04-02 02:53:43 +00007083 // Finally, this must be the case where we are shrinking elements: each input
7084 // turns into multiple outputs.
7085 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00007086 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7087 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007088 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007089
Dan Gohmana8665142007-06-25 16:23:39 +00007090 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007091 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00007092 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007093 continue;
7094 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007095
Jay Foad583abbc2010-12-07 08:25:19 +00007096 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7097 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007098
Chris Lattnere4e64b62006-04-02 02:53:43 +00007099 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00007100 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007101 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Dan Gohmane1c4f992008-03-03 23:51:38 +00007102 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007103 }
7104
7105 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00007106 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00007107 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7108 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007109
Craig Topper48d114b2014-04-26 18:35:24 +00007110 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007111}
7112
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007113/// Try to perform FMA combining on a given FADD node.
7114SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7115
7116
7117
7118
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007119 SDValue N0 = N->getOperand(0);
7120 SDValue N1 = N->getOperand(1);
7121 EVT VT = N->getValueType(0);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007122 SDLoc SL(N);
7123
7124 const TargetOptions &Options = DAG.getTarget().Options;
7125 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7126 Options.UnsafeFPMath);
7127
7128 // Floating-point multiply-add with intermediate rounding.
7129 bool HasFMAD = (LegalOperations &&
7130 TLI.isOperationLegal(ISD::FMAD, VT));
7131
7132 // Floating-point multiply-add without intermediate rounding.
7133 bool HasFMA = ((!LegalOperations ||
7134 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7135 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7136 UnsafeFPMath);
7137
7138 // No valid opcode, do not combine.
7139 if (!HasFMAD && !HasFMA)
7140 return SDValue();
7141
7142 // Always prefer FMAD to FMA for precision.
7143 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7144 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7145 bool LookThroughFPExt = TLI.isFPExtFree(VT);
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007146
7147 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7148 if (N0.getOpcode() == ISD::FMUL &&
7149 (Aggressive || N0->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007150 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007151 N0.getOperand(0), N0.getOperand(1), N1);
7152 }
7153
7154 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7155 // Note: Commutes FADD operands.
7156 if (N1.getOpcode() == ISD::FMUL &&
7157 (Aggressive || N1->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007158 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007159 N1.getOperand(0), N1.getOperand(1), N0);
7160 }
7161
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007162 // Look through FP_EXTEND nodes to do more combining.
7163 if (UnsafeFPMath && LookThroughFPExt) {
7164 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7165 if (N0.getOpcode() == ISD::FP_EXTEND) {
7166 SDValue N00 = N0.getOperand(0);
7167 if (N00.getOpcode() == ISD::FMUL)
7168 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7169 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7170 N00.getOperand(0)),
7171 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7172 N00.getOperand(1)), N1);
7173 }
7174
7175 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7176 // Note: Commutes FADD operands.
7177 if (N1.getOpcode() == ISD::FP_EXTEND) {
7178 SDValue N10 = N1.getOperand(0);
7179 if (N10.getOpcode() == ISD::FMUL)
7180 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7181 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7182 N10.getOperand(0)),
7183 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7184 N10.getOperand(1)), N0);
7185 }
7186 }
7187
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007188 // More folding opportunities when target permits.
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007189 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007190 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007191 if (N0.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007192 N0.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007193 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007194 N0.getOperand(0), N0.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007195 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007196 N0.getOperand(2).getOperand(0),
7197 N0.getOperand(2).getOperand(1),
7198 N1));
7199 }
7200
7201 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007202 if (N1->getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007203 N1.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007204 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007205 N1.getOperand(0), N1.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007206 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007207 N1.getOperand(2).getOperand(0),
7208 N1.getOperand(2).getOperand(1),
7209 N0));
7210 }
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007211
Olivier Sallenavec587bee2015-04-22 14:07:26 +00007212 if (UnsafeFPMath && LookThroughFPExt) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007213 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7214 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7215 auto FoldFAddFMAFPExtFMul = [&] (
7216 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7217 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7218 DAG.getNode(PreferredFusedOpcode, SL, VT,
7219 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7220 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7221 Z));
7222 };
7223 if (N0.getOpcode() == PreferredFusedOpcode) {
7224 SDValue N02 = N0.getOperand(2);
7225 if (N02.getOpcode() == ISD::FP_EXTEND) {
7226 SDValue N020 = N02.getOperand(0);
7227 if (N020.getOpcode() == ISD::FMUL)
7228 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7229 N020.getOperand(0), N020.getOperand(1),
7230 N1);
7231 }
7232 }
7233
7234 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7235 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7236 // FIXME: This turns two single-precision and one double-precision
7237 // operation into two double-precision operations, which might not be
7238 // interesting for all targets, especially GPUs.
7239 auto FoldFAddFPExtFMAFMul = [&] (
7240 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7241 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7242 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7243 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7244 DAG.getNode(PreferredFusedOpcode, SL, VT,
7245 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7246 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7247 Z));
7248 };
7249 if (N0.getOpcode() == ISD::FP_EXTEND) {
7250 SDValue N00 = N0.getOperand(0);
7251 if (N00.getOpcode() == PreferredFusedOpcode) {
7252 SDValue N002 = N00.getOperand(2);
7253 if (N002.getOpcode() == ISD::FMUL)
7254 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7255 N002.getOperand(0), N002.getOperand(1),
7256 N1);
7257 }
7258 }
7259
7260 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7261 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7262 if (N1.getOpcode() == PreferredFusedOpcode) {
7263 SDValue N12 = N1.getOperand(2);
7264 if (N12.getOpcode() == ISD::FP_EXTEND) {
7265 SDValue N120 = N12.getOperand(0);
7266 if (N120.getOpcode() == ISD::FMUL)
7267 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7268 N120.getOperand(0), N120.getOperand(1),
7269 N0);
7270 }
7271 }
7272
7273 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7274 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7275 // FIXME: This turns two single-precision and one double-precision
7276 // operation into two double-precision operations, which might not be
7277 // interesting for all targets, especially GPUs.
7278 if (N1.getOpcode() == ISD::FP_EXTEND) {
7279 SDValue N10 = N1.getOperand(0);
7280 if (N10.getOpcode() == PreferredFusedOpcode) {
7281 SDValue N102 = N10.getOperand(2);
7282 if (N102.getOpcode() == ISD::FMUL)
7283 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7284 N102.getOperand(0), N102.getOperand(1),
7285 N0);
7286 }
7287 }
7288 }
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007289 }
7290
7291 return SDValue();
7292}
7293
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007294/// Try to perform FMA combining on a given FSUB node.
7295SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7296
7297
7298
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007299 SDValue N0 = N->getOperand(0);
7300 SDValue N1 = N->getOperand(1);
7301 EVT VT = N->getValueType(0);
Rafael Espindola1c842712015-04-09 18:29:32 +00007302
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007303 SDLoc SL(N);
7304
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007305 const TargetOptions &Options = DAG.getTarget().Options;
7306 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7307 Options.UnsafeFPMath);
7308
7309 // Floating-point multiply-add with intermediate rounding.
7310 bool HasFMAD = (LegalOperations &&
7311 TLI.isOperationLegal(ISD::FMAD, VT));
7312
7313 // Floating-point multiply-add without intermediate rounding.
7314 bool HasFMA = ((!LegalOperations ||
7315 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7316 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7317 UnsafeFPMath);
7318
7319 // No valid opcode, do not combine.
7320 if (!HasFMAD && !HasFMA)
7321 return SDValue();
7322
7323 // Always prefer FMAD to FMA for precision.
7324 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7325 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7326 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7327
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007328 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7329 if (N0.getOpcode() == ISD::FMUL &&
7330 (Aggressive || N0->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007331 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007332 N0.getOperand(0), N0.getOperand(1),
7333 DAG.getNode(ISD::FNEG, SL, VT, N1));
7334 }
7335
7336 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7337 // Note: Commutes FSUB operands.
7338 if (N1.getOpcode() == ISD::FMUL &&
7339 (Aggressive || N1->hasOneUse()))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007340 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007341 DAG.getNode(ISD::FNEG, SL, VT,
7342 N1.getOperand(0)),
7343 N1.getOperand(1), N0);
7344
7345 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7346 if (N0.getOpcode() == ISD::FNEG &&
7347 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7348 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7349 SDValue N00 = N0.getOperand(0).getOperand(0);
7350 SDValue N01 = N0.getOperand(0).getOperand(1);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007351 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007352 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7353 DAG.getNode(ISD::FNEG, SL, VT, N1));
7354 }
7355
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007356 // Look through FP_EXTEND nodes to do more combining.
7357 if (UnsafeFPMath && LookThroughFPExt) {
7358 // fold (fsub (fpext (fmul x, y)), z)
7359 // -> (fma (fpext x), (fpext y), (fneg z))
7360 if (N0.getOpcode() == ISD::FP_EXTEND) {
7361 SDValue N00 = N0.getOperand(0);
7362 if (N00.getOpcode() == ISD::FMUL)
7363 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7364 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7365 N00.getOperand(0)),
7366 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7367 N00.getOperand(1)),
7368 DAG.getNode(ISD::FNEG, SL, VT, N1));
7369 }
7370
7371 // fold (fsub x, (fpext (fmul y, z)))
7372 // -> (fma (fneg (fpext y)), (fpext z), x)
7373 // Note: Commutes FSUB operands.
7374 if (N1.getOpcode() == ISD::FP_EXTEND) {
7375 SDValue N10 = N1.getOperand(0);
7376 if (N10.getOpcode() == ISD::FMUL)
7377 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7378 DAG.getNode(ISD::FNEG, SL, VT,
7379 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7380 N10.getOperand(0))),
7381 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7382 N10.getOperand(1)),
7383 N0);
7384 }
7385
7386 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7387 // -> (fneg (fma (fpext x), (fpext y), z))
7388 // Note: This could be removed with appropriate canonicalization of the
7389 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7390 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7391 // from implementing the canonicalization in visitFSUB.
7392 if (N0.getOpcode() == ISD::FP_EXTEND) {
7393 SDValue N00 = N0.getOperand(0);
7394 if (N00.getOpcode() == ISD::FNEG) {
7395 SDValue N000 = N00.getOperand(0);
7396 if (N000.getOpcode() == ISD::FMUL) {
7397 return DAG.getNode(ISD::FNEG, SL, VT,
7398 DAG.getNode(PreferredFusedOpcode, SL, VT,
7399 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7400 N000.getOperand(0)),
7401 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7402 N000.getOperand(1)),
7403 N1));
7404 }
7405 }
7406 }
7407
7408 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7409 // -> (fneg (fma (fpext x)), (fpext y), z)
7410 // Note: This could be removed with appropriate canonicalization of the
7411 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7412 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7413 // from implementing the canonicalization in visitFSUB.
7414 if (N0.getOpcode() == ISD::FNEG) {
7415 SDValue N00 = N0.getOperand(0);
7416 if (N00.getOpcode() == ISD::FP_EXTEND) {
7417 SDValue N000 = N00.getOperand(0);
7418 if (N000.getOpcode() == ISD::FMUL) {
7419 return DAG.getNode(ISD::FNEG, SL, VT,
7420 DAG.getNode(PreferredFusedOpcode, SL, VT,
7421 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7422 N000.getOperand(0)),
7423 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7424 N000.getOperand(1)),
7425 N1));
7426 }
7427 }
7428 }
7429
7430 }
7431
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007432 // More folding opportunities when target permits.
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007433 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007434 // fold (fsub (fma x, y, (fmul u, v)), z)
7435 // -> (fma x, y (fma u, v, (fneg z)))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007436 if (N0.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007437 N0.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007438 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007439 N0.getOperand(0), N0.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007440 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007441 N0.getOperand(2).getOperand(0),
7442 N0.getOperand(2).getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007443 DAG.getNode(ISD::FNEG, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007444 N1)));
7445 }
7446
7447 // fold (fsub x, (fma y, z, (fmul u, v)))
7448 // -> (fma (fneg y), z, (fma (fneg u), v, x))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007449 if (N1.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007450 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7451 SDValue N20 = N1.getOperand(2).getOperand(0);
7452 SDValue N21 = N1.getOperand(2).getOperand(1);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007453 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7454 DAG.getNode(ISD::FNEG, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007455 N1.getOperand(0)),
7456 N1.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007457 DAG.getNode(PreferredFusedOpcode, SL, VT,
7458 DAG.getNode(ISD::FNEG, SL, VT, N20),
7459
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007460 N21, N0));
7461 }
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007462
Olivier Sallenavec587bee2015-04-22 14:07:26 +00007463 if (UnsafeFPMath && LookThroughFPExt) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007464 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7465 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7466 if (N0.getOpcode() == PreferredFusedOpcode) {
7467 SDValue N02 = N0.getOperand(2);
7468 if (N02.getOpcode() == ISD::FP_EXTEND) {
7469 SDValue N020 = N02.getOperand(0);
7470 if (N020.getOpcode() == ISD::FMUL)
7471 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7472 N0.getOperand(0), N0.getOperand(1),
7473 DAG.getNode(PreferredFusedOpcode, SL, VT,
7474 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7475 N020.getOperand(0)),
7476 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7477 N020.getOperand(1)),
7478 DAG.getNode(ISD::FNEG, SL, VT,
7479 N1)));
7480 }
7481 }
7482
7483 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7484 // -> (fma (fpext x), (fpext y),
7485 // (fma (fpext u), (fpext v), (fneg z)))
7486 // FIXME: This turns two single-precision and one double-precision
7487 // operation into two double-precision operations, which might not be
7488 // interesting for all targets, especially GPUs.
7489 if (N0.getOpcode() == ISD::FP_EXTEND) {
7490 SDValue N00 = N0.getOperand(0);
7491 if (N00.getOpcode() == PreferredFusedOpcode) {
7492 SDValue N002 = N00.getOperand(2);
7493 if (N002.getOpcode() == ISD::FMUL)
7494 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7495 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7496 N00.getOperand(0)),
7497 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7498 N00.getOperand(1)),
7499 DAG.getNode(PreferredFusedOpcode, SL, VT,
7500 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7501 N002.getOperand(0)),
7502 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7503 N002.getOperand(1)),
7504 DAG.getNode(ISD::FNEG, SL, VT,
7505 N1)));
7506 }
7507 }
7508
7509 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7510 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7511 if (N1.getOpcode() == PreferredFusedOpcode &&
7512 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7513 SDValue N120 = N1.getOperand(2).getOperand(0);
7514 if (N120.getOpcode() == ISD::FMUL) {
7515 SDValue N1200 = N120.getOperand(0);
7516 SDValue N1201 = N120.getOperand(1);
7517 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7518 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7519 N1.getOperand(1),
7520 DAG.getNode(PreferredFusedOpcode, SL, VT,
7521 DAG.getNode(ISD::FNEG, SL, VT,
7522 DAG.getNode(ISD::FP_EXTEND, SL,
7523 VT, N1200)),
7524 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7525 N1201),
7526 N0));
7527 }
7528 }
7529
7530 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7531 // -> (fma (fneg (fpext y)), (fpext z),
7532 // (fma (fneg (fpext u)), (fpext v), x))
7533 // FIXME: This turns two single-precision and one double-precision
7534 // operation into two double-precision operations, which might not be
7535 // interesting for all targets, especially GPUs.
7536 if (N1.getOpcode() == ISD::FP_EXTEND &&
7537 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7538 SDValue N100 = N1.getOperand(0).getOperand(0);
7539 SDValue N101 = N1.getOperand(0).getOperand(1);
7540 SDValue N102 = N1.getOperand(0).getOperand(2);
7541 if (N102.getOpcode() == ISD::FMUL) {
7542 SDValue N1020 = N102.getOperand(0);
7543 SDValue N1021 = N102.getOperand(1);
7544 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7545 DAG.getNode(ISD::FNEG, SL, VT,
7546 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7547 N100)),
7548 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7549 DAG.getNode(PreferredFusedOpcode, SL, VT,
7550 DAG.getNode(ISD::FNEG, SL, VT,
7551 DAG.getNode(ISD::FP_EXTEND, SL,
7552 VT, N1020)),
7553 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7554 N1021),
7555 N0));
7556 }
7557 }
7558 }
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007559 }
7560
7561 return SDValue();
7562}
7563
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007564SDValue DAGCombiner::visitFADD(SDNode *N) {
7565 SDValue N0 = N->getOperand(0);
7566 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00007567 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7568 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007569 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007570 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007571
Dan Gohmana8665142007-06-25 16:23:39 +00007572 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007573 if (VT.isVector())
7574 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7575 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007576
Lang Hamesa33db652012-06-14 20:37:15 +00007577 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007578 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007579 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007580
Nate Begeman418c6e42005-10-18 00:28:13 +00007581 // canonicalize constant to RHS
7582 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007583 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007584
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007585 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007586 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007587 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007588 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007589 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007590
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007591 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007592 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007593 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007594 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007595 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007596
Sanjay Patel8170dea2014-09-08 17:32:19 +00007597 // If 'unsafe math' is enabled, fold lots of things.
7598 if (Options.UnsafeFPMath) {
7599 // No FP constant should be created after legalization as Instruction
7600 // Selection pass has a hard time dealing with FP constants.
7601 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007602
Sanjay Patel8170dea2014-09-08 17:32:19 +00007603 // fold (fadd A, 0) -> A
7604 if (N1CFP && N1CFP->getValueAPF().isZero())
7605 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007606
Sanjay Patel8170dea2014-09-08 17:32:19 +00007607 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7608 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7609 isa<ConstantFPSDNode>(N0.getOperand(1)))
7610 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7611 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7612 N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007613
Sanjay Patel8170dea2014-09-08 17:32:19 +00007614 // If allowed, fold (fadd (fneg x), x) -> 0.0
7615 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7616 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007617
Sanjay Patel8170dea2014-09-08 17:32:19 +00007618 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7619 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7620 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007621
Sanjay Patel8170dea2014-09-08 17:32:19 +00007622 // We can fold chains of FADD's of the same value into multiplications.
7623 // This transform is not safe in general because we are reducing the number
7624 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00007625 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7626 if (N0.getOpcode() == ISD::FMUL) {
7627 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7628 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007629
Sanjay Patel8170dea2014-09-08 17:32:19 +00007630 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7631 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7632 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7633 SDValue(CFP01, 0),
7634 DAG.getConstantFP(1.0, VT));
7635 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7636 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007637
Sanjay Patel8170dea2014-09-08 17:32:19 +00007638 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7639 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7640 N1.getOperand(0) == N1.getOperand(1) &&
7641 N0.getOperand(0) == N1.getOperand(0)) {
7642 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7643 SDValue(CFP01, 0),
7644 DAG.getConstantFP(2.0, VT));
7645 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7646 N0.getOperand(0), NewCFP);
7647 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007648 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007649
Sanjay Patel8170dea2014-09-08 17:32:19 +00007650 if (N1.getOpcode() == ISD::FMUL) {
7651 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7652 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007653
Sanjay Patel8170dea2014-09-08 17:32:19 +00007654 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7655 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7656 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7657 SDValue(CFP11, 0),
7658 DAG.getConstantFP(1.0, VT));
7659 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7660 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007661
Sanjay Patel8170dea2014-09-08 17:32:19 +00007662 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7663 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7664 N0.getOperand(0) == N0.getOperand(1) &&
7665 N1.getOperand(0) == N0.getOperand(0)) {
7666 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7667 SDValue(CFP11, 0),
7668 DAG.getConstantFP(2.0, VT));
7669 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7670 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007671 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007672
Sanjay Patel8170dea2014-09-08 17:32:19 +00007673 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7674 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7675 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7676 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7677 (N0.getOperand(0) == N1))
7678 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7679 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007680 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007681
Sanjay Patel8170dea2014-09-08 17:32:19 +00007682 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7683 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7684 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7685 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7686 N1.getOperand(0) == N0)
7687 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7688 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007689 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007690
Sanjay Patel8170dea2014-09-08 17:32:19 +00007691 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7692 if (AllowNewConst &&
7693 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00007694 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007695 N1.getOperand(0) == N1.getOperand(1) &&
7696 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00007698 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007699 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00007700 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007701
Lang Hames39fb1d02012-06-19 22:51:23 +00007702 // FADD -> FMA combines:
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007703 SDValue Fused = visitFADDForFMACombine(N);
7704 if (Fused) {
7705 AddToWorklist(Fused.getNode());
7706 return Fused;
Olivier Sallenave04515322015-01-07 20:54:17 +00007707 }
7708
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007709 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007710}
7711
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007712SDValue DAGCombiner::visitFSUB(SDNode *N) {
7713 SDValue N0 = N->getOperand(0);
7714 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00007715 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7716 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007717 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007718 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007719 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007720
Dan Gohmana8665142007-06-25 16:23:39 +00007721 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007722 if (VT.isVector())
7723 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7724 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007725
Nate Begeman418c6e42005-10-18 00:28:13 +00007726 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007727 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007728 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00007729
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007730 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007731 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007732 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007733 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007734
Sanjay Patelae402a32014-08-27 20:57:52 +00007735 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007736 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00007737 // (fsub A, 0) -> A
7738 if (N1CFP && N1CFP->getValueAPF().isZero())
7739 return N0;
7740
7741 // (fsub 0, B) -> -B
7742 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00007743 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00007744 return GetNegatedExpression(N1, DAG, LegalOperations);
7745 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7746 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7747 }
7748
7749 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00007750 if (N0 == N1)
7751 return DAG.getConstantFP(0.0f, VT);
7752
Sanjay Patelae402a32014-08-27 20:57:52 +00007753 // (fsub x, (fadd x, y)) -> (fneg y)
7754 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00007755 if (N1.getOpcode() == ISD::FADD) {
7756 SDValue N10 = N1->getOperand(0);
7757 SDValue N11 = N1->getOperand(1);
7758
Sanjay Patel78614bf2014-08-28 15:53:16 +00007759 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007760 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00007761
Sanjay Patel78614bf2014-08-28 15:53:16 +00007762 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007763 return GetNegatedExpression(N10, DAG, LegalOperations);
7764 }
7765 }
7766
Lang Hames39fb1d02012-06-19 22:51:23 +00007767 // FSUB -> FMA combines:
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007768 SDValue Fused = visitFSUBForFMACombine(N);
7769 if (Fused) {
7770 AddToWorklist(Fused.getNode());
7771 return Fused;
Lang Hames39fb1d02012-06-19 22:51:23 +00007772 }
7773
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007774 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007775}
7776
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007777SDValue DAGCombiner::visitFMUL(SDNode *N) {
7778 SDValue N0 = N->getOperand(0);
7779 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00007780 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7781 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007782 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007783 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007784
Dan Gohmana8665142007-06-25 16:23:39 +00007785 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007786 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007787 // This just handles C1 * C2 for vectors. Other vector folds are below.
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007788 if (SDValue FoldedVOp = SimplifyVBinOp(N))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007789 return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007790 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007791
Nate Begemanec48a1b2005-10-17 20:40:11 +00007792 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007793 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007794 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00007795
Nate Begemanec48a1b2005-10-17 20:40:11 +00007796 // canonicalize constant to RHS
Simon Pilgrimbcf3bc22015-04-05 14:30:37 +00007797 if (isConstantFPBuildVectorOrConstantFP(N0) &&
7798 !isConstantFPBuildVectorOrConstantFP(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007799 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007800
Owen Andersonb5f167c2012-05-02 21:32:35 +00007801 // fold (fmul A, 1.0) -> A
7802 if (N1CFP && N1CFP->isExactlyValue(1.0))
7803 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00007804
Sanjay Patel394c3332014-09-08 20:16:42 +00007805 if (Options.UnsafeFPMath) {
7806 // fold (fmul A, 0) -> 0
7807 if (N1CFP && N1CFP->getValueAPF().isZero())
7808 return N1;
7809
7810 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007811 if (N0.getOpcode() == ISD::FMUL) {
7812 // Fold scalars or any vector constants (not just splats).
7813 // This fold is done in general by InstCombine, but extra fmul insts
7814 // may have been generated during lowering.
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007815 SDValue N00 = N0.getOperand(0);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007816 SDValue N01 = N0.getOperand(1);
7817 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007818 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007819 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007820
7821 // Check 1: Make sure that the first operand of the inner multiply is NOT
7822 // a constant. Otherwise, we may induce infinite looping.
7823 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7824 // Check 2: Make sure that the second operand of the inner multiply and
7825 // the second operand of the outer multiply are constants.
7826 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7827 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7828 SDLoc SL(N);
7829 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7830 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7831 }
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007832 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007833 }
7834
Sanjay Patel394c3332014-09-08 20:16:42 +00007835 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007836 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7837 // during an early run of DAGCombiner can prevent folding with fmuls
7838 // inserted during lowering.
7839 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7840 SDLoc SL(N);
7841 const SDValue Two = DAG.getConstantFP(2.0, VT);
7842 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7843 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7844 }
7845 }
7846
Nate Begemanec48a1b2005-10-17 20:40:11 +00007847 // fold (fmul X, 2.0) -> (fadd X, X)
7848 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007849 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007850
Dan Gohmanb7170912009-08-10 16:50:32 +00007851 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00007852 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00007853 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007854 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007855
Bill Wendling3dc5d242009-01-30 22:57:07 +00007856 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007857 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7858 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007859 // Both can be negated for free, check to see if at least one is cheaper
7860 // negated.
7861 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007862 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007863 GetNegatedExpression(N0, DAG, LegalOperations),
7864 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007865 }
7866 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007867
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007868 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007869}
7870
Owen Anderson41b06652012-05-02 22:17:40 +00007871SDValue DAGCombiner::visitFMA(SDNode *N) {
7872 SDValue N0 = N->getOperand(0);
7873 SDValue N1 = N->getOperand(1);
7874 SDValue N2 = N->getOperand(2);
7875 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7876 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7877 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007878 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007879 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007880
7881 // Constant fold FMA.
7882 if (isa<ConstantFPSDNode>(N0) &&
7883 isa<ConstantFPSDNode>(N1) &&
7884 isa<ConstantFPSDNode>(N2)) {
7885 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7886 }
7887
Sanjay Patel78614bf2014-08-28 15:53:16 +00007888 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00007889 if (N0CFP && N0CFP->isZero())
7890 return N2;
7891 if (N1CFP && N1CFP->isZero())
7892 return N2;
7893 }
Owen Anderson41b06652012-05-02 22:17:40 +00007894 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007895 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007896 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007897 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007898
Owen Andersonc7aaf522012-05-30 18:50:39 +00007899 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00007900 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007901 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00007902
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007903 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007904 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007905 N2.getOpcode() == ISD::FMUL &&
7906 N0 == N2.getOperand(0) &&
7907 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7908 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7909 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7910 }
7911
7912
7913 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007914 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007915 N0.getOpcode() == ISD::FMUL && N1CFP &&
7916 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7917 return DAG.getNode(ISD::FMA, dl, VT,
7918 N0.getOperand(0),
7919 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7920 N2);
7921 }
7922
7923 // (fma x, 1, y) -> (fadd x, y)
7924 // (fma x, -1, y) -> (fadd (fneg x), y)
7925 if (N1CFP) {
7926 if (N1CFP->isExactlyValue(1.0))
7927 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7928
7929 if (N1CFP->isExactlyValue(-1.0) &&
7930 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7931 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007932 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007933 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7934 }
7935 }
7936
7937 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007938 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00007939 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007940 DAG.getNode(ISD::FADD, dl, VT,
7941 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007942
7943 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007944 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00007945 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7946 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007947 DAG.getNode(ISD::FADD, dl, VT,
7948 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007949
7950
Owen Anderson41b06652012-05-02 22:17:40 +00007951 return SDValue();
7952}
7953
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007954SDValue DAGCombiner::visitFDIV(SDNode *N) {
7955 SDValue N0 = N->getOperand(0);
7956 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007957 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7958 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007959 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007960 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007961 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007962
Dan Gohmana8665142007-06-25 16:23:39 +00007963 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007964 if (VT.isVector())
7965 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7966 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007967
Nate Begeman569c4392006-01-18 22:35:16 +00007968 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007969 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007970 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007971
Sanjay Patelb67bd262014-09-21 15:19:15 +00007972 if (Options.UnsafeFPMath) {
7973 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7974 if (N1CFP) {
7975 // Compute the reciprocal 1.0 / c2.
7976 APFloat N1APF = N1CFP->getValueAPF();
7977 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7978 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7979 // Only do the transform if the reciprocal is a legal fp immediate that
7980 // isn't too nasty (eg NaN, denormal, ...).
7981 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7982 (!LegalOperations ||
7983 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7984 // backend)... we should handle this gracefully after Legalize.
7985 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7986 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7987 TLI.isFPImmLegal(Recip, VT)))
7988 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7989 DAG.getConstantFP(Recip, VT));
7990 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007991
Sanjay Patelb67bd262014-09-21 15:19:15 +00007992 // If this FDIV is part of a reciprocal square root, it may be folded
7993 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007994 if (N1.getOpcode() == ISD::FSQRT) {
7995 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007996 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7997 }
7998 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7999 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8000 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008001 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8002 AddToWorklist(RV.getNode());
8003 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8004 }
8005 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8006 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8007 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008008 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8009 AddToWorklist(RV.getNode());
8010 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8011 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00008012 } else if (N1.getOpcode() == ISD::FMUL) {
8013 // Look through an FMUL. Even though this won't remove the FDIV directly,
8014 // it's still worthwhile to get rid of the FSQRT if possible.
8015 SDValue SqrtOp;
8016 SDValue OtherOp;
8017 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8018 SqrtOp = N1.getOperand(0);
8019 OtherOp = N1.getOperand(1);
8020 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8021 SqrtOp = N1.getOperand(1);
8022 OtherOp = N1.getOperand(0);
8023 }
8024 if (SqrtOp.getNode()) {
8025 // We found a FSQRT, so try to make this fold:
8026 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8027 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00008028 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8029 AddToWorklist(RV.getNode());
8030 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8031 }
8032 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008033 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008034
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008035 // Fold into a reciprocal estimate and multiply instead of a real divide.
8036 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8037 AddToWorklist(RV.getNode());
8038 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8039 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00008040 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008041
Bill Wendling3dc5d242009-01-30 22:57:07 +00008042 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008043 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8044 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00008045 // Both can be negated for free, check to see if at least one is cheaper
8046 // negated.
8047 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008048 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008049 GetNegatedExpression(N0, DAG, LegalOperations),
8050 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00008051 }
8052 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008053
Hao Liu44e5d7a2014-11-21 06:39:58 +00008054 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8055 // reciprocal.
8056 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8057 // Notice that this is not always beneficial. One reason is different target
8058 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8059 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8060 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8061 if (Options.UnsafeFPMath) {
8062 // Skip if current node is a reciprocal.
8063 if (N0CFP && N0CFP->isExactlyValue(1.0))
8064 return SDValue();
8065
8066 SmallVector<SDNode *, 4> Users;
8067 // Find all FDIV users of the same divisor.
8068 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8069 UE = N1.getNode()->use_end();
8070 UI != UE; ++UI) {
8071 SDNode *User = UI.getUse().getUser();
8072 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8073 Users.push_back(User);
8074 }
8075
8076 if (TLI.combineRepeatedFPDivisors(Users.size())) {
8077 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
8078 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
8079
8080 // Dividend / Divisor -> Dividend * Reciprocal
8081 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8082 if ((*I)->getOperand(0) != FPOne) {
8083 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8084 (*I)->getOperand(0), Reciprocal);
8085 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8086 }
8087 }
8088 return SDValue();
8089 }
8090 }
8091
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008092 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008093}
8094
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008095SDValue DAGCombiner::visitFREM(SDNode *N) {
8096 SDValue N0 = N->getOperand(0);
8097 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008098 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8099 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008100 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00008101
Nate Begeman569c4392006-01-18 22:35:16 +00008102 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008103 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008104 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00008105
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008106 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008107}
8108
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008109SDValue DAGCombiner::visitFSQRT(SDNode *N) {
Matt Arsenaultbf0db912015-01-13 20:53:23 +00008110 if (DAG.getTarget().Options.UnsafeFPMath &&
8111 !TLI.isFsqrtCheap()) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008112 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008113 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008114 EVT VT = RV.getValueType();
8115 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
8116 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008117
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008118 // Unfortunately, RV is now NaN if the input was exactly 0.
8119 // Select out this case and force the answer to 0.
8120 SDValue Zero = DAG.getConstantFP(0.0, VT);
8121 SDValue ZeroCmp =
8122 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
8123 N->getOperand(0), Zero, ISD::SETEQ);
8124 AddToWorklist(ZeroCmp.getNode());
8125 AddToWorklist(RV.getNode());
8126
8127 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8128 SDLoc(N), VT, ZeroCmp, Zero, RV);
8129 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008130 }
8131 }
8132 return SDValue();
8133}
8134
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008135SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8136 SDValue N0 = N->getOperand(0);
8137 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00008138 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8139 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008140 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00008141
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008142 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00008143 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008144
Chris Lattner3bc40502006-03-05 05:30:57 +00008145 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00008146 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00008147 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8148 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00008149 if (!V.isNegative()) {
8150 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008151 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00008152 } else {
8153 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008154 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8155 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00008156 }
Chris Lattner3bc40502006-03-05 05:30:57 +00008157 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008158
Chris Lattner3bc40502006-03-05 05:30:57 +00008159 // copysign(fabs(x), y) -> copysign(x, y)
8160 // copysign(fneg(x), y) -> copysign(x, y)
8161 // copysign(copysign(x,z), y) -> copysign(x, y)
8162 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8163 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008164 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008165 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00008166
8167 // copysign(x, abs(y)) -> abs(x)
8168 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008169 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008170
Chris Lattner3bc40502006-03-05 05:30:57 +00008171 // copysign(x, copysign(y,z)) -> copysign(x, z)
8172 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008173 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008174 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008175
Chris Lattner3bc40502006-03-05 05:30:57 +00008176 // copysign(x, fp_extend(y)) -> copysign(x, y)
8177 // copysign(x, fp_round(y)) -> copysign(x, y)
8178 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008179 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008180 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008181
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008182 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00008183}
8184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008185SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8186 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008187 EVT VT = N->getValueType(0);
8188 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008189
Nate Begeman21158fc2005-09-01 00:19:25 +00008190 // fold (sint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008191 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008192 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008193 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008194 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008195 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008196
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008197 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8198 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008199 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8200 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008201 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008202 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008203 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008204 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008205
Alp Tokercb402912014-01-24 17:20:08 +00008206 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008207 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008208 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8209 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8210 !VT.isVector() &&
8211 (!LegalOperations ||
8212 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8213 SDValue Ops[] =
8214 { N0.getOperand(0), N0.getOperand(1),
8215 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
8216 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00008217 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008218 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008219
Nadav Rotem90560762012-07-23 07:59:50 +00008220 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8221 // (select_cc x, y, 1.0, 0.0,, cc)
8222 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8223 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8224 (!LegalOperations ||
8225 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8226 SDValue Ops[] =
8227 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8228 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
8229 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00008230 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008231 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008232 }
8233
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008234 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008235}
8236
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008237SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8238 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008239 EVT VT = N->getValueType(0);
8240 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00008241
Nate Begeman21158fc2005-09-01 00:19:25 +00008242 // fold (uint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008243 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008244 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008245 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008246 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008247 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008248
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008249 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8250 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008251 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8252 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008253 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008254 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008255 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008256 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008257
Alp Tokercb402912014-01-24 17:20:08 +00008258 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008259 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008260 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00008261
Nadav Rotem90560762012-07-23 07:59:50 +00008262 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8263 (!LegalOperations ||
8264 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8265 SDValue Ops[] =
8266 { N0.getOperand(0), N0.getOperand(1),
8267 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8268 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00008269 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008270 }
8271 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008272
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008273 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008274}
8275
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008276// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8277static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8278 SDValue N0 = N->getOperand(0);
8279 EVT VT = N->getValueType(0);
8280
8281 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8282 return SDValue();
8283
8284 SDValue Src = N0.getOperand(0);
8285 EVT SrcVT = Src.getValueType();
8286 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8287 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8288
8289 // We can safely assume the conversion won't overflow the output range,
8290 // because (for example) (uint8_t)18293.f is undefined behavior.
8291
8292 // Since we can assume the conversion won't overflow, our decision as to
8293 // whether the input will fit in the float should depend on the minimum
8294 // of the input range and output range.
8295
8296 // This means this is also safe for a signed input and unsigned output, since
8297 // a negative input would lead to undefined behavior.
8298 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8299 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8300 unsigned ActualSize = std::min(InputSize, OutputSize);
8301 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8302
8303 // We can only fold away the float conversion if the input range can be
8304 // represented exactly in the float range.
8305 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8306 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8307 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8308 : ISD::ZERO_EXTEND;
8309 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8310 }
8311 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8312 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8313 if (SrcVT == VT)
8314 return Src;
8315 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8316 }
8317 return SDValue();
8318}
8319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008320SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8321 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008322 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008323 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008324
Nate Begeman21158fc2005-09-01 00:19:25 +00008325 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008326 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008327 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008328
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008329 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008330}
8331
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008332SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8333 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008334 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008335 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008336
Nate Begeman21158fc2005-09-01 00:19:25 +00008337 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008338 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008339 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008340
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008341 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008342}
8343
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008344SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8345 SDValue N0 = N->getOperand(0);
8346 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008347 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008348 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008349
Nate Begeman21158fc2005-09-01 00:19:25 +00008350 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008351 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008352 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008353
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008354 // fold (fp_round (fp_extend x)) -> x
8355 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8356 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008357
Chris Lattner0feb1b02008-01-24 06:45:35 +00008358 // fold (fp_round (fp_round x)) -> (fp_round x)
8359 if (N0.getOpcode() == ISD::FP_ROUND) {
Ahmed Bougacha24433a72015-02-12 06:15:29 +00008360 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8361 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8362 // If the first fp_round isn't a value preserving truncation, it might
8363 // introduce a tie in the second fp_round, that wouldn't occur in the
8364 // single-step fp_round we want to fold to.
8365 // In other words, double rounding isn't the same as rounding.
8366 // Also, this is a value preserving truncation iff both fp_round's are.
8367 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8368 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8369 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
Chris Lattner0feb1b02008-01-24 06:45:35 +00008370 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008371
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008372 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00008373 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008374 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008375 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008376 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008377 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008378 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008379 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008380
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008381 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008382}
8383
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008384SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8385 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008386 EVT VT = N->getValueType(0);
8387 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008388 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008389
Nate Begeman21158fc2005-09-01 00:19:25 +00008390 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00008391 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00008392 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008393 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00008394 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008395
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008396 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008397}
8398
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008399SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8400 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008401 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008402
Chris Lattner5919b482007-12-29 06:55:23 +00008403 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008404 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00008405 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008406 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00008407
Nate Begeman21158fc2005-09-01 00:19:25 +00008408 // fold (fp_extend c1fp) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008409 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008410 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00008411
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +00008412 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8413 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8414 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8415 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8416
Chris Lattner72733e52008-01-17 07:00:52 +00008417 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8418 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00008419 if (N0.getOpcode() == ISD::FP_ROUND
8420 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008421 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00008422 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00008423 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008424 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008425 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008426 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00008427 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008428
Chris Lattner72733e52008-01-17 07:00:52 +00008429 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00008430 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00008431 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008432 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008433 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008434 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008435 LN0->getBasePtr(), N0.getValueType(),
8436 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00008437 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00008438 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008439 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00008440 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00008441 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008442 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00008443 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00008444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008445 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008446}
8447
Sanjay Patelccd26762014-08-28 21:51:37 +00008448SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8449 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008450 EVT VT = N->getValueType(0);
8451
8452 // fold (fceil c1) -> fceil(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008453 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008454 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8455
8456 return SDValue();
8457}
8458
8459SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8460 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008461 EVT VT = N->getValueType(0);
8462
8463 // fold (ftrunc c1) -> ftrunc(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008464 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008465 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8466
8467 return SDValue();
8468}
8469
8470SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8471 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008472 EVT VT = N->getValueType(0);
8473
8474 // fold (ffloor c1) -> ffloor(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008475 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008476 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8477
8478 return SDValue();
8479}
8480
8481// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008482SDValue DAGCombiner::visitFNEG(SDNode *N) {
8483 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00008484 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008485
Sanjay Patelccd26762014-08-28 21:51:37 +00008486 // Constant fold FNEG.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008487 if (isConstantFPBuildVectorOrConstantFP(N0))
8488 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008489
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00008490 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8491 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008492 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00008493
Sanjay Patel35d31332014-08-14 15:15:28 +00008494 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008495 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00008496 if (!TLI.isFNegFree(VT) &&
8497 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00008498 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008499 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008500 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008501 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00008502 APInt SignMask;
8503 if (N0.getValueType().isVector()) {
8504 // For a vector, get a mask such as 0x80... per scalar element
8505 // and splat it.
8506 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8507 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8508 } else {
8509 // For a scalar, just generate 0x80...
8510 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8511 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008512 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00008513 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008514 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00008515 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008516 }
8517 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008518
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008519 // (fneg (fmul c, x)) -> (fmul -c, x)
8520 if (N0.getOpcode() == ISD::FMUL) {
8521 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00008522 if (CFP1) {
8523 APFloat CVal = CFP1->getValueAPF();
8524 CVal.changeSign();
8525 if (Level >= AfterLegalizeDAG &&
8526 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8527 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8528 return DAG.getNode(
8529 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8530 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8531 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008532 }
8533
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008534 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008535}
8536
Matt Arsenault7c936902014-10-21 23:01:01 +00008537SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8538 SDValue N0 = N->getOperand(0);
8539 SDValue N1 = N->getOperand(1);
8540 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8541 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8542
8543 if (N0CFP && N1CFP) {
8544 const APFloat &C0 = N0CFP->getValueAPF();
8545 const APFloat &C1 = N1CFP->getValueAPF();
8546 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8547 }
8548
8549 if (N0CFP) {
8550 EVT VT = N->getValueType(0);
8551 // Canonicalize to constant on RHS.
8552 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8553 }
8554
8555 return SDValue();
8556}
8557
8558SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8559 SDValue N0 = N->getOperand(0);
8560 SDValue N1 = N->getOperand(1);
8561 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8562 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8563
8564 if (N0CFP && N1CFP) {
8565 const APFloat &C0 = N0CFP->getValueAPF();
8566 const APFloat &C1 = N1CFP->getValueAPF();
8567 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8568 }
8569
8570 if (N0CFP) {
8571 EVT VT = N->getValueType(0);
8572 // Canonicalize to constant on RHS.
8573 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8574 }
8575
8576 return SDValue();
8577}
8578
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008579SDValue DAGCombiner::visitFABS(SDNode *N) {
8580 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008581 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008582
Nate Begeman21158fc2005-09-01 00:19:25 +00008583 // fold (fabs c1) -> fabs(c1)
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008584 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008585 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008586
Nate Begeman21158fc2005-09-01 00:19:25 +00008587 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008588 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00008589 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008590
Nate Begeman21158fc2005-09-01 00:19:25 +00008591 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008592 // fold (fabs (fcopysign x, y)) -> (fabs x)
8593 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008594 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008595
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008596 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008597 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00008598 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008599 N0.getOpcode() == ISD::BITCAST &&
8600 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008601 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008602 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008603 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008604 APInt SignMask;
8605 if (N0.getValueType().isVector()) {
8606 // For a vector, get a mask such as 0x7f... per scalar element
8607 // and splat it.
8608 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8609 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8610 } else {
8611 // For a scalar, just generate 0x7f...
8612 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8613 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008614 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008615 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008616 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008617 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008618 }
8619 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008620
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008621 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008622}
8623
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008624SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8625 SDValue Chain = N->getOperand(0);
8626 SDValue N1 = N->getOperand(1);
8627 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008628
Dan Gohman82e80012009-11-17 00:47:23 +00008629 // If N is a constant we could fold this into a fallthrough or unconditional
8630 // branch. However that doesn't happen very often in normal code, because
8631 // Instcombine/SimplifyCFG should have handled the available opportunities.
8632 // If we did this folding here, it would be necessary to update the
8633 // MachineBasicBlock CFG, which is awkward.
8634
Nate Begeman7e7f4392006-02-01 07:19:44 +00008635 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8636 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008637 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00008638 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8639 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008640 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008641 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00008642 N1.getOperand(0), N1.getOperand(1), N2);
8643 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008644
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008645 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8646 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8647 (N1.getOperand(0).hasOneUse() &&
8648 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00008649 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008650 if (N1.getOpcode() == ISD::TRUNCATE) {
8651 // Look pass the truncate.
8652 Trunc = N1.getNode();
8653 N1 = N1.getOperand(0);
8654 }
Evan Cheng166a4e62010-01-06 19:38:29 +00008655
Bill Wendlingaa28be62009-03-26 06:14:09 +00008656 // Match this pattern so that we can generate simpler code:
8657 //
8658 // %a = ...
8659 // %b = and i32 %a, 2
8660 // %c = srl i32 %b, 1
8661 // brcond i32 %c ...
8662 //
8663 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00008664 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00008665 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00008666 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00008667 // %c = setcc eq %b, 0
8668 // brcond %c ...
8669 //
8670 // This applies only when the AND constant value has one bit set and the
8671 // SRL constant is equal to the log2 of the AND constant. The back-end is
8672 // smart enough to convert the result into a TEST/JMP sequence.
8673 SDValue Op0 = N1.getOperand(0);
8674 SDValue Op1 = N1.getOperand(1);
8675
8676 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00008677 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00008678 SDValue AndOp1 = Op0.getOperand(1);
8679
8680 if (AndOp1.getOpcode() == ISD::Constant) {
8681 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8682
8683 if (AndConst.isPowerOf2() &&
8684 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8685 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008686 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00008687 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00008688 Op0, DAG.getConstant(0, Op0.getValueType()),
8689 ISD::SETNE);
8690
Andrew Trickef9de2a2013-05-25 02:42:55 +00008691 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00008692 MVT::Other, Chain, SetCC, N2);
8693 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8694 // will convert it back to (X & C1) >> C2.
8695 CombineTo(N, NewBRCond, false);
8696 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00008697 if (Trunc)
8698 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008699 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008700 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008701 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008702 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00008703 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00008704 }
8705 }
8706 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008707
8708 if (Trunc)
8709 // Restore N1 if the above transformation doesn't match.
8710 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008711 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008712
Evan Cheng228c31f2010-02-27 07:36:59 +00008713 // Transform br(xor(x, y)) -> br(x != y)
8714 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8715 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8716 SDNode *TheXor = N1.getNode();
8717 SDValue Op0 = TheXor->getOperand(0);
8718 SDValue Op1 = TheXor->getOperand(1);
8719 if (Op0.getOpcode() == Op1.getOpcode()) {
8720 // Avoid missing important xor optimizations.
8721 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008722 if (Tmp.getNode()) {
8723 if (Tmp.getNode() != TheXor) {
8724 DEBUG(dbgs() << "\nReplacing.8 ";
8725 TheXor->dump(&DAG);
8726 dbgs() << "\nWith: ";
8727 Tmp.getNode()->dump(&DAG);
8728 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008729 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008730 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00008731 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008732 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00008733 MVT::Other, Chain, Tmp, N2);
8734 }
8735
Benjamin Kramer93354432013-03-30 21:28:18 +00008736 // visitXOR has changed XOR's operands or replaced the XOR completely,
8737 // bail out.
8738 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00008739 }
8740 }
8741
8742 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8743 bool Equal = false;
8744 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8745 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8746 Op0.getOpcode() == ISD::XOR) {
8747 TheXor = Op0.getNode();
8748 Equal = true;
8749 }
8750
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008751 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00008752 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00008753 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008754 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00008755 SetCCVT,
8756 Op0, Op1,
8757 Equal ? ISD::SETEQ : ISD::SETNE);
8758 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008759 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008760 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008761 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008762 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00008763 MVT::Other, Chain, SetCC, N2);
8764 }
8765 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00008766
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008767 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008768}
8769
Chris Lattnera49e16f2005-10-05 06:47:48 +00008770// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8771//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008772SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00008773 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008774 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008775
Dan Gohman82e80012009-11-17 00:47:23 +00008776 // If N is a constant we could fold this into a fallthrough or unconditional
8777 // branch. However that doesn't happen very often in normal code, because
8778 // Instcombine/SimplifyCFG should have handled the available opportunities.
8779 // If we did this folding here, it would be necessary to update the
8780 // MachineBasicBlock CFG, which is awkward.
8781
Duncan Sands93b66092008-06-09 11:32:28 +00008782 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00008783 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008784 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00008785 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008786 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00008787
Nate Begemanbd7df032005-10-05 21:43:42 +00008788 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00008789 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008790 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008791 N->getOperand(0), Simp.getOperand(2),
8792 Simp.getOperand(0), Simp.getOperand(1),
8793 N->getOperand(4));
8794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008795 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008796}
8797
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008798/// Return true if 'Use' is a load or a store that uses N as its base pointer
8799/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00008800static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8801 SelectionDAG &DAG,
8802 const TargetLowering &TLI) {
8803 EVT VT;
8804 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8805 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8806 return false;
Quentin Colombet82291452015-04-24 21:28:00 +00008807 VT = LD->getMemoryVT();
Evan Chengfa832632012-01-13 01:37:24 +00008808 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8809 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8810 return false;
Quentin Colombet82291452015-04-24 21:28:00 +00008811 VT = ST->getMemoryVT();
Evan Chengfa832632012-01-13 01:37:24 +00008812 } else
8813 return false;
8814
Chandler Carruth95f83e02013-01-07 15:14:13 +00008815 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00008816 if (N->getOpcode() == ISD::ADD) {
8817 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8818 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008819 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008820 AM.BaseOffs = Offset->getSExtValue();
8821 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008822 // [reg +/- reg]
8823 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008824 } else if (N->getOpcode() == ISD::SUB) {
8825 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8826 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008827 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008828 AM.BaseOffs = -Offset->getSExtValue();
8829 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008830 // [reg +/- reg]
8831 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008832 } else
8833 return false;
8834
8835 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8836}
8837
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008838/// Try turning a load/store into a pre-indexed load/store when the base
8839/// pointer is an add or subtract and it has other uses besides the load/store.
8840/// After the transformation, the new indexed load/store has effectively folded
8841/// the add/subtract in and all of its other uses are redirected to the
8842/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008843bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008844 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008845 return false;
8846
8847 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008848 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008849 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008850 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008851 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008852 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008853 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00008854 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00008855 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8856 return false;
8857 Ptr = LD->getBasePtr();
8858 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008859 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008860 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008861 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008862 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8863 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8864 return false;
8865 Ptr = ST->getBasePtr();
8866 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008867 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008868 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008869 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008870
Chris Lattnereabc15c2006-11-11 00:56:29 +00008871 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8872 // out. There is no reason to make this a preinc/predec.
8873 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00008874 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008875 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008876
Chris Lattnereabc15c2006-11-11 00:56:29 +00008877 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008878 SDValue BasePtr;
8879 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008880 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8881 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8882 return false;
Hal Finkel25819052013-02-08 21:35:47 +00008883
8884 // Backends without true r+i pre-indexed forms may need to pass a
8885 // constant base with a variable offset so that constant coercion
8886 // will work with the patterns in canonical form.
8887 bool Swapped = false;
8888 if (isa<ConstantSDNode>(BasePtr)) {
8889 std::swap(BasePtr, Offset);
8890 Swapped = true;
8891 }
8892
Evan Cheng044a0a82007-05-03 23:52:19 +00008893 // Don't create a indexed load / store with zero offset.
8894 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008895 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008896 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008897
Chris Lattnera0a80032006-11-11 01:00:15 +00008898 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00008899 // 1) The new base ptr is a frame index.
8900 // 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 +00008901 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00008902 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00008903 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00008904 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00008905
Chris Lattnera0a80032006-11-11 01:00:15 +00008906 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8907 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00008908 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00008909 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008910
Chris Lattnera0a80032006-11-11 01:00:15 +00008911 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008912 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008913 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00008914 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008915 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008916 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008917
Hal Finkel25819052013-02-08 21:35:47 +00008918 // If the offset is a constant, there may be other adds of constants that
8919 // can be folded with this one. We should do this to avoid having to keep
8920 // a copy of the original base pointer.
8921 SmallVector<SDNode *, 16> OtherUses;
8922 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00008923 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00008924 if (Use == Ptr.getNode())
8925 continue;
8926
8927 if (Use->isPredecessorOf(N))
8928 continue;
8929
8930 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8931 OtherUses.clear();
8932 break;
8933 }
8934
8935 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8936 if (Op1.getNode() == BasePtr.getNode())
8937 std::swap(Op0, Op1);
8938 assert(Op0.getNode() == BasePtr.getNode() &&
8939 "Use of ADD/SUB but not an operand");
8940
8941 if (!isa<ConstantSDNode>(Op1)) {
8942 OtherUses.clear();
8943 break;
8944 }
8945
8946 // FIXME: In some cases, we can be smarter about this.
8947 if (Op1.getValueType() != Offset.getValueType()) {
8948 OtherUses.clear();
8949 break;
8950 }
8951
8952 OtherUses.push_back(Use);
8953 }
8954
8955 if (Swapped)
8956 std::swap(BasePtr, Offset);
8957
Evan Chenga4d187b2007-05-24 02:35:39 +00008958 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008959 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00008960
8961 // Caches for hasPredecessorHelper
8962 SmallPtrSet<const SDNode *, 32> Visited;
8963 SmallVector<const SDNode *, 16> Worklist;
8964
Jim Grosbache8160032014-04-11 01:13:13 +00008965 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008966 if (Use == N)
8967 continue;
Lang Hames5a004992011-07-07 04:31:51 +00008968 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008969 return false;
8970
Evan Chengfa832632012-01-13 01:37:24 +00008971 // If Ptr may be folded in addressing mode of other use, then it's
8972 // not profitable to do this transformation.
8973 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008974 RealUse = true;
8975 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008976
Chris Lattnereabc15c2006-11-11 00:56:29 +00008977 if (!RealUse)
8978 return false;
8979
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008980 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008981 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008982 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008983 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008984 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00008985 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008986 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008987 ++PreIndexedNodes;
8988 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008989 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008990 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008991 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008992 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008993 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008994 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008995 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008996 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8997 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008998 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008999 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009000 }
9001
Chris Lattnereabc15c2006-11-11 00:56:29 +00009002 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00009003 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009004
Hal Finkel25819052013-02-08 21:35:47 +00009005 if (Swapped)
9006 std::swap(BasePtr, Offset);
9007
9008 // Replace other uses of BasePtr that can be updated to use Ptr
9009 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9010 unsigned OffsetIdx = 1;
9011 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9012 OffsetIdx = 0;
9013 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9014 BasePtr.getNode() && "Expected BasePtr operand");
9015
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009016 // We need to replace ptr0 in the following expression:
9017 // x0 * offset0 + y0 * ptr0 = t0
9018 // knowing that
9019 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00009020 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009021 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9022 // indexed load/store and the expresion that needs to be re-written.
9023 //
9024 // Therefore, we have:
9025 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00009026
9027 ConstantSDNode *CN =
9028 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009029 int X0, X1, Y0, Y1;
9030 APInt Offset0 = CN->getAPIntValue();
9031 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00009032
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009033 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9034 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9035 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9036 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00009037
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009038 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9039
9040 APInt CNV = Offset0;
9041 if (X0 < 0) CNV = -CNV;
9042 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9043 else CNV = CNV - Offset1;
9044
9045 // We can now generate the new expression.
9046 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
9047 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9048
9049 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00009050 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00009051 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9052 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00009053 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00009054 }
9055
Chris Lattnereabc15c2006-11-11 00:56:29 +00009056 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009057 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00009058 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00009059
9060 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00009061}
9062
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009063/// Try to combine a load/store with a add/sub of the base pointer node into a
9064/// post-indexed load/store. The transformation folded the add/subtract into the
9065/// new indexed load/store effectively and all of its uses are redirected to the
9066/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00009067bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00009068 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00009069 return false;
9070
9071 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009072 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009073 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00009074 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009075 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009076 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009077 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009078 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9079 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9080 return false;
9081 Ptr = LD->getBasePtr();
9082 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009083 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009084 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009085 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009086 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9087 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9088 return false;
9089 Ptr = ST->getBasePtr();
9090 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009091 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00009092 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009093 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009094
Gabor Greiff304a7a2008-08-28 21:40:38 +00009095 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00009096 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009097
Jim Grosbache8160032014-04-11 01:13:13 +00009098 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00009099 if (Op == N ||
9100 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9101 continue;
9102
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009103 SDValue BasePtr;
9104 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00009105 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9106 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00009107 // Don't create a indexed load / store with zero offset.
9108 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00009109 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00009110 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00009111
Chris Lattnereabc15c2006-11-11 00:56:29 +00009112 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00009113 // 1) All uses are load / store ops that use it as base ptr (and
9114 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00009115 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9116 // nor a successor of N. Otherwise, if Op is folded that would
9117 // create a cycle.
9118
Evan Chengcfc05132009-05-06 18:25:01 +00009119 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9120 continue;
9121
Chris Lattnereabc15c2006-11-11 00:56:29 +00009122 // Check for #1.
9123 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00009124 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009125 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00009126 continue;
9127
Chris Lattnereabc15c2006-11-11 00:56:29 +00009128 // If all the uses are load / store addresses, then don't do the
9129 // transformation.
9130 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9131 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00009132 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00009133 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009134 RealUse = true;
9135 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009136
Chris Lattnereabc15c2006-11-11 00:56:29 +00009137 if (!RealUse) {
9138 TryNext = true;
9139 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00009140 }
9141 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009142 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009143
Chris Lattnereabc15c2006-11-11 00:56:29 +00009144 if (TryNext)
9145 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00009146
Chris Lattnereabc15c2006-11-11 00:56:29 +00009147 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00009148 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009149 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00009150 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009151 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009152 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009153 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009154 ++PostIndexedNodes;
9155 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00009156 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009157 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009158 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009159 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009160 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009161 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009162 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009163 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9164 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009165 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009166 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00009167 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009168
Chris Lattnereabc15c2006-11-11 00:56:29 +00009169 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00009170 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009171
9172 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009173 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009174 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00009175 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009176 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00009177 }
9178 }
9179 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009180
Chris Lattnerffad2162006-11-11 00:39:41 +00009181 return false;
9182}
9183
Hal Finkel51e6fa22014-09-02 06:24:04 +00009184/// \brief Return the base-pointer arithmetic from an indexed \p LD.
9185SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9186 ISD::MemIndexedMode AM = LD->getAddressingMode();
9187 assert(AM != ISD::UNINDEXED);
9188 SDValue BP = LD->getOperand(1);
9189 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00009190
9191 // Some backends use TargetConstants for load offsets, but don't expect
9192 // TargetConstants in general ADD nodes. We can convert these constants into
9193 // regular Constants (if the constant is not opaque).
9194 assert((Inc.getOpcode() != ISD::TargetConstant ||
9195 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9196 "Cannot split out indexing using opaque target constants");
9197 if (Inc.getOpcode() == ISD::TargetConstant) {
9198 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9199 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
9200 ConstInc->getValueType(0));
9201 }
9202
Hal Finkel51e6fa22014-09-02 06:24:04 +00009203 unsigned Opc =
9204 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9205 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9206}
9207
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009208SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00009209 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009210 SDValue Chain = LD->getChain();
9211 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009212
Evan Chenga684cd22007-05-01 00:38:21 +00009213 // If load is not volatile and there are no uses of the loaded value (and
9214 // the updated indexed value in case of indexed loads), change uses of the
9215 // chain value into uses of the chain input (i.e. delete the dead load).
9216 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00009217 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00009218 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00009219 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00009220 // It's not safe to use the two value CombineTo variant here. e.g.
9221 // v1, chain2 = load chain1, loc
9222 // v2, chain3 = load chain2, loc
9223 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00009224 // Now we replace use of chain2 with chain1. This makes the second load
9225 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00009226 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009227 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009228 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009229 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009230 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009231 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009232 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00009233
Chandler Carruth18066972014-08-02 10:02:07 +00009234 if (N->use_empty())
9235 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00009236
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009237 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00009238 }
Evan Chengb68343c2007-05-01 08:53:39 +00009239 } else {
9240 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00009241 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00009242
Hal Finkele19006e2014-09-02 16:05:23 +00009243 // If this load has an opaque TargetConstant offset, then we cannot split
9244 // the indexing into an add/sub directly (that TargetConstant may not be
9245 // valid for a different type of node, and we cannot convert an opaque
9246 // target constant into a regular constant).
9247 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9248 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00009249
9250 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00009251 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00009252 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00009253 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00009254 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00009255 Index = SplitIndexingFromLoad(LD);
9256 // Try to fold the base pointer arithmetic into subsequent loads and
9257 // stores.
9258 AddUsersToWorklist(N);
9259 } else
9260 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00009261 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009262 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009263 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009264 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009265 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009266 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009267 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00009268 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009269 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00009270 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009271 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00009272 }
Evan Chenga684cd22007-05-01 00:38:21 +00009273 }
9274 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009275
Chris Lattnere260ed82005-10-10 22:04:48 +00009276 // If this load is directly stored, replace the load value with the stored
9277 // value.
9278 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009279 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00009280 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009281 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00009282 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9283 if (PrevST->getBasePtr() == Ptr &&
9284 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00009285 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00009286 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00009287 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009288
Evan Cheng43cd9e32010-04-01 06:04:33 +00009289 // Try to infer better alignment information than the load already has.
9290 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009291 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00009292 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9293 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00009294 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00009295 LD->getValueType(0),
9296 Chain, Ptr, LD->getPointerInfo(),
9297 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00009298 LD->isVolatile(), LD->isNonTemporal(),
9299 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +00009300 if (NewLoad.getNode() != N)
9301 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
Owen Andersonde89ecf2013-02-05 19:24:39 +00009302 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00009303 }
9304 }
9305
Eric Christopherf55d4712014-10-08 23:38:39 +00009306 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9307 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009308#ifndef NDEBUG
9309 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9310 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9311 UseAA = false;
9312#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009313 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009314 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009315 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009316
Jim Laskey708d0db2006-10-04 16:53:27 +00009317 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009318 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009319 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00009320
Jim Laskeyd07be232006-09-25 16:29:54 +00009321 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009322 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009323 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009324 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009325 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009326 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00009327 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009328 BetterChain, Ptr, LD->getMemoryVT(),
9329 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009330 }
Jim Laskeyd07be232006-09-25 16:29:54 +00009331
Jim Laskey708d0db2006-10-04 16:53:27 +00009332 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009333 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009334 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00009335
Nate Begeman879d8f12009-09-15 00:18:30 +00009336 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009337 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00009338
Jim Laskeydcf983c2006-10-13 23:32:28 +00009339 // Replace uses with load result and token factor. Don't add users
9340 // to work list.
9341 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009342 }
9343 }
9344
Evan Cheng357017f2006-11-03 03:06:21 +00009345 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00009346 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009347 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00009348
Quentin Colombetde0e0622013-10-11 18:29:42 +00009349 // Try to slice up N to more direct loads if the slices are mapped to
9350 // different register banks or pairing can take place.
9351 if (SliceUpLoad(N))
9352 return SDValue(N, 0);
9353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009354 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00009355}
9356
Quentin Colombetde0e0622013-10-11 18:29:42 +00009357namespace {
9358/// \brief Helper structure used to slice a load in smaller loads.
9359/// Basically a slice is obtained from the following sequence:
9360/// Origin = load Ty1, Base
9361/// Shift = srl Ty1 Origin, CstTy Amount
9362/// Inst = trunc Shift to Ty2
9363///
9364/// Then, it will be rewriten into:
9365/// Slice = load SliceTy, Base + SliceOffset
9366/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9367///
9368/// SliceTy is deduced from the number of bits that are actually used to
9369/// build Inst.
9370struct LoadedSlice {
9371 /// \brief Helper structure used to compute the cost of a slice.
9372 struct Cost {
9373 /// Are we optimizing for code size.
9374 bool ForCodeSize;
9375 /// Various cost.
9376 unsigned Loads;
9377 unsigned Truncates;
9378 unsigned CrossRegisterBanksCopies;
9379 unsigned ZExts;
9380 unsigned Shift;
9381
9382 Cost(bool ForCodeSize = false)
9383 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9384 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9385
9386 /// \brief Get the cost of one isolated slice.
9387 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9388 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9389 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9390 EVT TruncType = LS.Inst->getValueType(0);
9391 EVT LoadedType = LS.getLoadedType();
9392 if (TruncType != LoadedType &&
9393 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9394 ZExts = 1;
9395 }
9396
9397 /// \brief Account for slicing gain in the current cost.
9398 /// Slicing provide a few gains like removing a shift or a
9399 /// truncate. This method allows to grow the cost of the original
9400 /// load with the gain from this slice.
9401 void addSliceGain(const LoadedSlice &LS) {
9402 // Each slice saves a truncate.
9403 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9404 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9405 LS.Inst->getOperand(0).getValueType()))
9406 ++Truncates;
9407 // If there is a shift amount, this slice gets rid of it.
9408 if (LS.Shift)
9409 ++Shift;
9410 // If this slice can merge a cross register bank copy, account for it.
9411 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9412 ++CrossRegisterBanksCopies;
9413 }
9414
9415 Cost &operator+=(const Cost &RHS) {
9416 Loads += RHS.Loads;
9417 Truncates += RHS.Truncates;
9418 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9419 ZExts += RHS.ZExts;
9420 Shift += RHS.Shift;
9421 return *this;
9422 }
9423
9424 bool operator==(const Cost &RHS) const {
9425 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9426 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9427 ZExts == RHS.ZExts && Shift == RHS.Shift;
9428 }
9429
9430 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9431
9432 bool operator<(const Cost &RHS) const {
9433 // Assume cross register banks copies are as expensive as loads.
9434 // FIXME: Do we want some more target hooks?
9435 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9436 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9437 // Unless we are optimizing for code size, consider the
9438 // expensive operation first.
9439 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9440 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9441 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9442 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9443 }
9444
9445 bool operator>(const Cost &RHS) const { return RHS < *this; }
9446
9447 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9448
9449 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9450 };
9451 // The last instruction that represent the slice. This should be a
9452 // truncate instruction.
9453 SDNode *Inst;
9454 // The original load instruction.
9455 LoadSDNode *Origin;
9456 // The right shift amount in bits from the original load.
9457 unsigned Shift;
9458 // The DAG from which Origin came from.
9459 // This is used to get some contextual information about legal types, etc.
9460 SelectionDAG *DAG;
9461
Craig Topperc0196b12014-04-14 00:51:57 +00009462 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9463 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00009464 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9465
Quentin Colombetde0e0622013-10-11 18:29:42 +00009466 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9467 /// \return Result is \p BitWidth and has used bits set to 1 and
9468 /// not used bits set to 0.
9469 APInt getUsedBits() const {
9470 // Reproduce the trunc(lshr) sequence:
9471 // - Start from the truncated value.
9472 // - Zero extend to the desired bit width.
9473 // - Shift left.
9474 assert(Origin && "No original load to compare against.");
9475 unsigned BitWidth = Origin->getValueSizeInBits(0);
9476 assert(Inst && "This slice is not bound to an instruction");
9477 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9478 "Extracted slice is bigger than the whole type!");
9479 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9480 UsedBits.setAllBits();
9481 UsedBits = UsedBits.zext(BitWidth);
9482 UsedBits <<= Shift;
9483 return UsedBits;
9484 }
9485
9486 /// \brief Get the size of the slice to be loaded in bytes.
9487 unsigned getLoadedSize() const {
9488 unsigned SliceSize = getUsedBits().countPopulation();
9489 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9490 return SliceSize / 8;
9491 }
9492
9493 /// \brief Get the type that will be loaded for this slice.
9494 /// Note: This may not be the final type for the slice.
9495 EVT getLoadedType() const {
9496 assert(DAG && "Missing context");
9497 LLVMContext &Ctxt = *DAG->getContext();
9498 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9499 }
9500
9501 /// \brief Get the alignment of the load used for this slice.
9502 unsigned getAlignment() const {
9503 unsigned Alignment = Origin->getAlignment();
9504 unsigned Offset = getOffsetFromBase();
9505 if (Offset != 0)
9506 Alignment = MinAlign(Alignment, Alignment + Offset);
9507 return Alignment;
9508 }
9509
9510 /// \brief Check if this slice can be rewritten with legal operations.
9511 bool isLegal() const {
9512 // An invalid slice is not legal.
9513 if (!Origin || !Inst || !DAG)
9514 return false;
9515
9516 // Offsets are for indexed load only, we do not handle that.
9517 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9518 return false;
9519
9520 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9521
9522 // Check that the type is legal.
9523 EVT SliceType = getLoadedType();
9524 if (!TLI.isTypeLegal(SliceType))
9525 return false;
9526
9527 // Check that the load is legal for this type.
9528 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9529 return false;
9530
9531 // Check that the offset can be computed.
9532 // 1. Check its type.
9533 EVT PtrType = Origin->getBasePtr().getValueType();
9534 if (PtrType == MVT::Untyped || PtrType.isExtended())
9535 return false;
9536
9537 // 2. Check that it fits in the immediate.
9538 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9539 return false;
9540
9541 // 3. Check that the computation is legal.
9542 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9543 return false;
9544
9545 // Check that the zext is legal if it needs one.
9546 EVT TruncateType = Inst->getValueType(0);
9547 if (TruncateType != SliceType &&
9548 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9549 return false;
9550
9551 return true;
9552 }
9553
9554 /// \brief Get the offset in bytes of this slice in the original chunk of
9555 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00009556 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009557 uint64_t getOffsetFromBase() const {
9558 assert(DAG && "Missing context.");
9559 bool IsBigEndian =
9560 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9561 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9562 uint64_t Offset = Shift / 8;
9563 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9564 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9565 "The size of the original loaded type is not a multiple of a"
9566 " byte.");
9567 // If Offset is bigger than TySizeInBytes, it means we are loading all
9568 // zeros. This should have been optimized before in the process.
9569 assert(TySizeInBytes > Offset &&
9570 "Invalid shift amount for given loaded size");
9571 if (IsBigEndian)
9572 Offset = TySizeInBytes - Offset - getLoadedSize();
9573 return Offset;
9574 }
9575
9576 /// \brief Generate the sequence of instructions to load the slice
9577 /// represented by this object and redirect the uses of this slice to
9578 /// this new sequence of instructions.
9579 /// \pre this->Inst && this->Origin are valid Instructions and this
9580 /// object passed the legal check: LoadedSlice::isLegal returned true.
9581 /// \return The last instruction of the sequence used to load the slice.
9582 SDValue loadSlice() const {
9583 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9584 const SDValue &OldBaseAddr = Origin->getBasePtr();
9585 SDValue BaseAddr = OldBaseAddr;
9586 // Get the offset in that chunk of bytes w.r.t. the endianess.
9587 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9588 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9589 if (Offset) {
9590 // BaseAddr = BaseAddr + Offset.
9591 EVT ArithType = BaseAddr.getValueType();
9592 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9593 DAG->getConstant(Offset, ArithType));
9594 }
9595
9596 // Create the type of the loaded slice according to its size.
9597 EVT SliceType = getLoadedType();
9598
9599 // Create the load for the slice.
9600 SDValue LastInst = DAG->getLoad(
9601 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9602 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9603 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9604 // If the final type is not the same as the loaded type, this means that
9605 // we have to pad with zero. Create a zero extend for that.
9606 EVT FinalType = Inst->getValueType(0);
9607 if (SliceType != FinalType)
9608 LastInst =
9609 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9610 return LastInst;
9611 }
9612
9613 /// \brief Check if this slice can be merged with an expensive cross register
9614 /// bank copy. E.g.,
9615 /// i = load i32
9616 /// f = bitcast i32 i to float
9617 bool canMergeExpensiveCrossRegisterBankCopy() const {
9618 if (!Inst || !Inst->hasOneUse())
9619 return false;
9620 SDNode *Use = *Inst->use_begin();
9621 if (Use->getOpcode() != ISD::BITCAST)
9622 return false;
9623 assert(DAG && "Missing context");
9624 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9625 EVT ResVT = Use->getValueType(0);
9626 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9627 const TargetRegisterClass *ArgRC =
9628 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9629 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9630 return false;
9631
9632 // At this point, we know that we perform a cross-register-bank copy.
9633 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00009634 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00009635 // Assume bitcasts are cheap, unless both register classes do not
9636 // explicitly share a common sub class.
9637 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9638 return false;
9639
9640 // Check if it will be merged with the load.
9641 // 1. Check the alignment constraint.
9642 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9643 ResVT.getTypeForEVT(*DAG->getContext()));
9644
9645 if (RequiredAlignment > getAlignment())
9646 return false;
9647
9648 // 2. Check that the load is a legal operation for that type.
9649 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9650 return false;
9651
9652 // 3. Check that we do not have a zext in the way.
9653 if (Inst->getValueType(0) != getLoadedType())
9654 return false;
9655
9656 return true;
9657 }
9658};
9659}
9660
Quentin Colombetde0e0622013-10-11 18:29:42 +00009661/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9662/// \p UsedBits looks like 0..0 1..1 0..0.
9663static bool areUsedBitsDense(const APInt &UsedBits) {
9664 // If all the bits are one, this is dense!
9665 if (UsedBits.isAllOnesValue())
9666 return true;
9667
9668 // Get rid of the unused bits on the right.
9669 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9670 // Get rid of the unused bits on the left.
9671 if (NarrowedUsedBits.countLeadingZeros())
9672 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9673 // Check that the chunk of bits is completely used.
9674 return NarrowedUsedBits.isAllOnesValue();
9675}
9676
9677/// \brief Check whether or not \p First and \p Second are next to each other
9678/// in memory. This means that there is no hole between the bits loaded
9679/// by \p First and the bits loaded by \p Second.
9680static bool areSlicesNextToEachOther(const LoadedSlice &First,
9681 const LoadedSlice &Second) {
9682 assert(First.Origin == Second.Origin && First.Origin &&
9683 "Unable to match different memory origins.");
9684 APInt UsedBits = First.getUsedBits();
9685 assert((UsedBits & Second.getUsedBits()) == 0 &&
9686 "Slices are not supposed to overlap.");
9687 UsedBits |= Second.getUsedBits();
9688 return areUsedBitsDense(UsedBits);
9689}
9690
9691/// \brief Adjust the \p GlobalLSCost according to the target
9692/// paring capabilities and the layout of the slices.
9693/// \pre \p GlobalLSCost should account for at least as many loads as
9694/// there is in the slices in \p LoadedSlices.
9695static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9696 LoadedSlice::Cost &GlobalLSCost) {
9697 unsigned NumberOfSlices = LoadedSlices.size();
9698 // If there is less than 2 elements, no pairing is possible.
9699 if (NumberOfSlices < 2)
9700 return;
9701
9702 // Sort the slices so that elements that are likely to be next to each
9703 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009704 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9705 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9706 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9707 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9708 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00009709 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9710 // First (resp. Second) is the first (resp. Second) potentially candidate
9711 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00009712 const LoadedSlice *First = nullptr;
9713 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009714 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9715 // Set the beginning of the pair.
9716 First = Second) {
9717
9718 Second = &LoadedSlices[CurrSlice];
9719
9720 // If First is NULL, it means we start a new pair.
9721 // Get to the next slice.
9722 if (!First)
9723 continue;
9724
9725 EVT LoadedType = First->getLoadedType();
9726
9727 // If the types of the slices are different, we cannot pair them.
9728 if (LoadedType != Second->getLoadedType())
9729 continue;
9730
9731 // Check if the target supplies paired loads for this type.
9732 unsigned RequiredAlignment = 0;
9733 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9734 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00009735 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009736 continue;
9737 }
9738 // Check if we meet the alignment requirement.
9739 if (RequiredAlignment > First->getAlignment())
9740 continue;
9741
9742 // Check that both loads are next to each other in memory.
9743 if (!areSlicesNextToEachOther(*First, *Second))
9744 continue;
9745
9746 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9747 --GlobalLSCost.Loads;
9748 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00009749 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009750 }
9751}
9752
9753/// \brief Check the profitability of all involved LoadedSlice.
9754/// Currently, it is considered profitable if there is exactly two
9755/// involved slices (1) which are (2) next to each other in memory, and
9756/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9757///
9758/// Note: The order of the elements in \p LoadedSlices may be modified, but not
9759/// the elements themselves.
9760///
9761/// FIXME: When the cost model will be mature enough, we can relax
9762/// constraints (1) and (2).
9763static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9764 const APInt &UsedBits, bool ForCodeSize) {
9765 unsigned NumberOfSlices = LoadedSlices.size();
9766 if (StressLoadSlicing)
9767 return NumberOfSlices > 1;
9768
9769 // Check (1).
9770 if (NumberOfSlices != 2)
9771 return false;
9772
9773 // Check (2).
9774 if (!areUsedBitsDense(UsedBits))
9775 return false;
9776
9777 // Check (3).
9778 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9779 // The original code has one big load.
9780 OrigCost.Loads = 1;
9781 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9782 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9783 // Accumulate the cost of all the slices.
9784 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9785 GlobalSlicingCost += SliceCost;
9786
9787 // Account as cost in the original configuration the gain obtained
9788 // with the current slices.
9789 OrigCost.addSliceGain(LS);
9790 }
9791
9792 // If the target supports paired load, adjust the cost accordingly.
9793 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9794 return OrigCost > GlobalSlicingCost;
9795}
9796
9797/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9798/// operations, split it in the various pieces being extracted.
9799///
9800/// This sort of thing is introduced by SROA.
9801/// This slicing takes care not to insert overlapping loads.
9802/// \pre LI is a simple load (i.e., not an atomic or volatile load).
9803bool DAGCombiner::SliceUpLoad(SDNode *N) {
9804 if (Level < AfterLegalizeDAG)
9805 return false;
9806
9807 LoadSDNode *LD = cast<LoadSDNode>(N);
9808 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9809 !LD->getValueType(0).isInteger())
9810 return false;
9811
9812 // Keep track of already used bits to detect overlapping values.
9813 // In that case, we will just abort the transformation.
9814 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9815
9816 SmallVector<LoadedSlice, 4> LoadedSlices;
9817
9818 // Check if this load is used as several smaller chunks of bits.
9819 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9820 // of computation for each trunc.
9821 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9822 UI != UIEnd; ++UI) {
9823 // Skip the uses of the chain.
9824 if (UI.getUse().getResNo() != 0)
9825 continue;
9826
9827 SDNode *User = *UI;
9828 unsigned Shift = 0;
9829
9830 // Check if this is a trunc(lshr).
9831 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9832 isa<ConstantSDNode>(User->getOperand(1))) {
9833 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9834 User = *User->use_begin();
9835 }
9836
9837 // At this point, User is a Truncate, iff we encountered, trunc or
9838 // trunc(lshr).
9839 if (User->getOpcode() != ISD::TRUNCATE)
9840 return false;
9841
9842 // The width of the type must be a power of 2 and greater than 8-bits.
9843 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00009844 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00009845 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009846 unsigned Width = User->getValueSizeInBits(0);
9847 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9848 return 0;
9849
9850 // Build the slice for this chain of computations.
9851 LoadedSlice LS(User, LD, Shift, &DAG);
9852 APInt CurrentUsedBits = LS.getUsedBits();
9853
9854 // Check if this slice overlaps with another.
9855 if ((CurrentUsedBits & UsedBits) != 0)
9856 return false;
9857 // Update the bits used globally.
9858 UsedBits |= CurrentUsedBits;
9859
9860 // Check if the new slice would be legal.
9861 if (!LS.isLegal())
9862 return false;
9863
9864 // Record the slice.
9865 LoadedSlices.push_back(LS);
9866 }
9867
9868 // Abort slicing if it does not seem to be profitable.
9869 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9870 return false;
9871
9872 ++SlicedLoads;
9873
9874 // Rewrite each chain to use an independent load.
9875 // By construction, each chain can be represented by a unique load.
9876
9877 // Prepare the argument for the new token factor for all the slices.
9878 SmallVector<SDValue, 8> ArgChains;
9879 for (SmallVectorImpl<LoadedSlice>::const_iterator
9880 LSIt = LoadedSlices.begin(),
9881 LSItEnd = LoadedSlices.end();
9882 LSIt != LSItEnd; ++LSIt) {
9883 SDValue SliceInst = LSIt->loadSlice();
9884 CombineTo(LSIt->Inst, SliceInst, true);
9885 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9886 SliceInst = SliceInst.getOperand(0);
9887 assert(SliceInst->getOpcode() == ISD::LOAD &&
9888 "It takes more than a zext to get to the loaded slice!!");
9889 ArgChains.push_back(SliceInst.getValue(1));
9890 }
9891
9892 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00009893 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00009894 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9895 return true;
9896}
9897
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009898/// Check to see if V is (and load (ptr), imm), where the load is having
9899/// specific bytes cleared out. If so, return the byte size being masked out
9900/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00009901static std::pair<unsigned, unsigned>
9902CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9903 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009904
Chris Lattner4041ab62010-04-15 04:48:01 +00009905 // Check for the structure we're looking for.
9906 if (V->getOpcode() != ISD::AND ||
9907 !isa<ConstantSDNode>(V->getOperand(1)) ||
9908 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9909 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009910
Chris Lattner3245afd2010-04-15 06:10:49 +00009911 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00009912 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00009913 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00009914
Chris Lattner3245afd2010-04-15 06:10:49 +00009915 // The store should be chained directly to the load or be an operand of a
9916 // tokenfactor.
9917 if (LD == Chain.getNode())
9918 ; // ok.
9919 else if (Chain->getOpcode() != ISD::TokenFactor)
9920 return Result; // Fail.
9921 else {
9922 bool isOk = false;
9923 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9924 if (Chain->getOperand(i).getNode() == LD) {
9925 isOk = true;
9926 break;
9927 }
9928 if (!isOk) return Result;
9929 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009930
Chris Lattner4041ab62010-04-15 04:48:01 +00009931 // This only handles simple types.
9932 if (V.getValueType() != MVT::i16 &&
9933 V.getValueType() != MVT::i32 &&
9934 V.getValueType() != MVT::i64)
9935 return Result;
9936
9937 // Check the constant mask. Invert it so that the bits being masked out are
9938 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9939 // follow the sign bit for uniformity.
9940 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009941 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009942 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009943 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009944 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9945 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00009946
Chris Lattner4041ab62010-04-15 04:48:01 +00009947 // See if we have a continuous run of bits. If so, we have 0*1+0*
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00009948 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
Chris Lattner4041ab62010-04-15 04:48:01 +00009949 return Result;
9950
9951 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9952 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9953 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00009954
Chris Lattner4041ab62010-04-15 04:48:01 +00009955 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9956 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00009957 case 1:
9958 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00009959 case 4: break;
9960 default: return Result; // All one mask, or 5-byte mask.
9961 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009962
Chris Lattner4041ab62010-04-15 04:48:01 +00009963 // Verify that the first bit starts at a multiple of mask so that the access
9964 // is aligned the same as the access width.
9965 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009966
Chris Lattner4041ab62010-04-15 04:48:01 +00009967 Result.first = MaskedBytes;
9968 Result.second = NotMaskTZ/8;
9969 return Result;
9970}
9971
9972
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009973/// Check to see if IVal is something that provides a value as specified by
9974/// MaskInfo. If so, replace the specified store with a narrower store of
9975/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00009976static SDNode *
9977ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9978 SDValue IVal, StoreSDNode *St,
9979 DAGCombiner *DC) {
9980 unsigned NumBytes = MaskInfo.first;
9981 unsigned ByteShift = MaskInfo.second;
9982 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00009983
Chris Lattner4041ab62010-04-15 04:48:01 +00009984 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9985 // that uses this. If not, this is not a replacement.
9986 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9987 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00009988 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009989
Chris Lattner4041ab62010-04-15 04:48:01 +00009990 // Check that it is legal on the target to do this. It is legal if the new
9991 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9992 // legalization.
9993 MVT VT = MVT::getIntegerVT(NumBytes*8);
9994 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00009995 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009996
Chris Lattner4041ab62010-04-15 04:48:01 +00009997 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9998 // shifted by ByteShift and truncated down to NumBytes.
9999 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010000 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010001 DAG.getConstant(ByteShift*8,
10002 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +000010003
10004 // Figure out the offset for the store and the alignment of the access.
10005 unsigned StOffset;
10006 unsigned NewAlign = St->getAlignment();
10007
10008 if (DAG.getTargetLoweringInfo().isLittleEndian())
10009 StOffset = ByteShift;
10010 else
10011 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +000010012
Chris Lattner4041ab62010-04-15 04:48:01 +000010013 SDValue Ptr = St->getBasePtr();
10014 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010015 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +000010016 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
10017 NewAlign = MinAlign(NewAlign, StOffset);
10018 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010019
Chris Lattner4041ab62010-04-15 04:48:01 +000010020 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010021 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +000010022
Chris Lattner4041ab62010-04-15 04:48:01 +000010023 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +000010024 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +000010025 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +000010026 false, false, NewAlign).getNode();
10027}
10028
Evan Chenga9cda8a2009-05-28 00:35:15 +000010029
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010030/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10031/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10032/// narrowing the load and store if it would end up being a win for performance
10033/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +000010034SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10035 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +000010036 if (ST->isVolatile())
10037 return SDValue();
10038
Evan Chenga9cda8a2009-05-28 00:35:15 +000010039 SDValue Chain = ST->getChain();
10040 SDValue Value = ST->getValue();
10041 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010042 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010043
10044 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +000010045 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010046
10047 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +000010048
Chris Lattner4041ab62010-04-15 04:48:01 +000010049 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10050 // is a byte mask indicating a consecutive number of bytes, check to see if
10051 // Y is known to provide just those bytes. If so, we try to replace the
10052 // load + replace + store sequence with a single (narrower) store, which makes
10053 // the load dead.
10054 if (Opc == ISD::OR) {
10055 std::pair<unsigned, unsigned> MaskedLoad;
10056 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10057 if (MaskedLoad.first)
10058 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10059 Value.getOperand(1), ST,this))
10060 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +000010061
Chris Lattner4041ab62010-04-15 04:48:01 +000010062 // Or is commutative, so try swapping X and Y.
10063 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10064 if (MaskedLoad.first)
10065 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10066 Value.getOperand(0), ST,this))
10067 return SDValue(NewST, 0);
10068 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010069
Evan Chenga9cda8a2009-05-28 00:35:15 +000010070 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10071 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +000010072 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010073
10074 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +000010075 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10076 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +000010077 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010078 if (LD->getBasePtr() != Ptr ||
10079 LD->getPointerInfo().getAddrSpace() !=
10080 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +000010081 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010082
10083 // Find the type to narrow it the load / op / store to.
10084 SDValue N1 = Value.getOperand(1);
10085 unsigned BitWidth = N1.getValueSizeInBits();
10086 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10087 if (Opc == ISD::AND)
10088 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +000010089 if (Imm == 0 || Imm.isAllOnesValue())
10090 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010091 unsigned ShAmt = Imm.countTrailingZeros();
10092 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10093 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +000010094 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Elena Demikhovsky150d9f32015-01-22 12:07:59 +000010095 // The narrowing should be profitable, the load/store operation should be
Elena Demikhovsky9c264622015-01-22 09:39:08 +000010096 // legal (or custom) and the store size should be equal to the NewVT width.
Evan Chenga9cda8a2009-05-28 00:35:15 +000010097 while (NewBW < BitWidth &&
Elena Demikhovsky9c264622015-01-22 09:39:08 +000010098 (NewVT.getStoreSizeInBits() != NewBW ||
10099 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10100 !TLI.isNarrowingProfitable(VT, NewVT))) {
Evan Chenga9cda8a2009-05-28 00:35:15 +000010101 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +000010102 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +000010103 }
Evan Cheng6673ff02009-05-28 18:41:02 +000010104 if (NewBW >= BitWidth)
10105 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010106
10107 // If the lsb changed does not start at the type bitwidth boundary,
10108 // start at the previous one.
10109 if (ShAmt % NewBW)
10110 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +000010111 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10112 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +000010113 if ((Imm & Mask) == Imm) {
10114 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10115 if (Opc == ISD::AND)
10116 NewImm ^= APInt::getAllOnesValue(NewBW);
10117 uint64_t PtrOff = ShAmt / 8;
10118 // For big endian targets, we need to adjust the offset to the pointer to
10119 // load the correct bytes.
10120 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +000010121 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +000010122
10123 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +000010124 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010125 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +000010126 return SDValue();
10127
Andrew Trickef9de2a2013-05-25 02:42:55 +000010128 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010129 Ptr.getValueType(), Ptr,
10130 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010131 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010132 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010133 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +000010134 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010135 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010136 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010137 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +000010138 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010139 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010140 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010141 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +000010142 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +000010143
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010144 AddToWorklist(NewPtr.getNode());
10145 AddToWorklist(NewLD.getNode());
10146 AddToWorklist(NewVal.getNode());
10147 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +000010148 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +000010149 ++OpsNarrowed;
10150 return NewST;
10151 }
10152 }
10153
Evan Cheng6673ff02009-05-28 18:41:02 +000010154 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010155}
10156
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010157/// For a given floating point load / store pair, if the load value isn't used
10158/// by any other operations, then consider transforming the pair to integer
10159/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +000010160SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10161 StoreSDNode *ST = cast<StoreSDNode>(N);
10162 SDValue Chain = ST->getChain();
10163 SDValue Value = ST->getValue();
10164 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10165 Value.hasOneUse() &&
10166 Chain == SDValue(Value.getNode(), 1)) {
10167 LoadSDNode *LD = cast<LoadSDNode>(Value);
10168 EVT VT = LD->getMemoryVT();
10169 if (!VT.isFloatingPoint() ||
10170 VT != ST->getMemoryVT() ||
10171 LD->isNonTemporal() ||
10172 ST->isNonTemporal() ||
10173 LD->getPointerInfo().getAddrSpace() != 0 ||
10174 ST->getPointerInfo().getAddrSpace() != 0)
10175 return SDValue();
10176
10177 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10178 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10179 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10180 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10181 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10182 return SDValue();
10183
10184 unsigned LDAlign = LD->getAlignment();
10185 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +000010186 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010187 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +000010188 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10189 return SDValue();
10190
Andrew Trickef9de2a2013-05-25 02:42:55 +000010191 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +000010192 LD->getChain(), LD->getBasePtr(),
10193 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010194 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +000010195
Andrew Trickef9de2a2013-05-25 02:42:55 +000010196 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +000010197 NewLD, ST->getBasePtr(),
10198 ST->getPointerInfo(),
10199 false, false, STAlign);
10200
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010201 AddToWorklist(NewLD.getNode());
10202 AddToWorklist(NewST.getNode());
10203 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +000010204 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +000010205 ++LdStFP2Int;
10206 return NewST;
10207 }
10208
10209 return SDValue();
10210}
10211
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010212namespace {
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010213/// Helper struct to parse and store a memory address as base + index + offset.
10214/// We ignore sign extensions when it is safe to do so.
10215/// The following two expressions are not equivalent. To differentiate we need
10216/// to store whether there was a sign extension involved in the index
10217/// computation.
10218/// (load (i64 add (i64 copyfromreg %c)
10219/// (i64 signextend (add (i8 load %index)
10220/// (i8 1))))
10221/// vs
10222///
10223/// (load (i64 add (i64 copyfromreg %c)
10224/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10225/// (i32 1)))))
10226struct BaseIndexOffset {
10227 SDValue Base;
10228 SDValue Index;
10229 int64_t Offset;
10230 bool IsIndexSignExt;
10231
10232 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10233
10234 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10235 bool IsIndexSignExt) :
10236 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10237
10238 bool equalBaseIndex(const BaseIndexOffset &Other) {
10239 return Other.Base == Base && Other.Index == Index &&
10240 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010241 }
10242
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010243 /// Parses tree in Ptr for base, index, offset addresses.
10244 static BaseIndexOffset match(SDValue Ptr) {
10245 bool IsIndexSignExt = false;
10246
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010247 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10248 // instruction, then it could be just the BASE or everything else we don't
10249 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010250 if (Ptr->getOpcode() != ISD::ADD)
10251 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10252
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010253 // We know that we have at least an ADD instruction. Try to pattern match
10254 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010255 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10256 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10257 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10258 IsIndexSignExt);
10259 }
10260
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010261 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010262 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010263 // (i64 add (i64 %array_ptr)
10264 // (i64 mul (i64 %induction_var)
10265 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010266 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010267 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010268
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010269 // Look at Base + Index + Offset cases.
10270 SDValue Base = Ptr->getOperand(0);
10271 SDValue IndexOffset = Ptr->getOperand(1);
10272
10273 // Skip signextends.
10274 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10275 IndexOffset = IndexOffset->getOperand(0);
10276 IsIndexSignExt = true;
10277 }
10278
10279 // Either the case of Base + Index (no offset) or something else.
10280 if (IndexOffset->getOpcode() != ISD::ADD)
10281 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10282
10283 // Now we have the case of Base + Index + offset.
10284 SDValue Index = IndexOffset->getOperand(0);
10285 SDValue Offset = IndexOffset->getOperand(1);
10286
10287 if (!isa<ConstantSDNode>(Offset))
10288 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10289
10290 // Ignore signextends.
10291 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10292 Index = Index->getOperand(0);
10293 IsIndexSignExt = true;
10294 } else IsIndexSignExt = false;
10295
10296 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10297 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10298 }
10299};
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010300} // namespace
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010301
Sanjay Patel37c41c12015-01-22 18:21:26 +000010302bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10303 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
Quentin Colombet308b1712015-01-27 23:58:01 +000010304 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010305 // Make sure we have something to merge.
Quentin Colombet308b1712015-01-27 23:58:01 +000010306 if (NumElem < 2)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010307 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010308
Sanjay Patel37c41c12015-01-22 18:21:26 +000010309 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10310 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
Akira Hatanakac6fab802015-04-08 20:34:53 +000010311 unsigned LatestNodeUsed = 0;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010312
Quentin Colombet308b1712015-01-27 23:58:01 +000010313 for (unsigned i=0; i < NumElem; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010314 // Find a chain for the new wide-store operand. Notice that some
10315 // of the store nodes that we found may not be selected for inclusion
10316 // in the wide store. The chain we use needs to be the chain of the
Akira Hatanakac6fab802015-04-08 20:34:53 +000010317 // latest store node which is *used* and replaced by the wide store.
10318 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10319 LatestNodeUsed = i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010320 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010321
Akira Hatanakac6fab802015-04-08 20:34:53 +000010322 // The latest Node in the DAG.
10323 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010324 SDLoc DL(StoreNodes[0].MemNode);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010325
Sanjay Patel37c41c12015-01-22 18:21:26 +000010326 SDValue StoredVal;
10327 if (UseVector) {
Quentin Colombet308b1712015-01-27 23:58:01 +000010328 // Find a legal type for the vector store.
10329 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010330 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10331 if (IsConstantSrc) {
10332 // A vector store with a constant source implies that the constant is
10333 // zero; we only handle merging stores of constant zeros because the zero
10334 // can be materialized without a load.
10335 // It may be beneficial to loosen this restriction to allow non-zero
10336 // store merging.
10337 StoredVal = DAG.getConstant(0, Ty);
10338 } else {
10339 SmallVector<SDValue, 8> Ops;
Quentin Colombet308b1712015-01-27 23:58:01 +000010340 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010341 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10342 SDValue Val = St->getValue();
Quentin Colombet308b1712015-01-27 23:58:01 +000010343 // All of the operands of a BUILD_VECTOR must have the same type.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010344 if (Val.getValueType() != MemVT)
10345 return false;
10346 Ops.push_back(Val);
10347 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010348
Sanjay Patel37c41c12015-01-22 18:21:26 +000010349 // Build the extracted vector elements back into a vector.
Quentin Colombet308b1712015-01-27 23:58:01 +000010350 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010351 }
10352 } else {
10353 // We should always use a vector store when merging extracted vector
10354 // elements, so this path implies a store of constants.
10355 assert(IsConstantSrc && "Merged vector elements should use vector store");
10356
Quentin Colombet308b1712015-01-27 23:58:01 +000010357 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010358 APInt StoreInt(StoreBW, 0);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010359
Sanjay Patel37c41c12015-01-22 18:21:26 +000010360 // Construct a single integer constant which is made of the smaller
10361 // constant inputs.
10362 bool IsLE = TLI.isLittleEndian();
Quentin Colombet308b1712015-01-27 23:58:01 +000010363 for (unsigned i = 0; i < NumElem ; ++i) {
10364 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010365 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10366 SDValue Val = St->getValue();
10367 StoreInt <<= ElementSizeBytes*8;
10368 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10369 StoreInt |= C->getAPIntValue().zext(StoreBW);
10370 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10371 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10372 } else {
10373 llvm_unreachable("Invalid constant element type");
10374 }
10375 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010376
Sanjay Patel37c41c12015-01-22 18:21:26 +000010377 // Create the new Load and Store operations.
10378 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10379 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10380 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010381
Akira Hatanakac6fab802015-04-08 20:34:53 +000010382 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010383 FirstInChain->getBasePtr(),
10384 FirstInChain->getPointerInfo(),
10385 false, false,
10386 FirstInChain->getAlignment());
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010387
Akira Hatanakac6fab802015-04-08 20:34:53 +000010388 // Replace the last store with the new store
10389 CombineTo(LatestOp, NewStore);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010390 // Erase all other stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010391 for (unsigned i = 0; i < NumElem ; ++i) {
Akira Hatanakac6fab802015-04-08 20:34:53 +000010392 if (StoreNodes[i].MemNode == LatestOp)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010393 continue;
10394 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10395 // ReplaceAllUsesWith will replace all uses that existed when it was
10396 // called, but graph optimizations may cause new ones to appear. For
10397 // example, the case in pr14333 looks like
10398 //
10399 // St's chain -> St -> another store -> X
10400 //
10401 // And the only difference from St to the other store is the chain.
10402 // When we change it's chain to be St's chain they become identical,
10403 // get CSEed and the net result is that X is now a use of St.
10404 // Since we know that St is redundant, just iterate.
10405 while (!St->use_empty())
10406 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10407 deleteAndRecombine(St);
10408 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010409
Sanjay Patel37c41c12015-01-22 18:21:26 +000010410 return true;
10411}
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010412
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010413bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
Paul Robinson093d6e12015-02-26 18:47:57 +000010414 if (OptLevel == CodeGenOpt::None)
10415 return false;
10416
Quentin Colombet308b1712015-01-27 23:58:01 +000010417 EVT MemVT = St->getMemoryVT();
10418 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +000010419 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10420 Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010421
Quentin Colombet308b1712015-01-27 23:58:01 +000010422 // Don't merge vectors into wider inputs.
10423 if (MemVT.isVector() || !MemVT.isSimple())
10424 return false;
10425
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010426 // Perform an early exit check. Do not bother looking at stored values that
Sanjay Patel37c41c12015-01-22 18:21:26 +000010427 // are not constants, loads, or extracted vector elements.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010428 SDValue StoredVal = St->getValue();
10429 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010430 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10431 isa<ConstantFPSDNode>(StoredVal);
Quentin Colombet308b1712015-01-27 23:58:01 +000010432 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010433
Quentin Colombet308b1712015-01-27 23:58:01 +000010434 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010435 return false;
10436
10437 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +000010438 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010439 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10440 return false;
10441
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010442 // This holds the base pointer, index, and the offset in bytes from the base
10443 // pointer.
10444 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010445
10446 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010447 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010448 return false;
10449
10450 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010451 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010452 return false;
10453
Nadav Rotem307d7672012-11-29 00:00:08 +000010454 // Save the LoadSDNodes that we find in the chain.
10455 // We need to make sure that these nodes do not interfere with
10456 // any of the store nodes.
10457 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10458
10459 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010460 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +000010461
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010462 // Walk up the chain and look for nodes with offsets from the same
10463 // base pointer. Stop when reaching an instruction with a different kind
10464 // or instruction which has a different base pointer.
10465 unsigned Seq = 0;
10466 StoreSDNode *Index = St;
10467 while (Index) {
10468 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +000010469 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010470 break;
10471
10472 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010473 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010474
10475 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010476 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010477 break;
10478
10479 // Check that the alignment is the same.
10480 if (Index->getAlignment() != St->getAlignment())
10481 break;
10482
10483 // The memory operands must not be volatile.
10484 if (Index->isVolatile() || Index->isIndexed())
10485 break;
10486
10487 // No truncation.
10488 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10489 if (St->isTruncatingStore())
10490 break;
10491
10492 // The stored memory type must be the same.
10493 if (Index->getMemoryVT() != MemVT)
10494 break;
10495
10496 // We do not allow unaligned stores because we want to prevent overriding
10497 // stores.
10498 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10499 break;
10500
10501 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010502 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010503
Nadav Rotem307d7672012-11-29 00:00:08 +000010504 // Find the next memory operand in the chain. If the next operand in the
10505 // chain is a store then move up and continue the scan with the next
10506 // memory operand. If the next operand is a load save it and use alias
10507 // information to check if it interferes with anything.
10508 SDNode *NextInChain = Index->getChain().getNode();
10509 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +000010510 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +000010511 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +000010512 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +000010513 break;
10514 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +000010515 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +000010516 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +000010517 break;
10518 }
10519
Nadav Rotem307d7672012-11-29 00:00:08 +000010520 // Save the load node for later. Continue the scan.
10521 AliasLoadNodes.push_back(Ldn);
10522 NextInChain = Ldn->getChain().getNode();
10523 continue;
10524 } else {
Craig Topperc0196b12014-04-14 00:51:57 +000010525 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +000010526 break;
10527 }
10528 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010529 }
10530
10531 // Check if there is anything to merge.
10532 if (StoreNodes.size() < 2)
10533 return false;
10534
10535 // Sort the memory operands according to their distance from the base pointer.
10536 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +000010537 [](MemOpLink LHS, MemOpLink RHS) {
10538 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10539 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10540 LHS.SequenceNum > RHS.SequenceNum);
10541 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010542
10543 // Scan the memory operations on the chain and find the first non-consecutive
10544 // store memory address.
10545 unsigned LastConsecutiveStore = 0;
10546 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +000010547 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10548
10549 // Check that the addresses are consecutive starting from the second
10550 // element in the list of stores.
10551 if (i > 0) {
10552 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10553 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10554 break;
10555 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010556
Nadav Rotem307d7672012-11-29 00:00:08 +000010557 bool Alias = false;
10558 // Check if this store interferes with any of the loads that we found.
10559 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10560 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10561 Alias = true;
10562 break;
10563 }
Nadav Rotem307d7672012-11-29 00:00:08 +000010564 // We found a load that alias with this store. Stop the sequence.
10565 if (Alias)
10566 break;
10567
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010568 // Mark this node as useful.
10569 LastConsecutiveStore = i;
10570 }
10571
10572 // The node with the lowest store address.
10573 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10574
10575 // Store the constants into memory as one consecutive store.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010576 if (IsConstantSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010577 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010578 unsigned LastLegalVectorType = 0;
10579 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010580 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10581 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10582 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010583
10584 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010585 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010586 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010587 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010588 } else {
Alp Tokerf907b892013-12-05 05:44:44 +000010589 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010590 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010591 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010592
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010593 // Find a legal type for the constant store.
10594 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10595 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10596 if (TLI.isTypeLegal(StoreTy))
10597 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010598 // Or check whether a truncstore is legal.
10599 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10600 TargetLowering::TypePromoteInteger) {
10601 EVT LegalizedStoredValueTy =
10602 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10603 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10604 LastLegalType = i+1;
10605 }
Nadav Rotemb27777f2012-10-04 22:35:15 +000010606
10607 // Find a legal type for the vector store.
10608 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10609 if (TLI.isTypeLegal(Ty))
10610 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010611 }
10612
Bob Wilson3365b802012-12-20 01:36:20 +000010613 // We only use vectors if the constant is known to be zero and the
10614 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010615 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +000010616 LastLegalVectorType = 0;
10617
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010618 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +000010619 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010620 return false;
10621
Nadav Rotem495b1a42013-02-14 18:28:52 +000010622 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010623 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10624
Sanjay Patel37c41c12015-01-22 18:21:26 +000010625 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10626 true, UseVector);
10627 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010628
Sanjay Patel37c41c12015-01-22 18:21:26 +000010629 // When extracting multiple vector elements, try to store them
10630 // in one vector store rather than a sequence of scalar stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010631 if (IsExtractVecEltSrc) {
10632 unsigned NumElem = 0;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010633 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10634 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Quentin Colombet308b1712015-01-27 23:58:01 +000010635 SDValue StoredVal = St->getValue();
Sanjay Patel37c41c12015-01-22 18:21:26 +000010636 // This restriction could be loosened.
10637 // Bail out if any stored values are not elements extracted from a vector.
10638 // It should be possible to handle mixed sources, but load sources need
10639 // more careful handling (see the block of code below that handles
10640 // consecutive loads).
Quentin Colombet308b1712015-01-27 23:58:01 +000010641 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010642 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010643
Nadav Rotemb27777f2012-10-04 22:35:15 +000010644 // Find a legal type for the vector store.
Quentin Colombet308b1712015-01-27 23:58:01 +000010645 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10646 if (TLI.isTypeLegal(Ty))
10647 NumElem = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010648 }
10649
Quentin Colombet308b1712015-01-27 23:58:01 +000010650 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010651 false, true);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010652 }
10653
10654 // Below we handle the case of multiple consecutive stores that
10655 // come from multiple consecutive loads. We merge them into a single
10656 // wide load and a single wide store.
10657
10658 // Look for load nodes which are used by the stored values.
10659 SmallVector<MemOpLink, 8> LoadNodes;
10660
10661 // Find acceptable loads. Loads need to have the same chain (token factor),
10662 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010663 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010664 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10665 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10666 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10667 if (!Ld) break;
10668
10669 // Loads must only have one use.
10670 if (!Ld->hasNUsesOfValue(1, 0))
10671 break;
10672
10673 // Check that the alignment is the same as the stores.
10674 if (Ld->getAlignment() != St->getAlignment())
10675 break;
10676
10677 // The memory operands must not be volatile.
10678 if (Ld->isVolatile() || Ld->isIndexed())
10679 break;
10680
10681 // We do not accept ext loads.
10682 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10683 break;
10684
10685 // The stored memory type must be the same.
10686 if (Ld->getMemoryVT() != MemVT)
10687 break;
10688
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010689 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010690 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010691 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010692 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010693 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010694 break;
10695 } else {
10696 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010697 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010698 }
10699
10700 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010701 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010702 }
10703
10704 if (LoadNodes.size() < 2)
10705 return false;
10706
James Molloyce45be02014-08-02 14:51:24 +000010707 // If we have load/store pair instructions and we only have two values,
10708 // don't bother.
10709 unsigned RequiredAlignment;
10710 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10711 St->getAlignment() >= RequiredAlignment)
10712 return false;
10713
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010714 // Scan the memory operations on the chain and find the first non-consecutive
10715 // load memory address. These variables hold the index in the store node
10716 // array.
10717 unsigned LastConsecutiveLoad = 0;
10718 // This variable refers to the size and not index in the array.
10719 unsigned LastLegalVectorType = 0;
10720 unsigned LastLegalIntegerType = 0;
10721 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +000010722 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10723 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10724 // All loads much share the same chain.
10725 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10726 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +000010727
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010728 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10729 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10730 break;
10731 LastConsecutiveLoad = i;
10732
10733 // Find a legal type for the vector store.
10734 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10735 if (TLI.isTypeLegal(StoreTy))
10736 LastLegalVectorType = i + 1;
10737
10738 // Find a legal type for the integer store.
10739 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10740 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10741 if (TLI.isTypeLegal(StoreTy))
10742 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010743 // Or check whether a truncstore and extload is legal.
10744 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10745 TargetLowering::TypePromoteInteger) {
10746 EVT LegalizedStoredValueTy =
10747 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10748 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010749 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10750 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10751 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010752 LastLegalIntegerType = i+1;
10753 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010754 }
10755
10756 // Only use vector types if the vector type is larger than the integer type.
10757 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010758 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010759 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10760
10761 // We add +1 here because the LastXXX variables refer to location while
10762 // the NumElem refers to array/index size.
10763 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10764 NumElem = std::min(LastLegalType, NumElem);
10765
10766 if (NumElem < 2)
10767 return false;
10768
Akira Hatanakac6fab802015-04-08 20:34:53 +000010769 // The latest Node in the DAG.
10770 unsigned LatestNodeUsed = 0;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010771 for (unsigned i=1; i<NumElem; ++i) {
10772 // Find a chain for the new wide-store operand. Notice that some
10773 // of the store nodes that we found may not be selected for inclusion
10774 // in the wide store. The chain we use needs to be the chain of the
Akira Hatanakac6fab802015-04-08 20:34:53 +000010775 // latest store node which is *used* and replaced by the wide store.
10776 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10777 LatestNodeUsed = i;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010778 }
10779
Akira Hatanakac6fab802015-04-08 20:34:53 +000010780 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10781
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010782 // Find if it is better to use vectors or integers to load and store
10783 // to memory.
10784 EVT JointMemOpVT;
10785 if (UseVectorTy) {
10786 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10787 } else {
10788 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10789 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10790 }
10791
Andrew Trickef9de2a2013-05-25 02:42:55 +000010792 SDLoc LoadDL(LoadNodes[0].MemNode);
10793 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010794
10795 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10796 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10797 FirstLoad->getChain(),
10798 FirstLoad->getBasePtr(),
10799 FirstLoad->getPointerInfo(),
10800 false, false, false,
10801 FirstLoad->getAlignment());
10802
Akira Hatanakac6fab802015-04-08 20:34:53 +000010803 SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010804 FirstInChain->getBasePtr(),
10805 FirstInChain->getPointerInfo(), false, false,
10806 FirstInChain->getAlignment());
10807
Nadav Rotemac920662012-10-03 19:30:31 +000010808 // Replace one of the loads with the new load.
10809 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10810 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10811 SDValue(NewLoad.getNode(), 1));
10812
10813 // Remove the rest of the load chains.
10814 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010815 // Replace all chain users of the old load nodes with the chain of the new
10816 // load node.
10817 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +000010818 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10819 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010820
Akira Hatanakac6fab802015-04-08 20:34:53 +000010821 // Replace the last store with the new store.
10822 CombineTo(LatestOp, NewStore);
Nadav Rotemac920662012-10-03 19:30:31 +000010823 // Erase all other stores.
10824 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010825 // Remove all Store nodes.
Akira Hatanakac6fab802015-04-08 20:34:53 +000010826 if (StoreNodes[i].MemNode == LatestOp)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010827 continue;
10828 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10829 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +000010830 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010831 }
10832
10833 return true;
10834}
10835
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010836SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +000010837 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010838 SDValue Chain = ST->getChain();
10839 SDValue Value = ST->getValue();
10840 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010841
Evan Chenga4cf58a2007-05-07 21:27:48 +000010842 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +000010843 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +000010844 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010845 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +000010846 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010847 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010848 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +000010849 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +000010850 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010851 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +000010852 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010853 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +000010854 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010855 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010856 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +000010857 }
Owen Andersona5192842011-04-14 17:30:49 +000010858
Chris Lattner41c80e82011-04-09 02:32:02 +000010859 // Turn 'store undef, Ptr' -> nothing.
10860 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10861 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +000010862
Nate Begeman8e20c762006-12-11 02:23:46 +000010863 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +000010864 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +000010865 // NOTE: If the original store is volatile, this transform must not increase
10866 // the number of stores. For example, on x86-32 an f64 can be stored in one
10867 // processor operation but an i64 (which is not legal) requires two. So the
10868 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +000010869 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010870 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +000010871 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +000010872 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +000010873 case MVT::f16: // We don't do this for these yet.
10874 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +000010875 case MVT::f128:
10876 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +000010877 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010878 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +000010879 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010880 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +000010881 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +000010882 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010883 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010884 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000010885 }
10886 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010887 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000010888 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000010889 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010890 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +000010891 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +000010892 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010893 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010894 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000010895 }
Owen Andersona5192842011-04-14 17:30:49 +000010896
Chris Lattner41c80e82011-04-09 02:32:02 +000010897 if (!ST->isVolatile() &&
10898 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000010899 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000010900 // argument passing. Since this is so common, custom legalize the
10901 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000010902 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +000010903 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10904 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000010905 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010906
Dan Gohman2af30632007-07-09 22:18:38 +000010907 unsigned Alignment = ST->getAlignment();
10908 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000010909 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000010910 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000010911
Andrew Trickef9de2a2013-05-25 02:42:55 +000010912 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000010913 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000010914 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010915 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010916 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +000010917 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000010918 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010919 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000010920 Ptr, ST->getPointerInfo().getWithOffset(4),
10921 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010922 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010923 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000010924 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010925 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010926
Chris Lattnerb7524b62006-12-12 04:16:14 +000010927 break;
Evan Cheng21836982006-12-11 17:25:19 +000010928 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010929 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010930 }
10931
Evan Cheng43cd9e32010-04-01 06:04:33 +000010932 // Try to infer better alignment information than the store already has.
10933 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000010934 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersondb420122015-03-19 22:48:57 +000010935 if (Align > ST->getAlignment()) {
10936 SDValue NewStore =
10937 DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000010938 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010939 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000010940 ST->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +000010941 if (NewStore.getNode() != N)
10942 return CombineTo(ST, NewStore, true);
10943 }
Evan Cheng43cd9e32010-04-01 06:04:33 +000010944 }
10945 }
10946
Evan Chengd42641c2011-02-02 01:06:55 +000010947 // Try transforming a pair floating point load / store ops to integer
10948 // load / store ops.
10949 SDValue NewST = TransformFPLoadStorePair(N);
10950 if (NewST.getNode())
10951 return NewST;
10952
Eric Christopherf55d4712014-10-08 23:38:39 +000010953 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10954 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000010955#ifndef NDEBUG
10956 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10957 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10958 UseAA = false;
10959#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000010960 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000010961 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010962 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010963
Jim Laskey708d0db2006-10-04 16:53:27 +000010964 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000010965 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010966 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000010967
10968 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010969 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010970 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010971 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010972 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010973 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010974 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010975 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010976
Jim Laskeyd07be232006-09-25 16:29:54 +000010977 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010978 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000010979 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010980
Nate Begeman879d8f12009-09-15 00:18:30 +000010981 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010982 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000010983
Jim Laskeydcf983c2006-10-13 23:32:28 +000010984 // Don't add users to work list.
10985 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000010986 }
Jim Laskey5d19d592006-09-21 16:28:59 +000010987 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010988
Evan Cheng33157702006-11-05 09:31:14 +000010989 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000010990 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010991 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000010992
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010993 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010994 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010995 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000010996 // See if we can simplify the input to this truncstore with knowledge that
10997 // only the low bits are being used. For example:
10998 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000010999 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000011000 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000011001 APInt::getLowBitsSet(
11002 Value.getValueType().getScalarType().getSizeInBits(),
11003 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011004 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011005 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000011006 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011007 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000011008
Chris Lattnerf47e3062007-10-13 06:58:48 +000011009 // Otherwise, see if we can simplify the operation with
11010 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000011011 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011012 APInt::getLowBitsSet(
11013 Value.getValueType().getScalarType().getSizeInBits(),
11014 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011015 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000011016 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011017
Chris Lattner3f9c6a72007-12-29 06:26:16 +000011018 // If this is a load followed by a store to the same location, then the store
11019 // is dead/noop.
11020 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000011021 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011022 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000011023 // There can't be any side effects between the load and store, such as
11024 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011025 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000011026 // The store is dead, remove it.
11027 return Chain;
11028 }
11029 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000011030
James Molloy463db9a2014-09-27 17:02:54 +000011031 // If this is a store followed by a store with the same value to the same
11032 // location, then the store is dead/noop.
11033 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11034 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11035 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11036 ST1->isUnindexed() && !ST1->isVolatile()) {
11037 // The store is dead, remove it.
11038 return Chain;
11039 }
11040 }
11041
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011042 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11043 // truncating store. We can do this even if this is already a truncstore.
11044 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011045 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011046 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000011047 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011048 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011049 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011050 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000011051
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011052 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000011053 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000011054 if (!LegalTypes) {
11055 bool EverChanged = false;
11056
11057 do {
11058 // There can be multiple store sequences on the same chain.
11059 // Keep trying to merge store sequences until we are unable to do so
11060 // or until we merge the last store on the chain.
11061 bool Changed = MergeConsecutiveStores(ST);
11062 EverChanged |= Changed;
11063 if (!Changed) break;
11064 } while (ST->getOpcode() != ISD::DELETED_NODE);
11065
11066 if (EverChanged)
11067 return SDValue(N, 0);
11068 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011069
Evan Chenga9cda8a2009-05-28 00:35:15 +000011070 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000011071}
11072
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011073SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11074 SDValue InVec = N->getOperand(0);
11075 SDValue InVal = N->getOperand(1);
11076 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011077 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011078
Bob Wilson42603952010-05-19 23:42:58 +000011079 // If the inserted element is an UNDEF, just use the input vector.
11080 if (InVal.getOpcode() == ISD::UNDEF)
11081 return InVec;
11082
Nadav Rotemdb2f5482011-02-12 14:40:33 +000011083 EVT VT = InVec.getValueType();
11084
Owen Andersonb2c80da2011-02-25 21:41:48 +000011085 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000011086 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11087 return SDValue();
11088
Eli Friedmanb7910b72011-09-09 21:04:06 +000011089 // Check that we know which element is being inserted
11090 if (!isa<ConstantSDNode>(EltNo))
11091 return SDValue();
11092 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011093
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000011094 // Canonicalize insert_vector_elt dag nodes.
11095 // Example:
11096 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11097 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11098 //
11099 // Do this only if the child insert_vector node has one use; also
11100 // do this only if indices are both constants and Idx1 < Idx0.
11101 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11102 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11103 unsigned OtherElt =
11104 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11105 if (Elt < OtherElt) {
11106 // Swap nodes.
11107 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11108 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011109 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000011110 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11111 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11112 }
11113 }
11114
Eli Friedmanb7910b72011-09-09 21:04:06 +000011115 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11116 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11117 // vector elements.
11118 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000011119 // Do not combine these two vectors if the output vector will not replace
11120 // the input vector.
11121 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000011122 Ops.append(InVec.getNode()->op_begin(),
11123 InVec.getNode()->op_end());
11124 } else if (InVec.getOpcode() == ISD::UNDEF) {
11125 unsigned NElts = VT.getVectorNumElements();
11126 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11127 } else {
11128 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011129 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000011130
11131 // Insert the element
11132 if (Elt < Ops.size()) {
11133 // All the operands of BUILD_VECTOR must have the same type;
11134 // we enforce that here.
11135 EVT OpVT = Ops[0].getValueType();
11136 if (InVal.getValueType() != OpVT)
11137 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11138 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11139 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11140 Ops[Elt] = InVal;
11141 }
11142
11143 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000011144 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000011145}
11146
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011147SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11148 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11149 EVT ResultVT = EVE->getValueType(0);
11150 EVT VecEltVT = InVecVT.getVectorElementType();
11151 unsigned Align = OriginalLoad->getAlignment();
11152 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11153 VecEltVT.getTypeForEVT(*DAG.getContext()));
11154
11155 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11156 return SDValue();
11157
11158 Align = NewAlign;
11159
11160 SDValue NewPtr = OriginalLoad->getBasePtr();
11161 SDValue Offset;
11162 EVT PtrType = NewPtr.getValueType();
11163 MachinePointerInfo MPI;
11164 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11165 int Elt = ConstEltNo->getZExtValue();
11166 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11167 if (TLI.isBigEndian())
11168 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11169 Offset = DAG.getConstant(PtrOff, PtrType);
11170 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11171 } else {
11172 Offset = DAG.getNode(
11173 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
11174 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
11175 if (TLI.isBigEndian())
11176 Offset = DAG.getNode(
11177 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
11178 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
11179 MPI = OriginalLoad->getPointerInfo();
11180 }
11181 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
11182
11183 // The replacement we need to do here is a little tricky: we need to
11184 // replace an extractelement of a load with a load.
11185 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11186 // Note that this replacement assumes that the extractvalue is the only
11187 // use of the load; that's okay because we don't want to perform this
11188 // transformation in other cases anyway.
11189 SDValue Load;
11190 SDValue Chain;
11191 if (ResultVT.bitsGT(VecEltVT)) {
11192 // If the result type of vextract is wider than the load, then issue an
11193 // extending load instead.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000011194 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11195 VecEltVT)
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011196 ? ISD::ZEXTLOAD
11197 : ISD::EXTLOAD;
11198 Load = DAG.getExtLoad(
11199 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11200 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11201 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11202 Chain = Load.getValue(1);
11203 } else {
11204 Load = DAG.getLoad(
11205 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11206 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11207 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11208 Chain = Load.getValue(1);
11209 if (ResultVT.bitsLT(VecEltVT))
11210 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11211 else
11212 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11213 }
11214 WorklistRemover DeadNodes(*this);
11215 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11216 SDValue To[] = { Load, Chain };
11217 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11218 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11219 // worklist explicitly as well.
11220 AddToWorklist(Load.getNode());
11221 AddUsersToWorklist(Load.getNode()); // Add users too
11222 // Make sure to revisit this node to clean it up; it will usually be dead.
11223 AddToWorklist(EVE);
11224 ++OpsNarrowed;
11225 return SDValue(EVE, 0);
11226}
11227
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011228SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000011229 // (vextract (scalar_to_vector val, 0) -> val
11230 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011231 EVT VT = InVec.getValueType();
11232 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000011233
Duncan Sands6be291a2011-05-09 08:03:33 +000011234 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11235 // Check if the result type doesn't match the inserted element type. A
11236 // SCALAR_TO_VECTOR may truncate the inserted element and the
11237 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11238 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000011239 if (InOp.getValueType() != NVT) {
11240 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000011241 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000011242 }
11243 return InOp;
11244 }
Evan Cheng1120279a2008-05-13 08:35:03 +000011245
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011246 SDValue EltNo = N->getOperand(1);
11247 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11248
11249 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11250 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000011251 // we may introduce new vector instructions which are not backed by TD
11252 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000011253 // without using extract_subvector. However, if we can find an underlying
11254 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011255 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000011256 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011257 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11258 int NumElem = VT.getVectorNumElements();
11259 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11260 // Find the new index to extract from.
11261 int OrigElt = SVOp->getMaskElt(Elt);
11262
11263 // Extracting an undef index is undef.
11264 if (OrigElt == -1)
11265 return DAG.getUNDEF(NVT);
11266
11267 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000011268 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011269 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000011270 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011271 } else {
Hal Finkel02807592014-03-31 11:43:19 +000011272 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011273 OrigElt -= NumElem;
11274 }
11275
Hal Finkel02807592014-03-31 11:43:19 +000011276 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11277 SDValue InOp = SVInVec.getOperand(OrigElt);
11278 if (InOp.getValueType() != NVT) {
11279 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11280 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11281 }
11282
11283 return InOp;
11284 }
11285
11286 // FIXME: We should handle recursing on other vector shuffles and
11287 // scalar_to_vector here as well.
11288
11289 if (!LegalOperations) {
11290 EVT IndexTy = TLI.getVectorIdxTy();
11291 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11292 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11293 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011294 }
11295
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011296 bool BCNumEltsChanged = false;
11297 EVT ExtVT = VT.getVectorElementType();
11298 EVT LVT = ExtVT;
11299
11300 // If the result of load has to be truncated, then it's not necessarily
11301 // profitable.
11302 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11303 return SDValue();
11304
11305 if (InVec.getOpcode() == ISD::BITCAST) {
11306 // Don't duplicate a load with other uses.
11307 if (!InVec.hasOneUse())
11308 return SDValue();
11309
11310 EVT BCVT = InVec.getOperand(0).getValueType();
11311 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11312 return SDValue();
11313 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11314 BCNumEltsChanged = true;
11315 InVec = InVec.getOperand(0);
11316 ExtVT = BCVT.getVectorElementType();
11317 }
11318
11319 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11320 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11321 ISD::isNormalLoad(InVec.getNode()) &&
11322 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11323 SDValue Index = N->getOperand(1);
11324 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11325 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11326 OrigLoad);
11327 }
11328
Evan Cheng1120279a2008-05-13 08:35:03 +000011329 // Perform only after legalization to ensure build_vector / vector_shuffle
11330 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011331 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011332
Mon P Wangca6d6de2009-01-17 00:07:25 +000011333 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11334 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11335 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000011336
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011337 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000011338 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011339
Craig Topperc0196b12014-04-14 00:51:57 +000011340 LoadSDNode *LN0 = nullptr;
11341 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000011342 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011343 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000011344 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000011345 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000011346 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000011347 // Don't duplicate a load with other uses.
11348 if (!InVec.hasOneUse())
11349 return SDValue();
11350
Evan Cheng1120279a2008-05-13 08:35:03 +000011351 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000011352 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011353 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11354 // =>
11355 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000011356
Eli Friedmane96286c2011-12-26 22:49:32 +000011357 // Don't duplicate a load with other uses.
11358 if (!InVec.hasOneUse())
11359 return SDValue();
11360
Mon P Wangb5eb7202008-12-11 00:26:16 +000011361 // If the bit convert changed the number of elements, it is unsafe
11362 // to examine the mask.
11363 if (BCNumEltsChanged)
11364 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000011365
11366 // Select the input vector, guarding against out of range extract vector.
11367 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000011368 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000011369 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11370
Eli Friedmane96286c2011-12-26 22:49:32 +000011371 if (InVec.getOpcode() == ISD::BITCAST) {
11372 // Don't duplicate a load with other uses.
11373 if (!InVec.hasOneUse())
11374 return SDValue();
11375
Evan Cheng1120279a2008-05-13 08:35:03 +000011376 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000011377 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000011378 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011379 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000011380 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011381 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000011382 }
11383 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011384
Eli Friedmane96286c2011-12-26 22:49:32 +000011385 // Make sure we found a non-volatile load and the extractelement is
11386 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000011387 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011388 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011389
Eric Christopherc6418b12010-11-03 20:44:42 +000011390 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11391 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000011392 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000011393
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011394 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000011395 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011396
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011397 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011398}
Evan Cheng0de312d2007-10-06 08:19:55 +000011399
Michael Liao6d106b72012-10-23 23:06:52 +000011400// Simplify (build_vec (ext )) to (bitcast (build_vec ))
11401SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11402 // We perform this optimization post type-legalization because
11403 // the type-legalizer often scalarizes integer-promoted vectors.
11404 // Performing this optimization before may create bit-casts which
11405 // will be type-legalized to complex code sequences.
11406 // We perform this optimization only before the operation legalizer because we
11407 // may introduce illegal operations.
11408 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11409 return SDValue();
11410
Dan Gohmana8665142007-06-25 16:23:39 +000011411 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011412 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000011413 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011414
Nadav Rotembf6568b2011-10-29 21:23:04 +000011415 // Check to see if this is a BUILD_VECTOR of a bunch of values
11416 // which come from any_extend or zero_extend nodes. If so, we can create
11417 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000011418 // optimizations. We do not handle sign-extend because we can't fill the sign
11419 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011420 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000011421 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000011422
Craig Topper02cb0fb2012-01-17 09:09:48 +000011423 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000011424 SDValue In = N->getOperand(i);
11425 // Ignore undef inputs.
11426 if (In.getOpcode() == ISD::UNDEF) continue;
11427
11428 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11429 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11430
Nadav Rotemf3103612011-10-31 20:08:25 +000011431 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011432 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000011433 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011434 break;
11435 }
11436
11437 // The input is a ZeroExt or AnyExt. Check the original type.
11438 EVT InTy = In.getOperand(0).getValueType();
11439
11440 // Check that all of the widened source types are the same.
11441 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000011442 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011443 SourceType = InTy;
11444 else if (InTy != SourceType) {
11445 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000011446 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011447 break;
11448 }
11449
11450 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000011451 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011452 }
11453
Nadav Rotemf3103612011-10-31 20:08:25 +000011454 // In order to have valid types, all of the inputs must be extended from the
11455 // same source type and all of the inputs must be any or zero extend.
11456 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000011457 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011458 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000011459 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11460 isPowerOf2_32(SourceType.getSizeInBits());
11461
Nadav Rotem6fd1d322012-03-15 08:49:06 +000011462 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11463 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000011464 if (!ValidTypes)
11465 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000011466
Michael Liao6d106b72012-10-23 23:06:52 +000011467 bool isLE = TLI.isLittleEndian();
11468 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11469 assert(ElemRatio > 1 && "Invalid element size ratio");
11470 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11471 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011472
Michael Liao6d106b72012-10-23 23:06:52 +000011473 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11474 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011475
Michael Liao6d106b72012-10-23 23:06:52 +000011476 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000011477 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000011478 SDValue Cast = N->getOperand(i);
11479 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11480 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11481 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11482 SDValue In;
11483 if (Cast.getOpcode() == ISD::UNDEF)
11484 In = DAG.getUNDEF(SourceType);
11485 else
11486 In = Cast->getOperand(0);
11487 unsigned Index = isLE ? (i * ElemRatio) :
11488 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000011489
Michael Liao6d106b72012-10-23 23:06:52 +000011490 assert(Index < Ops.size() && "Invalid index");
11491 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011492 }
Chris Lattner5336a592006-03-19 01:27:56 +000011493
Michael Liao6d106b72012-10-23 23:06:52 +000011494 // The type of the new BUILD_VECTOR node.
11495 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11496 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11497 "Invalid vector size");
11498 // Check if the new vector type is legal.
11499 if (!isTypeLegal(VecVT)) return SDValue();
11500
11501 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000011502 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000011503
11504 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011505 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000011506 // Bitcast to the desired type.
11507 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11508}
11509
Michael Liao59229792012-10-24 04:14:18 +000011510SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11511 EVT VT = N->getValueType(0);
11512
11513 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011514 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000011515
11516 EVT SrcVT = MVT::Other;
11517 unsigned Opcode = ISD::DELETED_NODE;
11518 unsigned NumDefs = 0;
11519
11520 for (unsigned i = 0; i != NumInScalars; ++i) {
11521 SDValue In = N->getOperand(i);
11522 unsigned Opc = In.getOpcode();
11523
11524 if (Opc == ISD::UNDEF)
11525 continue;
11526
11527 // If all scalar values are floats and converted from integers.
11528 if (Opcode == ISD::DELETED_NODE &&
11529 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11530 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000011531 }
Tom Stellard567f8862013-01-02 22:13:01 +000011532
Michael Liao59229792012-10-24 04:14:18 +000011533 if (Opc != Opcode)
11534 return SDValue();
11535
11536 EVT InVT = In.getOperand(0).getValueType();
11537
11538 // If all scalar values are typed differently, bail out. It's chosen to
11539 // simplify BUILD_VECTOR of integer types.
11540 if (SrcVT == MVT::Other)
11541 SrcVT = InVT;
11542 if (SrcVT != InVT)
11543 return SDValue();
11544 NumDefs++;
11545 }
11546
11547 // If the vector has just one element defined, it's not worth to fold it into
11548 // a vectorized one.
11549 if (NumDefs < 2)
11550 return SDValue();
11551
11552 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11553 && "Should only handle conversion from integer to float.");
11554 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11555
11556 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000011557
11558 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11559 return SDValue();
11560
Hal Finkele2dd84e2015-02-22 16:10:22 +000011561 // Just because the floating-point vector type is legal does not necessarily
11562 // mean that the corresponding integer vector type is.
11563 if (!isTypeLegal(NVT))
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011564 return SDValue();
Hal Finkele2dd84e2015-02-22 16:10:22 +000011565
Michael Liao59229792012-10-24 04:14:18 +000011566 SmallVector<SDValue, 8> Opnds;
11567 for (unsigned i = 0; i != NumInScalars; ++i) {
11568 SDValue In = N->getOperand(i);
11569
11570 if (In.getOpcode() == ISD::UNDEF)
11571 Opnds.push_back(DAG.getUNDEF(SrcVT));
11572 else
11573 Opnds.push_back(In.getOperand(0));
11574 }
Craig Topper48d114b2014-04-26 18:35:24 +000011575 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011576 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000011577
11578 return DAG.getNode(Opcode, dl, VT, BV);
11579}
11580
Michael Liao6d106b72012-10-23 23:06:52 +000011581SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11582 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011583 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000011584 EVT VT = N->getValueType(0);
11585
11586 // A vector built entirely of undefs is undef.
11587 if (ISD::allOperandsUndef(N))
11588 return DAG.getUNDEF(VT);
11589
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011590 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
Michael Liao6d106b72012-10-23 23:06:52 +000011591 return V;
11592
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011593 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
Michael Liao59229792012-10-24 04:14:18 +000011594 return V;
11595
Dan Gohmana8665142007-06-25 16:23:39 +000011596 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11597 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11598 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011599
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000011600 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11601 if (!isTypeLegal(VT))
11602 return SDValue();
11603
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011604 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000011605 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011606 return SDValue();
11607
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011608 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011609 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000011610 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011611 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000011612 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011613 if (Op.getOpcode() == ISD::UNDEF) continue;
11614
11615 // See if we can combine this build_vector into a blend with a zero vector.
11616 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11617 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11618 (Op.getOpcode() == ISD::ConstantFP &&
11619 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11620 UsesZeroVector = true;
11621 continue;
11622 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011623
Dan Gohmana8665142007-06-25 16:23:39 +000011624 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000011625 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011626 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11627 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000011628 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011629 break;
11630 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011631
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011632 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011633 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011634 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11635 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011636
Craig Topperc0196b12014-04-14 00:51:57 +000011637 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011638 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011639 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011640 VecIn2 = ExtractedFromVec;
11641 } else {
11642 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000011643 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011644 break;
11645 }
11646 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011647
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000011648 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011649 if (VecIn1.getNode()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011650 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011651 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000011652 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011653 unsigned Opcode = N->getOperand(i).getOpcode();
11654 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011655 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000011656 continue;
11657 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011658
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011659 // Operands can also be zero.
11660 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11661 assert(UsesZeroVector &&
11662 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11663 "Unexpected node found!");
11664 Mask.push_back(NumInScalars+i);
11665 continue;
11666 }
11667
Rafael Espindolab93db662009-04-24 12:40:33 +000011668 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011669 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000011670 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011671 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011672 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000011673 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011674 continue;
11675 }
11676
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011677 // Otherwise, use InIdx + InputVecSize
11678 Mask.push_back(InNumElements + ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011679 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011680
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011681 // Avoid introducing illegal shuffles with zero.
11682 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11683 return SDValue();
11684
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011685 // We can't generate a shuffle node with mismatched input and output types.
11686 // Attempt to transform a single input vector to the correct type.
11687 if ((VT != VecIn1.getValueType())) {
James Molloy1e5c6112012-09-10 14:01:21 +000011688 // If the input vector type has a different base type to the output
11689 // vector type, bail out.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011690 EVT VTElemType = VT.getVectorElementType();
11691 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11692 (VecIn2.getNode() &&
11693 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
James Molloy1e5c6112012-09-10 14:01:21 +000011694 return SDValue();
11695
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011696 // If the input vector is too small, widen it.
11697 // We only support widening of vectors which are half the size of the
11698 // output registers. For example XMM->YMM widening on X86 with AVX.
11699 EVT VecInT = VecIn1.getValueType();
11700 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011701 // If we only have one small input, widen it by adding undef values.
11702 if (!VecIn2.getNode())
11703 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11704 DAG.getUNDEF(VecIn1.getValueType()));
11705 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11706 // If we have two small inputs of the same type, try to concat them.
11707 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11708 VecIn2 = SDValue(nullptr, 0);
11709 } else
11710 return SDValue();
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011711 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11712 // If the input vector is too large, try to split it.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011713 // We don't support having two input vectors that are too large.
Michael Kupersteinfb956972015-03-04 07:27:39 +000011714 // If the zero vector was used, we can not split the vector,
11715 // since we'd need 3 inputs.
11716 if (UsesZeroVector || VecIn2.getNode())
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011717 return SDValue();
11718
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011719 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11720 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011721
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011722 // Try to replace VecIn1 with two extract_subvectors
11723 // No need to update the masks, they should still be correct.
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011724 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011725 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11726 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11727 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011728 } else
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011729 return SDValue();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011730 }
11731
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011732 if (UsesZeroVector)
11733 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11734 DAG.getConstantFP(0.0, VT);
11735 else
11736 // If VecIn2 is unused then change it to undef.
11737 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011738
Nadav Rotem841c9a82012-09-20 08:53:31 +000011739 // Check that we were able to transform all incoming values to the same
11740 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000011741 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11742 VecIn1.getValueType() != VT)
11743 return SDValue();
11744
Dan Gohmana8665142007-06-25 16:23:39 +000011745 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011746 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000011747 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011748 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000011749 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000011750 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011751
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011752 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011753}
11754
Ahmed Bougachac984b902015-04-16 02:39:14 +000011755static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11756 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11757 EVT OpVT = N->getOperand(0).getValueType();
11758
11759 // If the operands are legal vectors, leave them alone.
11760 if (TLI.isTypeLegal(OpVT))
11761 return SDValue();
11762
11763 SDLoc DL(N);
11764 EVT VT = N->getValueType(0);
11765 SmallVector<SDValue, 8> Ops;
11766
11767 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11768 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11769
11770 // Keep track of what we encounter.
11771 bool AnyInteger = false;
11772 bool AnyFP = false;
11773 for (const SDValue &Op : N->ops()) {
11774 if (ISD::BITCAST == Op.getOpcode() &&
11775 !Op.getOperand(0).getValueType().isVector())
11776 Ops.push_back(Op.getOperand(0));
11777 else if (ISD::UNDEF == Op.getOpcode())
11778 Ops.push_back(ScalarUndef);
11779 else
11780 return SDValue();
11781
11782 // Note whether we encounter an integer or floating point scalar.
11783 // If it's neither, bail out, it could be something weird like x86mmx.
11784 EVT LastOpVT = Ops.back().getValueType();
11785 if (LastOpVT.isFloatingPoint())
11786 AnyFP = true;
11787 else if (LastOpVT.isInteger())
11788 AnyInteger = true;
11789 else
11790 return SDValue();
11791 }
11792
11793 // If any of the operands is a floating point scalar bitcast to a vector,
11794 // use floating point types throughout, and bitcast everything.
11795 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11796 if (AnyFP) {
11797 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11798 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11799 if (AnyInteger) {
11800 for (SDValue &Op : Ops) {
11801 if (Op.getValueType() == SVT)
11802 continue;
11803 if (Op.getOpcode() == ISD::UNDEF)
11804 Op = ScalarUndef;
11805 else
11806 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11807 }
11808 }
11809 }
11810
11811 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11812 VT.getSizeInBits() / SVT.getSizeInBits());
11813 return DAG.getNode(ISD::BITCAST, DL, VT,
11814 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11815}
11816
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011817SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000011818 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11819 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11820 // inputs come from at most two distinct vectors, turn this into a shuffle
11821 // node.
11822
11823 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000011824 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000011825 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011826
Nadav Rotem01892102012-07-14 21:30:27 +000011827 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011828 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011829 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011830 return DAG.getUNDEF(VT);
11831
Ahmed Bougachadf437372015-04-09 20:04:47 +000011832 // Optimize concat_vectors where all but the first of the vectors are undef.
11833 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11834 return Op.getOpcode() == ISD::UNDEF;
11835 })) {
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011836 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000011837 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011838
11839 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11840 if (In->getOpcode() == ISD::BITCAST &&
11841 !In->getOperand(0)->getValueType(0).isVector()) {
11842 SDValue Scalar = In->getOperand(0);
Ahmed Bougachadf437372015-04-09 20:04:47 +000011843
11844 // If the bitcast type isn't legal, it might be a trunc of a legal type;
11845 // look through the trunc so we can still do the transform:
11846 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11847 if (Scalar->getOpcode() == ISD::TRUNCATE &&
11848 !TLI.isTypeLegal(Scalar.getValueType()) &&
11849 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11850 Scalar = Scalar->getOperand(0);
11851
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011852 EVT SclTy = Scalar->getValueType(0);
11853
11854 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11855 return SDValue();
11856
11857 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11858 VT.getSizeInBits() / SclTy.getSizeInBits());
11859 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11860 return SDValue();
11861
11862 SDLoc dl = SDLoc(N);
11863 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11864 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11865 }
11866 }
Nadav Rotem01892102012-07-14 21:30:27 +000011867
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011868 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11869 // We have already tested above for an UNDEF only concatenation.
Robert Lougher7d9084f2014-02-11 15:42:46 +000011870 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11871 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011872 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11873 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11874 };
11875 bool AllBuildVectorsOrUndefs =
11876 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11877 if (AllBuildVectorsOrUndefs) {
Robert Lougher7d9084f2014-02-11 15:42:46 +000011878 SmallVector<SDValue, 8> Opnds;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011879 EVT SVT = VT.getScalarType();
Robert Lougher7d9084f2014-02-11 15:42:46 +000011880
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011881 EVT MinVT = SVT;
11882 if (!SVT.isFloatingPoint()) {
Hao Liu71224b02014-07-10 03:41:50 +000011883 // If BUILD_VECTOR are from built from integer, they may have different
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011884 // operand types. Get the smallest type and truncate all operands to it.
11885 bool FoundMinVT = false;
11886 for (const SDValue &Op : N->ops())
11887 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11888 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11889 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11890 FoundMinVT = true;
11891 }
11892 assert(FoundMinVT && "Concat vector type mismatch");
Hao Liu71224b02014-07-10 03:41:50 +000011893 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000011894
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011895 for (const SDValue &Op : N->ops()) {
11896 EVT OpVT = Op.getValueType();
11897 unsigned NumElts = OpVT.getVectorNumElements();
11898
11899 if (ISD::UNDEF == Op.getOpcode())
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000011900 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011901
11902 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11903 if (SVT.isFloatingPoint()) {
11904 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000011905 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011906 } else {
11907 for (unsigned i = 0; i != NumElts; ++i)
11908 Opnds.push_back(
11909 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11910 }
11911 }
11912 }
11913
11914 assert(VT.getVectorNumElements() == Opnds.size() &&
11915 "Concat vector type mismatch");
Craig Topper48d114b2014-04-26 18:35:24 +000011916 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000011917 }
11918
Ahmed Bougachac984b902015-04-16 02:39:14 +000011919 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
11920 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
11921 return V;
11922
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011923 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11924 // nodes often generate nop CONCAT_VECTOR nodes.
11925 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11926 // place the incoming vectors at the exact same location.
11927 SDValue SingleSource = SDValue();
11928 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11929
11930 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11931 SDValue Op = N->getOperand(i);
11932
11933 if (Op.getOpcode() == ISD::UNDEF)
11934 continue;
11935
11936 // Check if this is the identity extract:
11937 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11938 return SDValue();
11939
11940 // Find the single incoming vector for the extract_subvector.
11941 if (SingleSource.getNode()) {
11942 if (Op.getOperand(0) != SingleSource)
11943 return SDValue();
11944 } else {
11945 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000011946
11947 // Check the source type is the same as the type of the result.
11948 // If not, this concat may extend the vector, so we can not
11949 // optimize it away.
11950 if (SingleSource.getValueType() != N->getValueType(0))
11951 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011952 }
11953
11954 unsigned IdentityIndex = i * PartNumElem;
11955 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11956 // The extract index must be constant.
11957 if (!CS)
11958 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000011959
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011960 // Check that we are reading from the identity index.
11961 if (CS->getZExtValue() != IdentityIndex)
11962 return SDValue();
11963 }
11964
11965 if (SingleSource.getNode())
11966 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000011967
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011968 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000011969}
11970
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011971SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11972 EVT NVT = N->getValueType(0);
11973 SDValue V = N->getOperand(0);
11974
Michael Liao7a442c802012-10-17 20:48:33 +000011975 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11976 // Combine:
11977 // (extract_subvec (concat V1, V2, ...), i)
11978 // Into:
11979 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000011980 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11981 // type.
Michael Liao2c235802012-10-19 03:17:00 +000011982 if (V->getOperand(0).getValueType() != NVT)
11983 return SDValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +000011984 unsigned Idx = N->getConstantOperandVal(1);
Michael Liao7a442c802012-10-17 20:48:33 +000011985 unsigned NumElems = NVT.getVectorNumElements();
11986 assert((Idx % NumElems) == 0 &&
11987 "IDX in concat is not a multiple of the result vector length.");
11988 return V->getOperand(Idx / NumElems);
11989 }
11990
Michael Liaobb05a1d2013-03-25 23:47:35 +000011991 // Skip bitcasting
11992 if (V->getOpcode() == ISD::BITCAST)
11993 V = V.getOperand(0);
11994
11995 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011996 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000011997 // Handle only simple case where vector being inserted and vector
11998 // being extracted are of same type, and are half size of larger vectors.
11999 EVT BigVT = V->getOperand(0).getValueType();
12000 EVT SmallVT = V->getOperand(1).getValueType();
12001 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12002 return SDValue();
12003
12004 // Only handle cases where both indexes are constants with the same type.
12005 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12006 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12007
12008 if (InsIdx && ExtIdx &&
12009 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12010 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12011 // Combine:
12012 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12013 // Into:
12014 // indices are equal or bit offsets are equal => V1
12015 // otherwise => (extract_subvec V1, ExtIdx)
12016 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12017 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12018 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12019 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12020 DAG.getNode(ISD::BITCAST, dl,
12021 N->getOperand(0).getValueType(),
12022 V->getOperand(0)), N->getOperand(1));
12023 }
12024 }
12025
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000012026 return SDValue();
12027}
12028
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000012029static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12030 SDValue V, SelectionDAG &DAG) {
12031 SDLoc DL(V);
12032 EVT VT = V.getValueType();
12033
12034 switch (V.getOpcode()) {
12035 default:
12036 return V;
12037
12038 case ISD::CONCAT_VECTORS: {
12039 EVT OpVT = V->getOperand(0).getValueType();
12040 int OpSize = OpVT.getVectorNumElements();
12041 SmallBitVector OpUsedElements(OpSize, false);
12042 bool FoundSimplification = false;
12043 SmallVector<SDValue, 4> NewOps;
12044 NewOps.reserve(V->getNumOperands());
12045 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12046 SDValue Op = V->getOperand(i);
12047 bool OpUsed = false;
12048 for (int j = 0; j < OpSize; ++j)
12049 if (UsedElements[i * OpSize + j]) {
12050 OpUsedElements[j] = true;
12051 OpUsed = true;
12052 }
12053 NewOps.push_back(
12054 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12055 : DAG.getUNDEF(OpVT));
12056 FoundSimplification |= Op == NewOps.back();
12057 OpUsedElements.reset();
12058 }
12059 if (FoundSimplification)
12060 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12061 return V;
12062 }
12063
12064 case ISD::INSERT_SUBVECTOR: {
12065 SDValue BaseV = V->getOperand(0);
12066 SDValue SubV = V->getOperand(1);
12067 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12068 if (!IdxN)
12069 return V;
12070
12071 int SubSize = SubV.getValueType().getVectorNumElements();
12072 int Idx = IdxN->getZExtValue();
12073 bool SubVectorUsed = false;
12074 SmallBitVector SubUsedElements(SubSize, false);
12075 for (int i = 0; i < SubSize; ++i)
12076 if (UsedElements[i + Idx]) {
12077 SubVectorUsed = true;
12078 SubUsedElements[i] = true;
12079 UsedElements[i + Idx] = false;
12080 }
12081
12082 // Now recurse on both the base and sub vectors.
12083 SDValue SimplifiedSubV =
12084 SubVectorUsed
12085 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12086 : DAG.getUNDEF(SubV.getValueType());
12087 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12088 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12089 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12090 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12091 return V;
12092 }
12093 }
12094}
12095
12096static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12097 SDValue N1, SelectionDAG &DAG) {
12098 EVT VT = SVN->getValueType(0);
12099 int NumElts = VT.getVectorNumElements();
12100 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12101 for (int M : SVN->getMask())
12102 if (M >= 0 && M < NumElts)
12103 N0UsedElements[M] = true;
12104 else if (M >= NumElts)
12105 N1UsedElements[M - NumElts] = true;
12106
12107 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12108 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12109 if (S0 == N0 && S1 == N1)
12110 return SDValue();
12111
12112 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12113}
12114
Mehdi Amini37f316a2015-01-17 01:35:56 +000012115// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12116// or turn a shuffle of a single concat into simpler shuffle then concat.
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012117static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12118 EVT VT = N->getValueType(0);
12119 unsigned NumElts = VT.getVectorNumElements();
12120
12121 SDValue N0 = N->getOperand(0);
12122 SDValue N1 = N->getOperand(1);
12123 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12124
12125 SmallVector<SDValue, 4> Ops;
12126 EVT ConcatVT = N0.getOperand(0).getValueType();
12127 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12128 unsigned NumConcats = NumElts / NumElemsPerConcat;
12129
Mehdi Amini37f316a2015-01-17 01:35:56 +000012130 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12131 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12132 // half vector elements.
12133 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12134 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12135 SVN->getMask().end(), [](int i) { return i == -1; })) {
12136 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12137 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12138 N1 = DAG.getUNDEF(ConcatVT);
12139 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12140 }
12141
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012142 // Look at every vector that's inserted. We're looking for exact
12143 // subvector-sized copies from a concatenated vector
12144 for (unsigned I = 0; I != NumConcats; ++I) {
12145 // Make sure we're dealing with a copy.
12146 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000012147 bool AllUndef = true, NoUndef = true;
12148 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12149 if (SVN->getMaskElt(J) >= 0)
12150 AllUndef = false;
12151 else
12152 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012153 }
12154
Hao Liubc601962013-05-13 02:07:05 +000012155 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000012156 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12157 return SDValue();
12158
12159 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12160 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12161 return SDValue();
12162
12163 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12164 if (FirstElt < N0.getNumOperands())
12165 Ops.push_back(N0.getOperand(FirstElt));
12166 else
12167 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12168
12169 } else if (AllUndef) {
12170 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12171 } else { // Mixed with general masks and undefs, can't do optimization.
12172 return SDValue();
12173 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012174 }
12175
Craig Topper48d114b2014-04-26 18:35:24 +000012176 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012177}
12178
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012179SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012180 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012181 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012182
Mon P Wang25f01062008-11-10 04:46:22 +000012183 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000012184 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000012185
Craig Topper5894fe42012-04-09 05:16:56 +000012186 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000012187
Craig Topper279c77b2012-01-04 08:07:43 +000012188 // Canonicalize shuffle undef, undef -> undef
12189 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12190 return DAG.getUNDEF(VT);
12191
12192 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12193
12194 // Canonicalize shuffle v, v -> v, undef
12195 if (N0 == N1) {
12196 SmallVector<int, 8> NewMask;
12197 for (unsigned i = 0; i != NumElts; ++i) {
12198 int Idx = SVN->getMaskElt(i);
12199 if (Idx >= (int)NumElts) Idx -= NumElts;
12200 NewMask.push_back(Idx);
12201 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012202 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000012203 &NewMask[0]);
12204 }
12205
12206 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12207 if (N0.getOpcode() == ISD::UNDEF) {
12208 SmallVector<int, 8> NewMask;
12209 for (unsigned i = 0; i != NumElts; ++i) {
12210 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000012211 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000012212 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000012213 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000012214 else
12215 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000012216 }
12217 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000012218 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012219 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000012220 &NewMask[0]);
12221 }
12222
12223 // Remove references to rhs if it is undef
12224 if (N1.getOpcode() == ISD::UNDEF) {
12225 bool Changed = false;
12226 SmallVector<int, 8> NewMask;
12227 for (unsigned i = 0; i != NumElts; ++i) {
12228 int Idx = SVN->getMaskElt(i);
12229 if (Idx >= (int)NumElts) {
12230 Idx = -1;
12231 Changed = true;
12232 }
12233 NewMask.push_back(Idx);
12234 }
12235 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000012236 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000012237 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000012238
Bob Wilsonf63da122010-10-28 17:06:14 +000012239 // If it is a splat, check if the argument vector is another splat or a
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012240 // build_vector.
Bob Wilsonf63da122010-10-28 17:06:14 +000012241 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000012242 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000012243
Dan Gohmana8665142007-06-25 16:23:39 +000012244 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000012245 // not the number of vector elements, look through it. Be careful not to
12246 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000012247 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012248 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000012249 if (ConvInput.getValueType().isVector() &&
12250 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000012251 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000012252 }
12253
Dan Gohmana8665142007-06-25 16:23:39 +000012254 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000012255 assert(V->getNumOperands() == NumElts &&
12256 "BUILD_VECTOR has wrong number of operands");
12257 SDValue Base;
12258 bool AllSame = true;
12259 for (unsigned i = 0; i != NumElts; ++i) {
12260 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12261 Base = V->getOperand(i);
12262 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000012263 }
Evan Cheng7c970b92006-07-21 08:25:53 +000012264 }
Bob Wilsonf63da122010-10-28 17:06:14 +000012265 // Splat of <u, u, u, u>, return <u, u, u, u>
12266 if (!Base.getNode())
12267 return N0;
12268 for (unsigned i = 0; i != NumElts; ++i) {
12269 if (V->getOperand(i) != Base) {
12270 AllSame = false;
12271 break;
12272 }
12273 }
12274 // Splat of <x, x, x, x>, return <x, x, x, x>
12275 if (AllSame)
12276 return N0;
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012277
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012278 // Canonicalize any other splat as a build_vector.
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012279 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012280 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12281 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12282 V->getValueType(0), Ops);
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012283
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012284 // We may have jumped through bitcasts, so the type of the
12285 // BUILD_VECTOR may not match the type of the shuffle.
12286 if (V->getValueType(0) != VT)
Sanjay Pateld95dd9e2015-03-26 16:55:17 +000012287 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012288 return NewBV;
Evan Cheng7c970b92006-07-21 08:25:53 +000012289 }
12290 }
Nadav Rotemb0783502012-04-01 19:31:22 +000012291
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000012292 // There are various patterns used to build up a vector from smaller vectors,
12293 // subvectors, or elements. Scan chains of these and replace unused insertions
12294 // or components with undef.
12295 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12296 return S;
12297
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012298 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12299 Level < AfterLegalizeVectorOps &&
12300 (N1.getOpcode() == ISD::UNDEF ||
12301 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12302 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12303 SDValue V = partitionShuffleOfConcats(N, DAG);
12304
12305 if (V.getNode())
12306 return V;
12307 }
12308
Simon Pilgrimed2ba33ba2015-04-03 10:02:21 +000012309 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12310 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12311 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12312 SmallVector<SDValue, 8> Ops;
12313 for (int M : SVN->getMask()) {
12314 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12315 if (M >= 0) {
12316 int Idx = M % NumElts;
12317 SDValue &S = (M < (int)NumElts ? N0 : N1);
12318 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12319 Op = S.getOperand(Idx);
12320 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12321 if (Idx == 0)
12322 Op = S.getOperand(0);
12323 } else {
12324 // Operand can't be combined - bail out.
12325 break;
12326 }
12327 }
12328 Ops.push_back(Op);
12329 }
12330 if (Ops.size() == VT.getVectorNumElements()) {
12331 // BUILD_VECTOR requires all inputs to be of the same type, find the
12332 // maximum type and extend them all.
12333 EVT SVT = VT.getScalarType();
12334 if (SVT.isInteger())
12335 for (SDValue &Op : Ops)
12336 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12337 if (SVT != VT.getScalarType())
12338 for (SDValue &Op : Ops)
12339 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12340 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12341 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12342 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12343 }
12344 }
12345
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012346 // If this shuffle only has a single input that is a bitcasted shuffle,
12347 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12348 // back to their original types.
12349 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12350 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12351 TLI.isTypeLegal(VT)) {
12352
12353 // Peek through the bitcast only if there is one user.
12354 SDValue BC0 = N0;
12355 while (BC0.getOpcode() == ISD::BITCAST) {
12356 if (!BC0.hasOneUse())
12357 break;
12358 BC0 = BC0.getOperand(0);
12359 }
12360
12361 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12362 if (Scale == 1)
12363 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12364
12365 SmallVector<int, 8> NewMask;
12366 for (int M : Mask)
12367 for (int s = 0; s != Scale; ++s)
12368 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12369 return NewMask;
12370 };
12371
12372 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12373 EVT SVT = VT.getScalarType();
12374 EVT InnerVT = BC0->getValueType(0);
12375 EVT InnerSVT = InnerVT.getScalarType();
12376
12377 // Determine which shuffle works with the smaller scalar type.
12378 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12379 EVT ScaleSVT = ScaleVT.getScalarType();
12380
12381 if (TLI.isTypeLegal(ScaleVT) &&
12382 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12383 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12384
12385 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12386 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12387
12388 // Scale the shuffle masks to the smaller scalar type.
12389 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12390 SmallVector<int, 8> InnerMask =
12391 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12392 SmallVector<int, 8> OuterMask =
12393 ScaleShuffleMask(SVN->getMask(), OuterScale);
12394
12395 // Merge the shuffle masks.
12396 SmallVector<int, 8> NewMask;
12397 for (int M : OuterMask)
12398 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12399
12400 // Test for shuffle mask legality over both commutations.
12401 SDValue SV0 = BC0->getOperand(0);
12402 SDValue SV1 = BC0->getOperand(1);
12403 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12404 if (!LegalMask) {
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012405 std::swap(SV0, SV1);
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012406 ShuffleVectorSDNode::commuteMask(NewMask);
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012407 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12408 }
12409
12410 if (LegalMask) {
12411 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12412 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12413 return DAG.getNode(
12414 ISD::BITCAST, SDLoc(N), VT,
12415 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12416 }
12417 }
12418 }
12419 }
12420
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012421 // Canonicalize shuffles according to rules:
12422 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12423 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12424 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012425 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012426 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12427 TLI.isTypeLegal(VT)) {
12428 // The incoming shuffle must be of the same type as the result of the
12429 // current shuffle.
12430 assert(N1->getOperand(0).getValueType() == VT &&
12431 "Shuffle types don't match");
12432
12433 SDValue SV0 = N1->getOperand(0);
12434 SDValue SV1 = N1->getOperand(1);
12435 bool HasSameOp0 = N0 == SV0;
12436 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12437 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12438 // Commute the operands of this shuffle so that next rule
12439 // will trigger.
12440 return DAG.getCommutedVectorShuffle(*SVN);
12441 }
12442
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012443 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012444 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12445 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12446 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012447 // Don't try to fold shuffles with illegal type.
Chandler Carruth499d7332015-02-15 07:01:10 +000012448 // Only fold if this shuffle is the only user of the other shuffle.
12449 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12450 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012451 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12452
12453 // The incoming shuffle must be of the same type as the result of the
12454 // current shuffle.
12455 assert(OtherSV->getOperand(0).getValueType() == VT &&
12456 "Shuffle types don't match");
12457
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012458 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012459 SmallVector<int, 4> Mask;
12460 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12461 // operand, and SV1 as the second operand.
12462 for (unsigned i = 0; i != NumElts; ++i) {
12463 int Idx = SVN->getMaskElt(i);
12464 if (Idx < 0) {
12465 // Propagate Undef.
12466 Mask.push_back(Idx);
12467 continue;
12468 }
12469
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012470 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012471 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012472 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12473 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012474 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012475 if (Idx < 0) {
12476 // Propagate Undef.
12477 Mask.push_back(Idx);
12478 continue;
12479 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012480
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012481 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12482 : OtherSV->getOperand(1);
12483 } else {
12484 // This shuffle index references an element within N1.
12485 CurrentVec = N1;
12486 }
12487
12488 // Simple case where 'CurrentVec' is UNDEF.
12489 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12490 Mask.push_back(-1);
12491 continue;
12492 }
12493
12494 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12495 // will be the first or second operand of the combined shuffle.
12496 Idx = Idx % NumElts;
12497 if (!SV0.getNode() || SV0 == CurrentVec) {
12498 // Ok. CurrentVec is the left hand side.
12499 // Update the mask accordingly.
12500 SV0 = CurrentVec;
12501 Mask.push_back(Idx);
12502 continue;
12503 }
12504
12505 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12506 if (SV1.getNode() && SV1 != CurrentVec)
12507 return SDValue();
12508
12509 // Ok. CurrentVec is the right hand side.
12510 // Update the mask accordingly.
12511 SV1 = CurrentVec;
12512 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012513 }
12514
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000012515 // Check if all indices in Mask are Undef. In case, propagate Undef.
12516 bool isUndefMask = true;
12517 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12518 isUndefMask &= Mask[i] < 0;
12519
12520 if (isUndefMask)
12521 return DAG.getUNDEF(VT);
12522
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012523 if (!SV0.getNode())
12524 SV0 = DAG.getUNDEF(VT);
12525 if (!SV1.getNode())
12526 SV1 = DAG.getUNDEF(VT);
12527
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012528 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012529 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012530 ShuffleVectorSDNode::commuteMask(Mask);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012531
12532 if (!TLI.isShuffleMaskLegal(Mask, VT))
12533 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012534
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012535 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12536 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12537 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12538 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012539 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000012540
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012541 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12542 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12543 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12544 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012545 }
12546
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012547 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012548}
12549
Simon Pilgrimbede80a2015-03-07 05:52:42 +000012550SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12551 SDValue InVal = N->getOperand(0);
12552 EVT VT = N->getValueType(0);
12553
12554 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12555 // with a VECTOR_SHUFFLE.
12556 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12557 SDValue InVec = InVal->getOperand(0);
12558 SDValue EltNo = InVal->getOperand(1);
12559
12560 // FIXME: We could support implicit truncation if the shuffle can be
12561 // scaled to a smaller vector scalar type.
12562 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12563 if (C0 && VT == InVec.getValueType() &&
12564 VT.getScalarType() == InVal.getValueType()) {
12565 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12566 int Elt = C0->getZExtValue();
12567 NewMask[0] = Elt;
12568
12569 if (TLI.isShuffleMaskLegal(NewMask, VT))
12570 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12571 NewMask);
12572 }
12573 }
12574
12575 return SDValue();
12576}
12577
Manman Ren413a6cb2014-01-31 01:10:35 +000012578SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12579 SDValue N0 = N->getOperand(0);
12580 SDValue N2 = N->getOperand(2);
12581
12582 // If the input vector is a concatenation, and the insert replaces
12583 // one of the halves, we can optimize into a single concat_vectors.
12584 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12585 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12586 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12587 EVT VT = N->getValueType(0);
12588
12589 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12590 // (concat_vectors Z, Y)
12591 if (InsIdx == 0)
12592 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12593 N->getOperand(1), N0.getOperand(1));
12594
12595 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12596 // (concat_vectors X, Z)
12597 if (InsIdx == VT.getVectorNumElements()/2)
12598 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12599 N0.getOperand(0), N->getOperand(1));
12600 }
12601
12602 return SDValue();
12603}
12604
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +000012605SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12606 SDValue N0 = N->getOperand(0);
12607
12608 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12609 if (N0->getOpcode() == ISD::FP16_TO_FP)
12610 return N0->getOperand(0);
12611
12612 return SDValue();
12613}
12614
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012615/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12616/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000012617/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000012618/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012619SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012620 EVT VT = N->getValueType(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012621 SDValue LHS = N->getOperand(0);
12622 SDValue RHS = N->getOperand(1);
Simon Pilgrim257849f2015-03-17 22:19:08 +000012623 SDLoc dl(N);
Craig Toppere5893f62012-04-09 05:59:53 +000012624
Simon Pilgrim257849f2015-03-17 22:19:08 +000012625 // Make sure we're not running after operation legalization where it
12626 // may have custom lowered the vector shuffles.
12627 if (LegalOperations)
12628 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012629
Simon Pilgrim257849f2015-03-17 22:19:08 +000012630 if (N->getOpcode() != ISD::AND)
12631 return SDValue();
12632
12633 if (RHS.getOpcode() == ISD::BITCAST)
12634 RHS = RHS.getOperand(0);
12635
12636 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12637 SmallVector<int, 8> Indices;
12638 unsigned NumElts = RHS.getNumOperands();
12639
12640 for (unsigned i = 0; i != NumElts; ++i) {
12641 SDValue Elt = RHS.getOperand(i);
12642 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012643 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012644
Simon Pilgrim257849f2015-03-17 22:19:08 +000012645 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12646 Indices.push_back(i);
12647 else if (cast<ConstantSDNode>(Elt)->isNullValue())
12648 Indices.push_back(NumElts+i);
12649 else
12650 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012651 }
Simon Pilgrim257849f2015-03-17 22:19:08 +000012652
12653 // Let's see if the target supports this vector_shuffle.
12654 EVT RVT = RHS.getValueType();
12655 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12656 return SDValue();
12657
12658 // Return the new VECTOR_SHUFFLE node.
12659 EVT EltVT = RVT.getVectorElementType();
12660 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12661 DAG.getConstant(0, EltVT));
12662 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
12663 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12664 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12665 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000012666 }
Bill Wendling31b50992009-01-30 23:59:18 +000012667
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012668 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012669}
12670
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012671/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012672SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000012673 assert(N->getValueType(0).isVector() &&
12674 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000012675
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012676 SDValue LHS = N->getOperand(0);
12677 SDValue RHS = N->getOperand(1);
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000012678
12679 if (SDValue Shuffle = XformToShuffleWithZero(N))
12680 return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000012681
Dan Gohmana8665142007-06-25 16:23:39 +000012682 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000012683 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012684 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000012685 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000012686 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000012687 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12688 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000012689 return SDValue();
12690
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012691 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000012692 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012693 SDValue LHSOp = LHS.getOperand(i);
12694 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000012695
Evan Cheng64d28462006-05-31 06:08:35 +000012696 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000012697 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12698 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000012699 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012700 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000012701 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012702 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000012703 break;
12704 }
Bill Wendling31b50992009-01-30 23:59:18 +000012705
Bob Wilson54081442010-12-17 23:06:49 +000012706 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000012707 EVT RVT = RHSOp.getValueType();
12708 if (RVT != VT) {
12709 // Integer BUILD_VECTOR operands may have types larger than the element
12710 // size (e.g., when the element type is not legal). Prior to type
12711 // legalization, the types may not match between the two BUILD_VECTORS.
12712 // Truncate one of the operands to make them match.
12713 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012714 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012715 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012716 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012717 VT = RVT;
12718 }
12719 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012720 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000012721 LHSOp, RHSOp);
12722 if (FoldOp.getOpcode() != ISD::UNDEF &&
12723 FoldOp.getOpcode() != ISD::Constant &&
12724 FoldOp.getOpcode() != ISD::ConstantFP)
12725 break;
12726 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012727 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000012728 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012729
Bob Wilson54081442010-12-17 23:06:49 +000012730 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000012731 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000012732 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012733
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012734 // Type legalization might introduce new shuffles in the DAG.
12735 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12736 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12737 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12738 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12739 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12740 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12741 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12742 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12743
12744 if (SVN0->getMask().equals(SVN1->getMask())) {
12745 EVT VT = N->getValueType(0);
12746 SDValue UndefVector = LHS.getOperand(1);
12747 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12748 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012749 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012750 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12751 &SVN0->getMask()[0]);
12752 }
12753 }
12754
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012755 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000012756}
12757
Andrew Trickef9de2a2013-05-25 02:42:55 +000012758SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012759 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000012760 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000012761
Bill Wendling31b50992009-01-30 23:59:18 +000012762 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000012763 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000012764
Nate Begeman2042aa52005-10-08 00:29:44 +000012765 // If we got a simplified select_cc node back from SimplifySelectCC, then
12766 // break it down into a new SETCC node, and a new SELECT node, and then return
12767 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000012768 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012769 // Check to see if we got a select_cc back (to turn into setcc/select).
12770 // Otherwise, just return whatever node we got back, like fabs.
12771 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012772 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012773 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000012774 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000012775 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012776 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000012777 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12778 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000012779 }
Bill Wendling31b50992009-01-30 23:59:18 +000012780
Nate Begeman2042aa52005-10-08 00:29:44 +000012781 return SCC;
12782 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012783 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012784}
12785
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012786/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12787/// being selected between, see if we can simplify the select. Callers of this
12788/// should assume that TheSelect is deleted if this returns true. As such, they
12789/// should return the appropriate thing (e.g. the node) back to the top-level of
12790/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012791bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012792 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012793
Tom Stellard69a7b912015-04-20 19:38:27 +000012794 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12795 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12796 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12797 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12798 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12799 SDValue Sqrt = RHS;
12800 ISD::CondCode CC;
12801 SDValue CmpLHS;
12802 const ConstantFPSDNode *NegZero = nullptr;
12803
12804 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12805 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12806 CmpLHS = TheSelect->getOperand(0);
12807 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12808 } else {
12809 // SELECT or VSELECT
12810 SDValue Cmp = TheSelect->getOperand(0);
12811 if (Cmp.getOpcode() == ISD::SETCC) {
12812 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12813 CmpLHS = Cmp.getOperand(0);
12814 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12815 }
12816 }
12817 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12818 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12819 CC == ISD::SETULT || CC == ISD::SETLT)) {
12820 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12821 CombineTo(TheSelect, Sqrt);
12822 return true;
12823 }
12824 }
12825 }
Nadav Rotema49a02a2011-02-11 19:57:47 +000012826 // Cannot simplify select with vector condition
12827 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12828
Chris Lattner6c14c352005-10-18 06:04:22 +000012829 // If this is a select from two identical things, try to pull the operation
12830 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000012831 if (LHS.getOpcode() != RHS.getOpcode() ||
12832 !LHS.hasOneUse() || !RHS.hasOneUse())
12833 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012834
Chris Lattner254c4452010-09-21 15:46:59 +000012835 // If this is a load and the token chain is identical, replace the select
12836 // of two loads with a load through a select of the address to load from.
12837 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12838 // constants have been dropped into the constant pool.
12839 if (LHS.getOpcode() == ISD::LOAD) {
12840 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12841 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000012842
Chris Lattner254c4452010-09-21 15:46:59 +000012843 // Token chains must be identical.
12844 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000012845 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000012846 LLD->isVolatile() || RLD->isVolatile() ||
Hal Finkel0d49cf22015-04-22 11:32:25 +000012847 // FIXME: If either is a pre/post inc/dec load,
12848 // we'd need to split out the address adjustment.
12849 LLD->isIndexed() || RLD->isIndexed() ||
Chris Lattner254c4452010-09-21 15:46:59 +000012850 // If this is an EXTLOAD, the VT's must match.
12851 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000012852 // If this is an EXTLOAD, the kind of extension must match.
12853 (LLD->getExtensionType() != RLD->getExtensionType() &&
12854 // The only exception is if one of the extensions is anyext.
12855 LLD->getExtensionType() != ISD::EXTLOAD &&
12856 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000012857 // FIXME: this discards src value information. This is
12858 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000012859 // both potential memory locations. Since we are discarding
12860 // src value info, don't do the transformation if the memory
12861 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000012862 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000012863 RLD->getPointerInfo().getAddrSpace() != 0 ||
12864 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12865 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000012866 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012867
Chris Lattnere3267522010-09-21 15:58:55 +000012868 // Check that the select condition doesn't reach either load. If so,
12869 // folding this will induce a cycle into the DAG. If not, this is safe to
12870 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000012871 SDValue Addr;
12872 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000012873 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12874 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12875 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12876 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000012877 // The loads must not depend on one another.
12878 if (LLD->isPredecessorOf(RLD) ||
12879 RLD->isPredecessorOf(LLD))
12880 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012881 Addr = DAG.getSelect(SDLoc(TheSelect),
12882 LLD->getBasePtr().getValueType(),
12883 TheSelect->getOperand(0), LLD->getBasePtr(),
12884 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000012885 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000012886 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12887 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12888
12889 if ((LLD->hasAnyUseOfValue(1) &&
12890 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000012891 (RLD->hasAnyUseOfValue(1) &&
12892 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000012893 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012894
Andrew Trickef9de2a2013-05-25 02:42:55 +000012895 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000012896 LLD->getBasePtr().getValueType(),
12897 TheSelect->getOperand(0),
12898 TheSelect->getOperand(1),
12899 LLD->getBasePtr(), RLD->getBasePtr(),
12900 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000012901 }
12902
Chris Lattnere3267522010-09-21 15:58:55 +000012903 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000012904 // It is safe to replace the two loads if they have different alignments,
12905 // but the new load must be the minimum (most restrictive) alignment of the
12906 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000012907 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000012908 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000012909 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12910 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012911 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000012912 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012913 LLD->getChain(), Addr, MachinePointerInfo(),
12914 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012915 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000012916 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000012917 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12918 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012919 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000012920 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000012921 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012922 LLD->getChain(), Addr, MachinePointerInfo(),
12923 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012924 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000012925 }
Chris Lattnere3267522010-09-21 15:58:55 +000012926
12927 // Users of the select now use the result of the load.
12928 CombineTo(TheSelect, Load);
12929
12930 // Users of the old loads now use the new load's chain. We know the
12931 // old-load value is dead now.
12932 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12933 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12934 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000012935 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012936
Chris Lattner6c14c352005-10-18 06:04:22 +000012937 return false;
12938}
12939
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012940/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000012941/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000012942SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012943 SDValue N2, SDValue N3,
12944 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000012945 // (x ? y : y) -> y.
12946 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000012947
Owen Anderson53aa7a92009-08-10 22:56:29 +000012948 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000012949 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12950 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12951 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012952
12953 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000012954 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000012955 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012956 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000012957 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012958
12959 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000012960 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012961 return N2;
12962 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000012963 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012964 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012965
Nate Begeman2042aa52005-10-08 00:29:44 +000012966 // Check to see if we can simplify the select into an fabs node
12967 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12968 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000012969 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012970 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12971 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12972 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12973 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000012974 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012975
Nate Begeman2042aa52005-10-08 00:29:44 +000012976 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12977 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12978 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12979 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000012980 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000012981 }
12982 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012983
Chris Lattner43d63772009-03-11 05:08:08 +000012984 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12985 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12986 // in it. This is a win when the constant is not otherwise available because
12987 // it replaces two constant pool loads with one. We only do this if the FP
12988 // type is known to be legal, because if it isn't, then we are before legalize
12989 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000012990 // messing with soft float) and if the ConstantFP is not legal, because if
12991 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000012992 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12993 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12994 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000012995 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000012996 TargetLowering::Legal &&
12997 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12998 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000012999 // If both constants have multiple uses, then we won't need to do an
13000 // extra load, they are likely around in registers for other users.
13001 (TV->hasOneUse() || FV->hasOneUse())) {
13002 Constant *Elts[] = {
13003 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13004 const_cast<ConstantFP*>(TV->getConstantFPValue())
13005 };
Chris Lattner229907c2011-07-18 04:54:35 +000013006 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000013007 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000013008
Chris Lattner43d63772009-03-11 05:08:08 +000013009 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000013010 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000013011 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13012 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000013013 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000013014
13015 // Get the offsets to the 0 and 1 element of the array so that we can
13016 // select between them.
13017 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000013018 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000013019 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000013020
Chris Lattner43d63772009-03-11 05:08:08 +000013021 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000013022 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000013023 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013024 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000013025 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13026 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013027 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000013028 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000013029 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013030 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000013031 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000013032 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000013033 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000013034
13035 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013036 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013037
Nate Begeman2042aa52005-10-08 00:29:44 +000013038 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000013039 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000013040 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000013041 (N1C->isNullValue() || // (a < 0) ? b : 0
13042 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000013043 EVT XType = N0.getValueType();
13044 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000013045 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000013046 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000013047 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000013048 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
13049 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000013050 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000013051 SDValue ShCt = DAG.getConstant(ShCtV,
13052 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013053 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013054 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013055 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000013056
Duncan Sands11dd4242008-06-08 20:54:56 +000013057 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000013058 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013059 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013060 }
Bill Wendling31b50992009-01-30 23:59:18 +000013061
13062 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000013063 }
Bill Wendling31b50992009-01-30 23:59:18 +000013064
Andrew Trickef9de2a2013-05-25 02:42:55 +000013065 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013066 XType, N0,
13067 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013068 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013069 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000013070
Duncan Sands11dd4242008-06-08 20:54:56 +000013071 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000013072 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013073 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013074 }
Bill Wendling31b50992009-01-30 23:59:18 +000013075
13076 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000013077 }
13078 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013079
Owen Anderson3231d132010-09-22 22:58:22 +000013080 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13081 // where y is has a single bit set.
13082 // A plaintext description would be, we can turn the SELECT_CC into an AND
13083 // when the condition can be materialized as an all-ones register. Any
13084 // single bit-test can be materialized as an all-ones register with
13085 // shift-left and shift-right-arith.
13086 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13087 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000013088 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000013089 N2C && N2C->isNullValue()) {
13090 SDValue AndLHS = N0->getOperand(0);
13091 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13092 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13093 // Shift the tested bit over the sign bit.
13094 APInt AndMask = ConstAndRHS->getAPIntValue();
13095 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000013096 DAG.getConstant(AndMask.countLeadingZeros(),
13097 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013098 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000013099
Owen Anderson3231d132010-09-22 22:58:22 +000013100 // Now arithmetic right shift it all the way over, so the result is either
13101 // all-ones, or zero.
13102 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000013103 DAG.getConstant(AndMask.getBitWidth()-1,
13104 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013105 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000013106
Owen Anderson3231d132010-09-22 22:58:22 +000013107 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13108 }
13109 }
13110
Nate Begeman6828ed92005-10-10 21:26:48 +000013111 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000013112 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000013113 TLI.getBooleanContents(N0.getValueType()) ==
13114 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013115
Chris Lattnera083ffc2007-04-11 06:50:51 +000013116 // If the caller doesn't want us to simplify this into a zext of a compare,
13117 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000013118 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013119 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013120
Nate Begeman6828ed92005-10-10 21:26:48 +000013121 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013122 // NOTE: Don't create a SETCC if it's not legal on this target.
13123 if (!LegalOperations ||
13124 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000013125 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013126 SDValue Temp, SCC;
13127 // cast from setcc result type to select result type
13128 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000013129 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013130 N0, N1, CC);
13131 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000013132 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013133 N2.getValueType());
13134 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000013135 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013136 N2.getValueType(), SCC);
13137 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013138 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13139 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000013140 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013141 }
13142
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013143 AddToWorklist(SCC.getNode());
13144 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013145
13146 if (N2C->getAPIntValue() == 1)
13147 return Temp;
13148
13149 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000013150 return DAG.getNode(
13151 ISD::SHL, DL, N2.getValueType(), Temp,
13152 DAG.getConstant(N2C->getAPIntValue().logBase2(),
13153 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000013154 }
Nate Begeman6828ed92005-10-10 21:26:48 +000013155 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013156
Nate Begeman2042aa52005-10-08 00:29:44 +000013157 // Check to see if this is the equivalent of setcc
13158 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13159 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000013160 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000013161 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000013162 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000013163 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13164 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000013165 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000013166 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000013167 return Res;
13168 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013169
Bill Wendling31b50992009-01-30 23:59:18 +000013170 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000013171 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000013172 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000013173 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013174 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013175 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000013176 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013177 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000013178 }
Bill Wendling31b50992009-01-30 23:59:18 +000013179 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000013180 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013181 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013182 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000013183 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000013184 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000013185 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000013186 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013187 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000013188 }
Bill Wendling31b50992009-01-30 23:59:18 +000013189 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000013190 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013191 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000013192 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013193 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000013194 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000013195 }
13196 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013197
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013198 // Check to see if this is an integer abs.
13199 // select_cc setg[te] X, 0, X, -X ->
13200 // select_cc setgt X, -1, X, -X ->
13201 // select_cc setl[te] X, 0, -X, X ->
13202 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000013203 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013204 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000013205 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013206 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13207 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13208 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13209 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13210 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13211 (N1C->isOne() && CC == ISD::SETLT)) &&
13212 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13213 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13214
Owen Anderson53aa7a92009-08-10 22:56:29 +000013215 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013216 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013217 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013218 N0,
13219 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013220 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013221 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013222 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013223 AddToWorklist(Shift.getNode());
13224 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013225 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000013226 }
13227 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013228
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013229 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000013230}
13231
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013232/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000013233SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013234 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000013235 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013236 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000013237 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000013238 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000013239}
13240
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013241/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000013242/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000013243/// by a magic number.
13244/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013245SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013246 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13247 if (!C)
13248 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013249
13250 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013251 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013252 return SDValue();
13253
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000013254 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013255 SDValue S =
13256 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013257
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013258 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013259 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013260 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000013261}
13262
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013263/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13264/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000013265SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13266 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13267 if (!C)
13268 return SDValue();
13269
13270 // Avoid division by zero.
13271 if (!C->getAPIntValue())
13272 return SDValue();
13273
13274 std::vector<SDNode *> Built;
13275 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13276
13277 for (SDNode *N : Built)
13278 AddToWorklist(N);
13279 return S;
13280}
13281
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013282/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13283/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000013284/// number.
13285/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013286SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013287 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13288 if (!C)
13289 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013290
13291 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013292 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013293 return SDValue();
13294
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000013295 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013296 SDValue S =
13297 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000013298
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013299 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013300 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013301 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000013302}
13303
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013304SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13305 if (Level >= AfterLegalizeDAG)
13306 return SDValue();
13307
Sanjay Patelb67bd262014-09-21 15:19:15 +000013308 // Expose the DAG combiner to the target combiner implementations.
13309 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000013310
Sanjay Patelab7f4602014-09-30 20:44:23 +000013311 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000013312 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000013313 if (Iterations) {
13314 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13315 // For the reciprocal, we need to find the zero of the function:
13316 // F(X) = A X - 1 [which has a zero at X = 1/A]
13317 // =>
13318 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13319 // does not require additional intermediate precision]
13320 EVT VT = Op.getValueType();
13321 SDLoc DL(Op);
13322 SDValue FPOne = DAG.getConstantFP(1.0, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013323
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013324 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013325
Sanjay Patelab7f4602014-09-30 20:44:23 +000013326 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13327 for (unsigned i = 0; i < Iterations; ++i) {
13328 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13329 AddToWorklist(NewEst.getNode());
13330
13331 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13332 AddToWorklist(NewEst.getNode());
13333
13334 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13335 AddToWorklist(NewEst.getNode());
13336
13337 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13338 AddToWorklist(Est.getNode());
13339 }
13340 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013341 return Est;
13342 }
13343
13344 return SDValue();
13345}
13346
Sanjay Patel957efc232014-10-24 17:02:16 +000013347/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13348/// For the reciprocal sqrt, we need to find the zero of the function:
13349/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13350/// =>
13351/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13352/// As a result, we precompute A/2 prior to the iteration loop.
13353SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13354 unsigned Iterations) {
13355 EVT VT = Arg.getValueType();
13356 SDLoc DL(Arg);
13357 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013358
Sanjay Patel957efc232014-10-24 17:02:16 +000013359 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13360 // this entire sequence requires only one FP constant.
13361 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13362 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013363
Sanjay Patel957efc232014-10-24 17:02:16 +000013364 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13365 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013366
Sanjay Patel957efc232014-10-24 17:02:16 +000013367 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13368 for (unsigned i = 0; i < Iterations; ++i) {
13369 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13370 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013371
Sanjay Patel957efc232014-10-24 17:02:16 +000013372 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13373 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013374
Sanjay Patel957efc232014-10-24 17:02:16 +000013375 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13376 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013377
Sanjay Patel957efc232014-10-24 17:02:16 +000013378 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13379 AddToWorklist(Est.getNode());
13380 }
13381 return Est;
13382}
13383
13384/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13385/// For the reciprocal sqrt, we need to find the zero of the function:
13386/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13387/// =>
13388/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13389SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13390 unsigned Iterations) {
13391 EVT VT = Arg.getValueType();
13392 SDLoc DL(Arg);
13393 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13394 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13395
13396 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13397 for (unsigned i = 0; i < Iterations; ++i) {
13398 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13399 AddToWorklist(HalfEst.getNode());
13400
13401 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13402 AddToWorklist(Est.getNode());
13403
13404 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13405 AddToWorklist(Est.getNode());
13406
13407 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13408 AddToWorklist(Est.getNode());
13409
13410 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13411 AddToWorklist(Est.getNode());
13412 }
13413 return Est;
13414}
13415
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013416SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13417 if (Level >= AfterLegalizeDAG)
13418 return SDValue();
13419
13420 // Expose the DAG combiner to the target combiner implementations.
13421 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013422 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000013423 bool UseOneConstNR = false;
13424 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13425 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000013426 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000013427 Est = UseOneConstNR ?
13428 BuildRsqrtNROneConst(Op, Est, Iterations) :
13429 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013430 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013431 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000013432 }
13433
13434 return SDValue();
13435}
13436
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013437/// Return true if base is a frame index, which is known not to alias with
13438/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000013439static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000013440 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000013441 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000013442 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013443
Jim Laskey0463e082006-10-07 23:37:56 +000013444 // If it's an adding a simple constant then integrate the offset.
13445 if (Base.getOpcode() == ISD::ADD) {
13446 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13447 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000013448 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000013449 }
13450 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013451
Nate Begeman18150d52009-09-25 06:05:26 +000013452 // Return the underlying GlobalValue, and update the Offset. Return false
13453 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13454 // by multiple nodes with different offsets.
13455 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13456 GV = G->getGlobal();
13457 Offset += G->getOffset();
13458 return false;
13459 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013460
Nate Begeman18150d52009-09-25 06:05:26 +000013461 // Return the underlying Constant value, and update the Offset. Return false
13462 // for ConstantSDNodes since the same constant pool entry may be represented
13463 // by multiple nodes with different offsets.
13464 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000013465 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13466 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000013467 Offset += C->getOffset();
13468 return false;
13469 }
Jim Laskey0463e082006-10-07 23:37:56 +000013470 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000013471 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000013472}
13473
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013474/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013475bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000013476 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013477 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013478
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013479 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013480 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013481
Jim Laskey0463e082006-10-07 23:37:56 +000013482 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013483 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000013484 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000013485 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000013486 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013487 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13488 Base1, Offset1, GV1, CV1);
13489 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13490 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013491
Nate Begeman18150d52009-09-25 06:05:26 +000013492 // If they have a same base address then check to see if they overlap.
13493 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013494 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13495 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013496
Owen Anderson272ff942010-09-20 20:39:59 +000013497 // It is possible for different frame indices to alias each other, mostly
13498 // when tail call optimization reuses return address slots for arguments.
13499 // To catch this case, look up the actual index of frame indices to compute
13500 // the real alias relationship.
13501 if (isFrameIndex1 && isFrameIndex2) {
13502 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13503 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13504 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013505 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13506 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000013507 }
13508
Wesley Peck527da1b2010-11-23 03:31:01 +000013509 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000013510 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000013511 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13512 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013513
Nate Begeman879d8f12009-09-15 00:18:30 +000013514 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13515 // compared to the size and offset of the access, we may be able to prove they
13516 // do not alias. This check is conservative for now to catch cases created by
13517 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013518 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13519 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13520 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13521 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13522 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13523 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13524 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000013525
Nate Begeman879d8f12009-09-15 00:18:30 +000013526 // There is no overlap between these relatively aligned accesses of similar
13527 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013528 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13529 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000013530 return false;
13531 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013532
Eric Christopherf55d4712014-10-08 23:38:39 +000013533 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13534 ? CombinerGlobalAA
13535 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000013536#ifndef NDEBUG
13537 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13538 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13539 UseAA = false;
13540#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013541 if (UseAA &&
13542 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000013543 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013544 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13545 Op1->getSrcValueOffset());
13546 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13547 Op0->getSrcValueOffset() - MinOffset;
13548 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13549 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013550 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013551 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13552 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000013553 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013554 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13555 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000013556 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000013557 if (AAResult == AliasAnalysis::NoAlias)
13558 return false;
13559 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013560
13561 // Otherwise we have to assume they alias.
13562 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000013563}
13564
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013565/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000013566/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013567void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000013568 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013569 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000013570 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013571
Jim Laskeyd07be232006-09-25 16:29:54 +000013572 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013573 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000013574
Jim Laskey708d0db2006-10-04 16:53:27 +000013575 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000013576 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013577 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000013578
Jim Laskey6549d222006-10-05 15:07:25 +000013579 // Look at each chain and determine if it is an alias. If so, add it to the
13580 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000013581 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000013582 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013583 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000013584 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000013585
13586 // For TokenFactor nodes, look at each operand and only continue up the
13587 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013588 // find more and revert to original chain since the xform is unlikely to be
13589 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000013590 //
13591 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013592 // chain we found before we hit a tokenfactor rather than the original
13593 // chain.
13594 if (Depth > 6 || Aliases.size() == 2) {
13595 Aliases.clear();
13596 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000013597 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013598 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013599
Nate Begeman879d8f12009-09-15 00:18:30 +000013600 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000013601 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000013602 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013603
Jim Laskey6549d222006-10-05 15:07:25 +000013604 switch (Chain.getOpcode()) {
13605 case ISD::EntryToken:
13606 // Entry token is ideal chain operand, but handled in FindBetterChain.
13607 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013608
Jim Laskey6549d222006-10-05 15:07:25 +000013609 case ISD::LOAD:
13610 case ISD::STORE: {
13611 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013612 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13613 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013614
Jim Laskey6549d222006-10-05 15:07:25 +000013615 // If chain is alias then stop here.
13616 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013617 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000013618 Aliases.push_back(Chain);
13619 } else {
13620 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013621 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013622 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000013623 }
Jim Laskey6549d222006-10-05 15:07:25 +000013624 break;
13625 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013626
Jim Laskey6549d222006-10-05 15:07:25 +000013627 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000013628 // We have to check each of the operands of the token factor for "small"
13629 // token factors, so we queue them up. Adding the operands to the queue
13630 // (stack) in reverse order maintains the original order and increases the
13631 // likelihood that getNode will find a matching token factor (CSE.)
13632 if (Chain.getNumOperands() > 16) {
13633 Aliases.push_back(Chain);
13634 break;
13635 }
Jim Laskey6549d222006-10-05 15:07:25 +000013636 for (unsigned n = Chain.getNumOperands(); n;)
13637 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013638 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000013639 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013640
Jim Laskey6549d222006-10-05 15:07:25 +000013641 default:
13642 // For all other instructions we will just have to take what we can get.
13643 Aliases.push_back(Chain);
13644 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000013645 }
13646 }
Hal Finkel51a98382014-01-24 20:12:02 +000013647
13648 // We need to be careful here to also search for aliases through the
13649 // value operand of a store, etc. Consider the following situation:
13650 // Token1 = ...
13651 // L1 = load Token1, %52
13652 // S1 = store Token1, L1, %51
13653 // L2 = load Token1, %52+8
13654 // S2 = store Token1, L2, %51+8
13655 // Token2 = Token(S1, S2)
13656 // L3 = load Token2, %53
13657 // S3 = store Token2, L3, %52
13658 // L4 = load Token2, %53+8
13659 // S4 = store Token2, L4, %52+8
13660 // If we search for aliases of S3 (which loads address %52), and we look
13661 // only through the chain, then we'll miss the trivial dependence on L1
13662 // (which also loads from %52). We then might change all loads and
13663 // stores to use Token1 as their chain operand, which could result in
13664 // copying %53 into %52 before copying %52 into %51 (which should
13665 // happen first).
13666 //
13667 // The problem is, however, that searching for such data dependencies
13668 // can become expensive, and the cost is not directly related to the
13669 // chain depth. Instead, we'll rule out such configurations here by
13670 // insisting that we've visited all chain users (except for users
13671 // of the original chain, which is not necessary). When doing this,
13672 // we need to look through nodes we don't care about (otherwise, things
13673 // like register copies will interfere with trivial cases).
13674
13675 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000013676 for (const SDNode *N : Visited)
13677 if (N != OriginalChain.getNode())
13678 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000013679
13680 while (!Worklist.empty()) {
13681 const SDNode *M = Worklist.pop_back_val();
13682
13683 // We have already visited M, and want to make sure we've visited any uses
13684 // of M that we care about. For uses that we've not visisted, and don't
13685 // care about, queue them to the worklist.
13686
13687 for (SDNode::use_iterator UI = M->use_begin(),
13688 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000013689 if (UI.getUse().getValueType() == MVT::Other &&
13690 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000013691 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13692 // We've not visited this use, and we care about it (it could have an
13693 // ordering dependency with the original node).
13694 Aliases.clear();
13695 Aliases.push_back(OriginalChain);
13696 return;
13697 }
13698
13699 // We've not visited this use, but we don't care about it. Mark it as
13700 // visited and enqueue it to the worklist.
13701 Worklist.push_back(*UI);
13702 }
13703 }
Jim Laskey708d0db2006-10-04 16:53:27 +000013704}
13705
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013706/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13707/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013708SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13709 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013710
Jim Laskey708d0db2006-10-04 16:53:27 +000013711 // Accumulate all the aliases to this node.
13712 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013713
Dan Gohman4298df62011-05-17 22:20:36 +000013714 // If no operands then chain to entry token.
13715 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000013716 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000013717
13718 // If a single operand then chain to it. We don't need to revisit it.
13719 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000013720 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000013721
Jim Laskey708d0db2006-10-04 16:53:27 +000013722 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000013723 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000013724}
13725
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013726/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000013727void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000013728 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013729 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000013730 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000013731}