blob: 1186683aebafd64fb48dfd47d8505b19ba29f7d1 [file] [log] [blame]
Nate Begeman2504fe22005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman21158fc2005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman21158fc2005-09-01 00:19:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012//
Dan Gohman45399872009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman21158fc2005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
Nate Begeman21158fc2005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth9a0051c2014-07-23 07:08:53 +000021#include "llvm/ADT/SetVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000022#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043#define DEBUG_TYPE "dagcombine"
44
Chris Lattneraee775a2006-12-19 22:41:21 +000045STATISTIC(NodesCombined , "Number of dag nodes combined");
46STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000048STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000049STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000050STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000051
Nate Begeman21158fc2005-09-01 00:19:25 +000052namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000053 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000054 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000055 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000056
Jim Laskey55e4dca2006-10-18 19:08:31 +000057 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000059 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000060
Hal Finkeldbebb522014-01-25 19:24:54 +000061 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000062 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000063 cl::desc("Enable DAG combiner's use of TBAA"));
64
Hal Finkel9b2617a2014-01-25 17:32:39 +000065#ifndef NDEBUG
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
69 " function"));
70#endif
71
Quentin Colombetde0e0622013-10-11 18:29:42 +000072 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
74 static cl::opt<bool>
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
77 "slicing"),
78 cl::init(false));
79
Hal Finkel51e6fa22014-09-02 06:24:04 +000080 static cl::opt<bool>
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
83
Jim Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
Chandler Carruth9a0051c2014-07-23 07:08:53 +000095 /// \brief Worklist of all of the nodes that need to be simplified.
96 ///
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
99 ///
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
103
104 /// \brief Mapping from an SDNode to its position on the worklist.
105 ///
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000110
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000111 /// \brief Set of nodes which have been combined (at least once).
112 ///
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
116
Jim Laskeydcb2b832006-10-16 20:52:31 +0000117 // AA - Used for DAG load/store alias analysis.
118 AliasAnalysis &AA;
119
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000123 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000124 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000125 }
126
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000127 /// Call the node-specific routine that folds each particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000128 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000129
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000130 public:
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000131 /// Add to the worklist making sure its instance is at the back (next to be
132 /// processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000133 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
137 return;
138
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000141 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000142
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000143 /// Remove all instances of N from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000144 void removeFromWorklist(SDNode *N) {
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000145 CombinedNodes.erase(N);
146
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
150
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000155
Chandler Carruth18066972014-08-02 10:02:07 +0000156 void deleteAndRecombine(SDNode *N);
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000157 bool recursivelyDeleteUnusedNodes(SDNode *N);
158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000160 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000161
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000163 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000164 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000167 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000168 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000169 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000170 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000171
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000173
174 private:
175
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000179 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000182 return SimplifyDemandedBits(Op, Demanded);
183 }
184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000186
Chris Lattnerffad2162006-11-11 00:39:41 +0000187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
Hal Finkel51e6fa22014-09-02 06:24:04 +0000189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000190 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000191
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193 /// load.
194 ///
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000206 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000207 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000210
Craig Toppere0b71182013-07-13 07:43:40 +0000211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000213 ISD::NodeType ExtType);
214
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000215 /// Call the node-specific routine that knows how to fold each
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000218 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000219
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
222 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000226 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000232 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000234 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000252 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000256 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000257 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000259 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000263 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000271 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000276 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFCOPYSIGN(SDNode *N);
280 SDValue visitSINT_TO_FP(SDNode *N);
281 SDValue visitUINT_TO_FP(SDNode *N);
282 SDValue visitFP_TO_SINT(SDNode *N);
283 SDValue visitFP_TO_UINT(SDNode *N);
284 SDValue visitFP_ROUND(SDNode *N);
285 SDValue visitFP_ROUND_INREG(SDNode *N);
286 SDValue visitFP_EXTEND(SDNode *N);
287 SDValue visitFNEG(SDNode *N);
288 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000289 SDValue visitFCEIL(SDNode *N);
290 SDValue visitFTRUNC(SDNode *N);
291 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000292 SDValue visitBRCOND(SDNode *N);
293 SDValue visitBR_CC(SDNode *N);
294 SDValue visitLOAD(SDNode *N);
295 SDValue visitSTORE(SDNode *N);
296 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
297 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
298 SDValue visitBUILD_VECTOR(SDNode *N);
299 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000300 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000301 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000302 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000303
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000304 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000305 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000306
Matt Arsenault985b9de2014-03-17 18:58:01 +0000307 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000308
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000309 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
310 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000311 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
312 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000313 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000314 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000315 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000316 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000317
318 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319 SDValue &CC) const;
320 bool isOneUseSetCC(SDValue N) const;
321
Scott Michelcf0da6c2009-02-17 22:15:04 +0000322 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000323 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000324 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000325 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000326 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000327 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000328 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000329 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
330 bool DemandHighBits = true);
331 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000332 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
333 SDValue InnerPos, SDValue InnerNeg,
334 unsigned PosOpcode, unsigned NegOpcode,
335 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000336 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000337 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000338 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000339 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000340 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000341 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000342
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000343 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000344
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000345 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000346 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000347 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000348 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000349
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000350 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000351 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000352
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000353 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
354 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000355 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000356
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000357 /// Merge consecutive store operations into a wide store.
358 /// This optimization uses wide integers or vectors when possible.
359 /// \return True if some memory operations were changed.
360 bool MergeConsecutiveStores(StoreSDNode *N);
361
Adam Nemet67483892014-03-04 23:28:31 +0000362 /// \brief Try to transform a truncation where C is a constant:
363 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
364 ///
365 /// \p N needs to be a truncation and its first operand an AND. Other
366 /// requirements are checked by the function (e.g. that trunc is
367 /// single-use) and if missed an empty SDValue is returned.
368 SDValue distributeTruncateThroughAnd(SDNode *N);
369
Chris Lattner4041ab62010-04-15 04:48:01 +0000370 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000371 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000372 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374 AttributeSet FnAttrs =
375 DAG.getMachineFunction().getFunction()->getAttributes();
376 ForCodeSize =
377 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378 Attribute::OptimizeForSize) ||
379 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
380 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000381
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000382 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000383 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000384
Chris Lattner4041ab62010-04-15 04:48:01 +0000385 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000386
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000387 /// Returns a type large enough to hold any valid shift amount - before type
388 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000389 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000390 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391 if (LHSTy.isVector())
392 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000393 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000395 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000396
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000397 /// This method returns true if we are running before type legalization or
398 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000399 bool isTypeLegal(const EVT &VT) {
400 if (!LegalTypes) return true;
401 return TLI.isTypeLegal(VT);
402 }
Matt Arsenault758659232013-05-18 00:21:46 +0000403
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000404 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000405 EVT getSetCCResultType(EVT VT) const {
406 return TLI.getSetCCResultType(*DAG.getContext(), VT);
407 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000408 };
409}
410
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000411
412namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000413/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000414/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000415class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000416 DAGCombiner &DC;
417public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000418 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000419 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000420
Craig Topper7b883b32014-03-08 06:31:39 +0000421 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000422 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000423 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000424};
425}
426
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000427//===----------------------------------------------------------------------===//
428// TargetLowering::DAGCombinerInfo implementation
429//===----------------------------------------------------------------------===//
430
431void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000432 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000433}
434
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000435void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000436 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000437}
438
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000439SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000440CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
441 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000442}
443
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000444SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000445CombineTo(SDNode *N, SDValue Res, bool AddTo) {
446 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000447}
448
449
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000450SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000451CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
452 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000453}
454
Dan Gohmane58ab792009-01-29 01:59:02 +0000455void TargetLowering::DAGCombinerInfo::
456CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
457 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
458}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000459
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000460//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000461// Helper Functions
462//===----------------------------------------------------------------------===//
463
Chandler Carruth18066972014-08-02 10:02:07 +0000464void DAGCombiner::deleteAndRecombine(SDNode *N) {
465 removeFromWorklist(N);
466
467 // If the operands of this node are only used by the node, they will now be
468 // dead. Make sure to re-visit them and recursively delete dead nodes.
469 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000470 // For an operand generating multiple values, one of the values may
471 // become dead allowing further simplification (e.g. split index
472 // arithmetic from an indexed load).
473 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000474 AddToWorklist(Op.getNode());
475
476 DAG.DeleteNode(N);
477}
478
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000479/// Return 1 if we can compute the negated form of the specified expression for
480/// the same cost as the expression itself, or 2 if we can compute the negated
481/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000482static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000483 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000484 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000485 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000486 // fneg is removable even if it has multiple uses.
487 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000488
Chris Lattnere49c9742007-05-14 22:04:50 +0000489 // Don't allow anything with multiple uses.
490 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000491
Chris Lattner46980832007-05-25 02:19:06 +0000492 // Don't recurse exponentially.
493 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000494
Chris Lattnere49c9742007-05-14 22:04:50 +0000495 switch (Op.getOpcode()) {
496 default: return false;
497 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000498 // Don't invert constant FP values after legalize. The negated constant
499 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000500 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000501 case ISD::FADD:
502 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000503 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000504
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000505 // After operation legalization, it might not be legal to create new FSUBs.
506 if (LegalOperations &&
507 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
508 return 0;
509
Craig Topper03f39772012-09-09 22:58:45 +0000510 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000511 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000513 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000514 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000515 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000516 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000517 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000518 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000519 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000520
Bill Wendling6fbf5492009-01-30 23:10:18 +0000521 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000523
Chris Lattnere49c9742007-05-14 22:04:50 +0000524 case ISD::FMUL:
525 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000526 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000527
Bill Wendling6fbf5492009-01-30 23:10:18 +0000528 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000529 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
530 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000531 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000532
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000533 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000534 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000535
Chris Lattnere49c9742007-05-14 22:04:50 +0000536 case ISD::FP_EXTEND:
537 case ISD::FP_ROUND:
538 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000539 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000540 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000541 }
542}
543
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000544/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000545static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000546 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000547 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000548 // fneg is removable even if it has multiple uses.
549 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000550
Chris Lattnere49c9742007-05-14 22:04:50 +0000551 // Don't allow anything with multiple uses.
552 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000553
Chris Lattner46980832007-05-25 02:19:06 +0000554 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000555 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000556 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000557 case ISD::ConstantFP: {
558 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
559 V.changeSign();
560 return DAG.getConstantFP(V, Op.getValueType());
561 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000562 case ISD::FADD:
563 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000564 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000565
Bill Wendling6fbf5492009-01-30 23:10:18 +0000566 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000567 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000568 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000569 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000570 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000571 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000572 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000573 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000574 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000575 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000576 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000577 Op.getOperand(0));
578 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000580 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000581
Bill Wendling6fbf5492009-01-30 23:10:18 +0000582 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000583 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000584 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000585 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000586
Bill Wendling6fbf5492009-01-30 23:10:18 +0000587 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000588 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000589 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000590
Chris Lattnere49c9742007-05-14 22:04:50 +0000591 case ISD::FMUL:
592 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000593 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000594
Bill Wendling6fbf5492009-01-30 23:10:18 +0000595 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000596 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000597 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000598 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000599 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000600 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000601 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000602
Bill Wendling6fbf5492009-01-30 23:10:18 +0000603 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000604 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000605 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000606 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000607 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000608
Chris Lattnere49c9742007-05-14 22:04:50 +0000609 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000610 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000611 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000612 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000613 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000614 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000615 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000616 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000617 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000618 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000619 }
620}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000621
Nate Begeman2504fe22005-09-01 23:24:04 +0000622// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000623// that selects between the target values used for true and false, making it
624// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625// the appropriate nodes based on the type of node we are checking. This
626// simplifies life a bit for the callers.
627bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
628 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000629 if (N.getOpcode() == ISD::SETCC) {
630 LHS = N.getOperand(0);
631 RHS = N.getOperand(1);
632 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000633 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000634 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000635
636 if (N.getOpcode() != ISD::SELECT_CC ||
637 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
639 return false;
640
641 LHS = N.getOperand(0);
642 RHS = N.getOperand(1);
643 CC = N.getOperand(4);
644 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000645}
646
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000647/// Return true if this is a SetCC-equivalent operation with only one use.
648/// If this is true, it allows the users to invert the operation for free when
649/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000650bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000651 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000652 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000653 return true;
654 return false;
655}
656
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000657/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000658/// elements are all the same constant or undefined.
659static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
661 if (!C)
662 return false;
663
664 APInt SplatUndef;
665 unsigned SplatBitSize;
666 bool HasAnyUndefs;
667 EVT EltVT = N->getValueType(0).getVectorElementType();
668 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
669 HasAnyUndefs) &&
670 EltVT.getSizeInBits() >= SplatBitSize);
671}
672
673// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000674static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675 if (isa<ConstantSDNode>(N))
676 return N.getNode();
677 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678 if(BV && BV->isConstant())
679 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000680 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000681}
682
Matt Arsenault985b9de2014-03-17 18:58:01 +0000683// \brief Returns the SDNode if it is a constant splat BuildVector or constant
684// int.
685static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
687 return CN;
688
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000689 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000690 BitVector UndefElements;
691 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000692
693 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000694 // FIXME: We blindly ignore splats which include undef which is overly
695 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000696 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000697 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000698 return CN;
699 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000700
701 return nullptr;
702}
703
Matt Arsenault6cc00422014-08-16 10:14:19 +0000704// \brief Returns the SDNode if it is a constant splat BuildVector or constant
705// float.
706static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
708 return CN;
709
710 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711 BitVector UndefElements;
712 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
713
714 // BuildVectors can truncate their operands. Ignore that case here.
715 // FIXME: We blindly ignore splats which include undef which is overly
716 // pessimistic.
717 if (CN && UndefElements.none() &&
718 CN->getValueType(0) == N.getValueType().getScalarType())
719 return CN;
720 }
721
722 return nullptr;
723}
724
Andrew Trickef9de2a2013-05-25 02:42:55 +0000725SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000726 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000727 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000728 if (N0.getOpcode() == Opc) {
729 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733 if (!OpNode.getNode())
734 return SDValue();
735 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000736 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000737 if (N0.hasOneUse()) {
738 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
739 // use
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741 if (!OpNode.getNode())
742 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000743 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000744 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000745 }
746 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000747 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000748
Juergen Ributzka68402822014-01-13 21:49:25 +0000749 if (N1.getOpcode() == Opc) {
750 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754 if (!OpNode.getNode())
755 return SDValue();
756 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
757 }
758 if (N1.hasOneUse()) {
759 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
760 // use
761 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762 if (!OpNode.getNode())
763 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000764 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000765 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
766 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000767 }
768 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000769
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000770 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000771}
772
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000773SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
774 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000775 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
776 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000777 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000778 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000779 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000780 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000781 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000782 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000783 assert((!To[i].getNode() ||
784 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000785 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000786 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000787 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000788 if (AddTo) {
789 // Push the new nodes and any users onto the worklist
790 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000791 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000792 AddToWorklist(To[i].getNode());
793 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000794 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000795 }
796 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000797
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000798 // Finally, if the node is now dead, remove it from the graph. The node
799 // may not be dead if the replacement process recursively simplified to
800 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000801 if (N->use_empty())
802 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000803 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000804}
805
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000806void DAGCombiner::
807CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000808 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000809 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000810 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000811 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000812
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000813 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000814 AddToWorklist(TLO.New.getNode());
815 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000816
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000817 // Finally, if the node is now dead, remove it from the graph. The node
818 // may not be dead if the replacement process recursively simplified to
819 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000820 if (TLO.Old.getNode()->use_empty())
821 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000822}
823
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000824/// Check the specified integer node value to see if it can be simplified or if
825/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000826bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000827 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000828 APInt KnownZero, KnownOne;
829 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
830 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000831
Dan Gohmane58ab792009-01-29 01:59:02 +0000832 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000833 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000834
Dan Gohmane58ab792009-01-29 01:59:02 +0000835 // Replace the old value with the new one.
836 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000837 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000838 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000839 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000840 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000841 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000842
Dan Gohmane58ab792009-01-29 01:59:02 +0000843 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000844 return true;
845}
846
Evan Cheng0abb54d2010-04-24 04:43:44 +0000847void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000848 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000849 EVT VT = Load->getValueType(0);
850 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000851
Evan Cheng0abb54d2010-04-24 04:43:44 +0000852 DEBUG(dbgs() << "\nReplacing.9 ";
853 Load->dump(&DAG);
854 dbgs() << "\nWith: ";
855 Trunc.getNode()->dump(&DAG);
856 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000857 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000858 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
859 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000860 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000861 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000862}
863
864SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
865 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000866 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000867 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000868 EVT MemVT = LD->getMemoryVT();
869 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000870 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000871 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000872 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000873 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000874 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000875 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000876 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000877 }
878
Evan Chenge19aa5c2010-04-19 19:29:22 +0000879 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000880 switch (Opc) {
881 default: break;
882 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000883 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000884 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000885 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000886 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000887 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000888 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000889 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000890 case ISD::Constant: {
891 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000892 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000893 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000894 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000895 }
896
897 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000898 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000899 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000900}
901
Evan Cheng0abb54d2010-04-24 04:43:44 +0000902SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000903 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
904 return SDValue();
905 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000906 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000907 bool Replace = false;
908 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000909 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000910 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000911 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000912
913 if (Replace)
914 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
915 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000916 DAG.getValueType(OldVT));
917}
918
Evan Cheng0abb54d2010-04-24 04:43:44 +0000919SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000920 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000921 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000922 bool Replace = false;
923 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000924 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000925 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000926 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000927
928 if (Replace)
929 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
930 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000931}
932
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000933/// Promote the specified integer binary operation if the target indicates it is
934/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
935/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000936SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
937 if (!LegalOperations)
938 return SDValue();
939
940 EVT VT = Op.getValueType();
941 if (VT.isVector() || !VT.isInteger())
942 return SDValue();
943
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000944 // If operation type is 'undesirable', e.g. i16 on x86, consider
945 // promoting it.
946 unsigned Opc = Op.getOpcode();
947 if (TLI.isTypeDesirableForOp(Opc, VT))
948 return SDValue();
949
Evan Chengaf56fac2010-04-16 06:14:10 +0000950 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000951 // Consult target whether it is a good idea to promote this operation and
952 // what's the right type to promote it to.
953 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000954 assert(PVT != VT && "Don't know what type to promote to!");
955
Evan Cheng0abb54d2010-04-24 04:43:44 +0000956 bool Replace0 = false;
957 SDValue N0 = Op.getOperand(0);
958 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000959 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000960 return SDValue();
961
Evan Cheng0abb54d2010-04-24 04:43:44 +0000962 bool Replace1 = false;
963 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000964 SDValue NN1;
965 if (N0 == N1)
966 NN1 = NN0;
967 else {
968 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000969 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000970 return SDValue();
971 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000972
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000973 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000974 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000975 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000976
977 if (Replace0)
978 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
979 if (Replace1)
980 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000981
Evan Chenge8136902010-04-27 19:48:13 +0000982 DEBUG(dbgs() << "\nPromoting ";
983 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000984 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000985 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000986 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000987 }
988 return SDValue();
989}
990
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000991/// Promote the specified integer shift operation if the target indicates it is
992/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
993/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +0000994SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
995 if (!LegalOperations)
996 return SDValue();
997
998 EVT VT = Op.getValueType();
999 if (VT.isVector() || !VT.isInteger())
1000 return SDValue();
1001
1002 // If operation type is 'undesirable', e.g. i16 on x86, consider
1003 // promoting it.
1004 unsigned Opc = Op.getOpcode();
1005 if (TLI.isTypeDesirableForOp(Opc, VT))
1006 return SDValue();
1007
1008 EVT PVT = VT;
1009 // Consult target whether it is a good idea to promote this operation and
1010 // what's the right type to promote it to.
1011 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1012 assert(PVT != VT && "Don't know what type to promote to!");
1013
Evan Cheng0abb54d2010-04-24 04:43:44 +00001014 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001015 SDValue N0 = Op.getOperand(0);
1016 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001017 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001018 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001019 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001020 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001021 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001022 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001023 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001024
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001025 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001026 if (Replace)
1027 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001028
Evan Chenge8136902010-04-27 19:48:13 +00001029 DEBUG(dbgs() << "\nPromoting ";
1030 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001031 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001032 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001033 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001034 }
1035 return SDValue();
1036}
1037
Evan Chenge19aa5c2010-04-19 19:29:22 +00001038SDValue DAGCombiner::PromoteExtend(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 // fold (aext (aext x)) -> (aext x)
1058 // fold (aext (zext x)) -> (zext x)
1059 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001062 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001063 }
1064 return SDValue();
1065}
1066
1067bool DAGCombiner::PromoteLoad(SDValue Op) {
1068 if (!LegalOperations)
1069 return false;
1070
1071 EVT VT = Op.getValueType();
1072 if (VT.isVector() || !VT.isInteger())
1073 return false;
1074
1075 // If operation type is 'undesirable', e.g. i16 on x86, consider
1076 // promoting it.
1077 unsigned Opc = Op.getOpcode();
1078 if (TLI.isTypeDesirableForOp(Opc, VT))
1079 return false;
1080
1081 EVT PVT = VT;
1082 // Consult target whether it is a good idea to promote this operation and
1083 // what's the right type to promote it to.
1084 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1085 assert(PVT != VT && "Don't know what type to promote to!");
1086
Andrew Trickef9de2a2013-05-25 02:42:55 +00001087 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001088 SDNode *N = Op.getNode();
1089 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001090 EVT MemVT = LD->getMemoryVT();
1091 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001092 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001093 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001094 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001095 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001096 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001097 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001098 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1099
Evan Cheng0abb54d2010-04-24 04:43:44 +00001100 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001101 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001102 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001103 Result.getNode()->dump(&DAG);
1104 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001105 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001106 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001108 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001109 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001110 return true;
1111 }
1112 return false;
1113}
1114
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001115/// \brief Recursively delete a node which has no uses and any operands for
1116/// which it is the only use.
1117///
1118/// Note that this both deletes the nodes and removes them from the worklist.
1119/// It also adds any nodes who have had a user deleted to the worklist as they
1120/// may now have only one use and subject to other combines.
1121bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1122 if (!N->use_empty())
1123 return false;
1124
1125 SmallSetVector<SDNode *, 16> Nodes;
1126 Nodes.insert(N);
1127 do {
1128 N = Nodes.pop_back_val();
1129 if (!N)
1130 continue;
1131
1132 if (N->use_empty()) {
1133 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1134 Nodes.insert(N->getOperand(i).getNode());
1135
1136 removeFromWorklist(N);
1137 DAG.DeleteNode(N);
1138 } else {
1139 AddToWorklist(N);
1140 }
1141 } while (!Nodes.empty());
1142 return true;
1143}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001144
Chris Lattnere49c9742007-05-14 22:04:50 +00001145//===----------------------------------------------------------------------===//
1146// Main DAG Combiner implementation
1147//===----------------------------------------------------------------------===//
1148
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001149void DAGCombiner::Run(CombineLevel AtLevel) {
1150 // set the instance variables, so that the various visit routines may use it.
1151 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001152 LegalOperations = Level >= AfterLegalizeVectorOps;
1153 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001154
Evan Cheng5e7658c2008-08-29 22:21:44 +00001155 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001156 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1157 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001158 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001159
Evan Cheng5e7658c2008-08-29 22:21:44 +00001160 // Create a dummy node (which is not added to allnodes), that adds a reference
1161 // to the root node, preventing it from being deleted, and tracking any
1162 // changes of the root.
1163 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001164
James Molloy67b6b112012-02-16 09:17:04 +00001165 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001166 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001167 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001168 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001169 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001170 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001171 N = Worklist.pop_back_val();
1172 } while (!N);
1173
1174 bool GoodWorklistEntry = WorklistMap.erase(N);
1175 (void)GoodWorklistEntry;
1176 assert(GoodWorklistEntry &&
1177 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001178
Evan Cheng5e7658c2008-08-29 22:21:44 +00001179 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1180 // N is deleted from the DAG, since they too may now be dead or may have a
1181 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001182 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001183 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001184
1185 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001186
Chandler Carruth411fb402014-07-26 05:49:40 +00001187 // If this combine is running after legalizing the DAG, re-legalize any
1188 // nodes pulled off the worklist.
1189 if (Level == AfterLegalizeDAG) {
1190 SmallSetVector<SDNode *, 16> UpdatedNodes;
1191 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1192
1193 for (SDNode *LN : UpdatedNodes) {
1194 AddToWorklist(LN);
1195 AddUsersToWorklist(LN);
1196 }
1197 if (!NIsValid)
1198 continue;
1199 }
1200
Chandler Carruthb1432742014-07-28 17:55:07 +00001201 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1202
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001203 // Add any operands of the new node which have not yet been combined to the
1204 // worklist as well. Because the worklist uniques things already, this
1205 // won't repeatedly process the same operand.
1206 CombinedNodes.insert(N);
1207 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1208 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1209 AddToWorklist(N->getOperand(i).getNode());
1210
Evan Cheng5e7658c2008-08-29 22:21:44 +00001211 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001212
Craig Topperc0196b12014-04-14 00:51:57 +00001213 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001214 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001215
Evan Cheng5e7658c2008-08-29 22:21:44 +00001216 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001217
Evan Cheng5e7658c2008-08-29 22:21:44 +00001218 // If we get back the same node we passed in, rather than a new node or
1219 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001220 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001221 // mechanics for us, we have no work to do in this case.
1222 if (RV.getNode() == N)
1223 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001224
Evan Cheng5e7658c2008-08-29 22:21:44 +00001225 assert(N->getOpcode() != ISD::DELETED_NODE &&
1226 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1227 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001228
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001229 DEBUG(dbgs() << " ... into: ";
1230 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001231
Devang Patelefec7712011-05-23 22:04:42 +00001232 // Transfer debug value.
1233 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001234 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001235 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001236 else {
1237 assert(N->getValueType(0) == RV.getValueType() &&
1238 N->getNumValues() == 1 && "Type mismatch");
1239 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001240 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001241 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001242
Evan Cheng5e7658c2008-08-29 22:21:44 +00001243 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001244 AddToWorklist(RV.getNode());
1245 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001246
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001247 // Finally, if the node is now dead, remove it from the graph. The node
1248 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001249 // something else needing this node. This will also take care of adding any
1250 // operands which have lost a user to the worklist.
1251 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001252 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001253
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001254 // If the root changed (e.g. it was a dead load, update the root).
1255 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001256 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001257}
1258
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001259SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001260 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001261 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001262 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001263 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001264 case ISD::ADD: return visitADD(N);
1265 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001266 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001267 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001268 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001269 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001270 case ISD::MUL: return visitMUL(N);
1271 case ISD::SDIV: return visitSDIV(N);
1272 case ISD::UDIV: return visitUDIV(N);
1273 case ISD::SREM: return visitSREM(N);
1274 case ISD::UREM: return visitUREM(N);
1275 case ISD::MULHU: return visitMULHU(N);
1276 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001277 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1278 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001279 case ISD::SMULO: return visitSMULO(N);
1280 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001281 case ISD::SDIVREM: return visitSDIVREM(N);
1282 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001283 case ISD::AND: return visitAND(N);
1284 case ISD::OR: return visitOR(N);
1285 case ISD::XOR: return visitXOR(N);
1286 case ISD::SHL: return visitSHL(N);
1287 case ISD::SRA: return visitSRA(N);
1288 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001289 case ISD::ROTR:
1290 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001291 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001292 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001293 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001294 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001295 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001296 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001297 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001298 case ISD::SELECT_CC: return visitSELECT_CC(N);
1299 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001300 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1301 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001302 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001303 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1304 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001305 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001306 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001307 case ISD::FADD: return visitFADD(N);
1308 case ISD::FSUB: return visitFSUB(N);
1309 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001310 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001311 case ISD::FDIV: return visitFDIV(N);
1312 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001313 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001314 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1315 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1316 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1317 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1318 case ISD::FP_ROUND: return visitFP_ROUND(N);
1319 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1320 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1321 case ISD::FNEG: return visitFNEG(N);
1322 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001323 case ISD::FFLOOR: return visitFFLOOR(N);
1324 case ISD::FCEIL: return visitFCEIL(N);
1325 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001326 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001327 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001328 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001329 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001330 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001331 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001332 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1333 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001334 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001335 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001336 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001337 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001338 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001339}
1340
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001341SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001342 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001343
1344 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001345 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001346 assert(N->getOpcode() != ISD::DELETED_NODE &&
1347 "Node was deleted but visit returned NULL!");
1348
1349 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1350 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1351
1352 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001353 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001354 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001355
1356 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1357 }
1358 }
1359
Evan Chengf1005572010-04-28 07:10:39 +00001360 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001361 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001362 switch (N->getOpcode()) {
1363 default: break;
1364 case ISD::ADD:
1365 case ISD::SUB:
1366 case ISD::MUL:
1367 case ISD::AND:
1368 case ISD::OR:
1369 case ISD::XOR:
1370 RV = PromoteIntBinOp(SDValue(N, 0));
1371 break;
1372 case ISD::SHL:
1373 case ISD::SRA:
1374 case ISD::SRL:
1375 RV = PromoteIntShiftOp(SDValue(N, 0));
1376 break;
1377 case ISD::SIGN_EXTEND:
1378 case ISD::ZERO_EXTEND:
1379 case ISD::ANY_EXTEND:
1380 RV = PromoteExtend(SDValue(N, 0));
1381 break;
1382 case ISD::LOAD:
1383 if (PromoteLoad(SDValue(N, 0)))
1384 RV = SDValue(N, 0);
1385 break;
1386 }
1387 }
1388
Scott Michelcf0da6c2009-02-17 22:15:04 +00001389 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001390 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001391 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001392 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001393 SDValue N0 = N->getOperand(0);
1394 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001395
Evan Cheng31604a62008-03-22 01:55:50 +00001396 // Constant operands are canonicalized to RHS.
1397 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001398 SDValue Ops[] = {N1, N0};
1399 SDNode *CSENode;
1400 if (const BinaryWithFlagsSDNode *BinNode =
1401 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1402 CSENode = DAG.getNodeIfExists(
1403 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1404 BinNode->hasNoSignedWrap(), BinNode->isExact());
1405 } else {
1406 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1407 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001408 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001409 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001410 }
1411 }
1412
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001413 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001414}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001415
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001416/// Given a node, return its input chain if it has one, otherwise return a null
1417/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001418static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001419 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001420 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001421 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001422 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001423 return N->getOperand(NumOps-1);
1424 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001425 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001426 return N->getOperand(i);
1427 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001428 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001429}
1430
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001431SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001432 // If N has two operands, where one has an input chain equal to the other,
1433 // the 'other' chain is redundant.
1434 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001435 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001436 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001437 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001438 return N->getOperand(1);
1439 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001440
Chris Lattner48fb92f2007-05-16 06:37:59 +00001441 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001442 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001443 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001444 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001445
Jim Laskey708d0db2006-10-04 16:53:27 +00001446 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001447 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001448
Jim Laskey0463e082006-10-07 23:37:56 +00001449 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001450 // encountered.
1451 for (unsigned i = 0; i < TFs.size(); ++i) {
1452 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001453
Jim Laskey708d0db2006-10-04 16:53:27 +00001454 // Check each of the operands.
1455 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001456 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001457
Jim Laskey708d0db2006-10-04 16:53:27 +00001458 switch (Op.getOpcode()) {
1459 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001460 // Entry tokens don't need to be added to the list. They are
1461 // rededundant.
1462 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001463 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001464
Jim Laskey708d0db2006-10-04 16:53:27 +00001465 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001466 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001467 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001468 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001469 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001470 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001471 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001472 Changed = true;
1473 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001474 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001475 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001476
Jim Laskey708d0db2006-10-04 16:53:27 +00001477 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001478 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001479 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001480 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001481 else
1482 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001483 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001484 }
1485 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001486 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001487
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001488 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001489
1490 // If we've change things around then replace token factor.
1491 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001492 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001493 // The entry token is the only possible outcome.
1494 Result = DAG.getEntryNode();
1495 } else {
1496 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001497 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001498 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001499
Jim Laskeydcf983c2006-10-13 23:32:28 +00001500 // Don't add users to work list.
1501 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001502 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001503
Jim Laskey708d0db2006-10-04 16:53:27 +00001504 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001505}
1506
Chris Lattneree322b42008-02-13 07:25:05 +00001507/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001508SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001509 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001510 // Replacing results may cause a different MERGE_VALUES to suddenly
1511 // be CSE'd with N, and carry its uses with it. Iterate until no
1512 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001513 // First add the users of this node to the work list so that they
1514 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001515 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001516 do {
1517 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001518 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001519 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001520 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001521 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001522}
1523
Evan Cheng92011002007-01-19 17:51:44 +00001524static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001525SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001526 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001527 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001528 SDValue N00 = N0.getOperand(0);
1529 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001530 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001531
Gabor Greiff304a7a2008-08-28 21:40:38 +00001532 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001533 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001534 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001535 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1536 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001537 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001538 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001539 N00.getOperand(1), N01));
1540 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001541 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001543 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001544}
1545
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001546SDValue DAGCombiner::visitADD(SDNode *N) {
1547 SDValue N0 = N->getOperand(0);
1548 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001549 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1550 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001551 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001552
1553 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001554 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001555 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001556 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001557
1558 // fold (add x, 0) -> x, vector edition
1559 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1560 return N0;
1561 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1562 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001563 }
Bill Wendling0864a752008-12-10 22:36:00 +00001564
Dan Gohman06563a82007-07-03 14:03:57 +00001565 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001566 if (N0.getOpcode() == ISD::UNDEF)
1567 return N0;
1568 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001569 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001570 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001571 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001572 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001573 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001574 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001575 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001576 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001577 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001578 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001579 // fold (add Sym, c) -> Sym+c
1580 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001581 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001582 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001583 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001584 GA->getOffset() +
1585 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001586 // fold ((c1-A)+c2) -> (c1+c2)-A
1587 if (N1C && N0.getOpcode() == ISD::SUB)
1588 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001589 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001590 DAG.getConstant(N1C->getAPIntValue()+
1591 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001592 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001593 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001594 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001595 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001596 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001597 // fold ((0-A) + B) -> B-A
1598 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1599 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001600 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001601 // fold (A + (0-B)) -> A-B
1602 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1603 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001604 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001605 // fold (A+(B-A)) -> B
1606 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001607 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001608 // fold ((B-A)+A) -> B
1609 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1610 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001611 // fold (A+(B-(A+C))) to (B-C)
1612 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001613 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001614 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001615 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001616 // fold (A+(B-(C+A))) to (B-C)
1617 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001618 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001619 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001620 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001621 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001622 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1623 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001624 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001625 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001626 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001627
Dale Johannesen8c766702008-12-02 01:30:54 +00001628 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1629 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1630 SDValue N00 = N0.getOperand(0);
1631 SDValue N01 = N0.getOperand(1);
1632 SDValue N10 = N1.getOperand(0);
1633 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001634
1635 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001636 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1637 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1638 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001639 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001640
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001641 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1642 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001643
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001644 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001645 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001646 APInt LHSZero, LHSOne;
1647 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001648 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001649
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001650 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001651 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001652
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001653 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1654 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001655 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1656 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1657 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1658 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001659 }
1660 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001661
Evan Cheng92011002007-01-19 17:51:44 +00001662 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001663 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001664 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001665 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001666 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001667 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001668 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001669 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001670 }
1671
Dan Gohman954f4902010-01-19 23:30:49 +00001672 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1673 if (N1.getOpcode() == ISD::SHL &&
1674 N1.getOperand(0).getOpcode() == ISD::SUB)
1675 if (ConstantSDNode *C =
1676 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1677 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001678 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1679 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001680 N1.getOperand(0).getOperand(1),
1681 N1.getOperand(1)));
1682 if (N0.getOpcode() == ISD::SHL &&
1683 N0.getOperand(0).getOpcode() == ISD::SUB)
1684 if (ConstantSDNode *C =
1685 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1686 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001687 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1688 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001689 N0.getOperand(0).getOperand(1),
1690 N0.getOperand(1)));
1691
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001692 if (N1.getOpcode() == ISD::AND) {
1693 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001694 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001695 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1696 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001697
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001698 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1699 // and similar xforms where the inner op is either ~0 or 0.
1700 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001701 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001702 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1703 }
1704 }
1705
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001706 // add (sext i1), X -> sub X, (zext i1)
1707 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1708 N0.getOperand(0).getValueType() == MVT::i1 &&
1709 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001710 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001711 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1712 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1713 }
1714
Evan Chengf1005572010-04-28 07:10:39 +00001715 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001716}
1717
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001718SDValue DAGCombiner::visitADDC(SDNode *N) {
1719 SDValue N0 = N->getOperand(0);
1720 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001721 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001723 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001724
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001725 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001726 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001727 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001728 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001729 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001730
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001731 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001732 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001733 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001734
Chris Lattner47206662007-03-04 20:40:38 +00001735 // fold (addc x, 0) -> x + no carry out
1736 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001737 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001738 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001739
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001740 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001741 APInt LHSZero, LHSOne;
1742 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001743 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001744
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001745 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001746 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001747
Chris Lattner47206662007-03-04 20:40:38 +00001748 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1749 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001750 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001751 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001752 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001753 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001754 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001755
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001756 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001757}
1758
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001759SDValue DAGCombiner::visitADDE(SDNode *N) {
1760 SDValue N0 = N->getOperand(0);
1761 SDValue N1 = N->getOperand(1);
1762 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001765
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001766 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001767 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001768 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001769 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001770
Chris Lattner47206662007-03-04 20:40:38 +00001771 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001772 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001773 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001774
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001775 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001776}
1777
Eric Christophere5ca1e02011-02-16 04:50:12 +00001778// Since it may not be valid to emit a fold to zero for vector initializers
1779// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001780static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001781 SelectionDAG &DAG,
1782 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001783 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001784 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001785 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1786 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001787 return SDValue();
1788}
1789
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001790SDValue DAGCombiner::visitSUB(SDNode *N) {
1791 SDValue N0 = N->getOperand(0);
1792 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001793 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1794 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001795 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001796 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001797 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001798
Dan Gohmana8665142007-06-25 16:23:39 +00001799 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001800 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001801 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001802 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001803
1804 // fold (sub x, 0) -> x, vector edition
1805 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1806 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001807 }
Bill Wendling0864a752008-12-10 22:36:00 +00001808
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001809 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001810 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001811 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001812 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001813 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001814 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001815 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001816 // fold (sub x, c) -> (add x, -c)
1817 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001818 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001819 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001820 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1821 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001822 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001823 // fold A-(A-B) -> B
1824 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1825 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001826 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001827 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001828 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001829 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001830 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001831 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001832 // fold C2-(A+C1) -> (C2-C1)-A
1833 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001834 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1835 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001836 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001837 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001838 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001839 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001840 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001841 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1842 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001843 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001844 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001845 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001846 // fold ((A+(C+B))-B) -> A+C
1847 if (N0.getOpcode() == ISD::ADD &&
1848 N0.getOperand(1).getOpcode() == ISD::ADD &&
1849 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001850 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001851 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001852 // fold ((A-(B-C))-C) -> A-B
1853 if (N0.getOpcode() == ISD::SUB &&
1854 N0.getOperand(1).getOpcode() == ISD::SUB &&
1855 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001856 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001857 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001858
Dan Gohman06563a82007-07-03 14:03:57 +00001859 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001860 if (N0.getOpcode() == ISD::UNDEF)
1861 return N0;
1862 if (N1.getOpcode() == ISD::UNDEF)
1863 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001864
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001865 // If the relocation model supports it, consider symbol offsets.
1866 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001867 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001868 // fold (sub Sym, c) -> Sym-c
1869 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001870 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001871 GA->getOffset() -
1872 (uint64_t)N1C->getSExtValue());
1873 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1874 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1875 if (GA->getGlobal() == GB->getGlobal())
1876 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1877 VT);
1878 }
1879
Evan Chengf1005572010-04-28 07:10:39 +00001880 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001881}
1882
Craig Topper43a1bd62012-01-07 09:06:39 +00001883SDValue DAGCombiner::visitSUBC(SDNode *N) {
1884 SDValue N0 = N->getOperand(0);
1885 SDValue N1 = N->getOperand(1);
1886 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1887 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1888 EVT VT = N0.getValueType();
1889
1890 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001891 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001892 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1893 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001894 MVT::Glue));
1895
1896 // fold (subc x, x) -> 0 + no borrow
1897 if (N0 == N1)
1898 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001899 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001900 MVT::Glue));
1901
1902 // fold (subc x, 0) -> x + no borrow
1903 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001904 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001905 MVT::Glue));
1906
1907 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1908 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001909 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1910 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001911 MVT::Glue));
1912
1913 return SDValue();
1914}
1915
1916SDValue DAGCombiner::visitSUBE(SDNode *N) {
1917 SDValue N0 = N->getOperand(0);
1918 SDValue N1 = N->getOperand(1);
1919 SDValue CarryIn = N->getOperand(2);
1920
1921 // fold (sube x, y, false) -> (subc x, y)
1922 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001923 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001924
1925 return SDValue();
1926}
1927
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001928SDValue DAGCombiner::visitMUL(SDNode *N) {
1929 SDValue N0 = N->getOperand(0);
1930 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001931 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001932
Dan Gohman06563a82007-07-03 14:03:57 +00001933 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001934 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001935 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001936
1937 bool N0IsConst = false;
1938 bool N1IsConst = false;
1939 APInt ConstValue0, ConstValue1;
1940 // fold vector ops
1941 if (VT.isVector()) {
1942 SDValue FoldedVOp = SimplifyVBinOp(N);
1943 if (FoldedVOp.getNode()) return FoldedVOp;
1944
1945 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1946 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1947 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001948 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001949 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1950 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001951 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001952 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1953 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001954 }
1955
Nate Begeman21158fc2005-09-01 00:19:25 +00001956 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001957 if (N0IsConst && N1IsConst)
1958 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1959
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001960 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001961 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001962 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001963 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001964 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001965 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001966 // We require a splat of the entire scalar bit width for non-contiguous
1967 // bit patterns.
1968 bool IsFullSplat =
1969 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001970 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001971 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001972 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001973 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001974 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001975 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001976 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001977 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001978 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001979 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001980 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001981 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001982 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001983 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001984 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001985 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001986 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001987 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001988 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001989 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001990 DAG.getConstant(Log2Val,
1991 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001992 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001993
1994 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001995 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001996 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001997 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1998 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001999 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002000 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002001 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002002 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002003 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002004 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002005
Chris Lattner324871e2006-03-01 03:44:24 +00002006 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2007 // use.
2008 {
Craig Topperc0196b12014-04-14 00:51:57 +00002009 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002010 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002011 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002012 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2013 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002014 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002015 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002016 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002017 isa<ConstantSDNode>(N1.getOperand(1)) &&
2018 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002019 Sh = N1; Y = N0;
2020 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002021
Gabor Greiff304a7a2008-08-28 21:40:38 +00002022 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002023 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002024 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002025 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002026 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002027 }
2028 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002029
Chris Lattnerf29f5202006-03-04 23:33:26 +00002030 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002031 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2032 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2033 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002034 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2035 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002036 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002037 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002038 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002039
Nate Begeman22e251a2006-02-03 06:46:56 +00002040 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002041 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002042 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002043 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002044
Evan Chengf1005572010-04-28 07:10:39 +00002045 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002046}
2047
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002048SDValue DAGCombiner::visitSDIV(SDNode *N) {
2049 SDValue N0 = N->getOperand(0);
2050 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002051 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2052 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002053 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002054
Dan Gohmana8665142007-06-25 16:23:39 +00002055 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002056 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002057 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002058 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002059 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002060
Nate Begeman21158fc2005-09-01 00:19:25 +00002061 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002062 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002063 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002064 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002065 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002066 return N0;
2067 // fold (sdiv X, -1) -> 0-X
2068 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002069 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002070 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002071 // If we know the sign bits of both operands are zero, strength reduce to a
2072 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002073 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002074 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002075 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002076 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002077 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002078
Nate Begeman57b35672006-02-17 07:26:20 +00002079 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002080 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2081 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002082 // If dividing by powers of two is cheap, then don't perform the following
2083 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002084 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002085 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002086
Chad Rosier17020f92014-07-23 14:57:52 +00002087 // Target-specific implementation of sdiv x, pow2.
2088 SDValue Res = BuildSDIVPow2(N);
2089 if (Res.getNode())
2090 return Res;
2091
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002092 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002093
Chris Lattner471627c2006-02-16 08:02:36 +00002094 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002095 SDValue SGN =
2096 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2097 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2098 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002099 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002100
Chris Lattner471627c2006-02-16 08:02:36 +00002101 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002102 SDValue SRL =
2103 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2104 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2105 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002106 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002107 AddToWorklist(SRL.getNode());
2108 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002109 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002110 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002111
Nate Begeman4dd38312005-10-21 00:02:42 +00002112 // If we're dividing by a positive value, we're done. Otherwise, we must
2113 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002114 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002115 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002116
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002117 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002118 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002119 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002120
Nate Begemanc6f067a2005-10-20 02:15:44 +00002121 // if integer divide is expensive and we satisfy the requirements, emit an
2122 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002123 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002124 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002125 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002126 }
Dan Gohmana8665142007-06-25 16:23:39 +00002127
Dan Gohman06563a82007-07-03 14:03:57 +00002128 // undef / X -> 0
2129 if (N0.getOpcode() == ISD::UNDEF)
2130 return DAG.getConstant(0, VT);
2131 // X / undef -> undef
2132 if (N1.getOpcode() == ISD::UNDEF)
2133 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002134
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002135 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002136}
2137
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002138SDValue DAGCombiner::visitUDIV(SDNode *N) {
2139 SDValue N0 = N->getOperand(0);
2140 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002141 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2142 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002143 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002144
Dan Gohmana8665142007-06-25 16:23:39 +00002145 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002146 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002147 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002148 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002149 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002150
Nate Begeman21158fc2005-09-01 00:19:25 +00002151 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002152 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002153 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002154 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002155 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002156 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002157 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002158 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002159 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002160 if (N1.getOpcode() == ISD::SHL) {
2161 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002162 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002163 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002164 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002165 N1.getOperand(1),
2166 DAG.getConstant(SHC->getAPIntValue()
2167 .logBase2(),
2168 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002169 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002170 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002171 }
2172 }
2173 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002174 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002175 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002176 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002177 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002178 }
Dan Gohmana8665142007-06-25 16:23:39 +00002179
Dan Gohman06563a82007-07-03 14:03:57 +00002180 // undef / X -> 0
2181 if (N0.getOpcode() == ISD::UNDEF)
2182 return DAG.getConstant(0, VT);
2183 // X / undef -> undef
2184 if (N1.getOpcode() == ISD::UNDEF)
2185 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002186
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002187 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002188}
2189
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002190SDValue DAGCombiner::visitSREM(SDNode *N) {
2191 SDValue N0 = N->getOperand(0);
2192 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002193 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2194 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002195 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002196
Nate Begeman21158fc2005-09-01 00:19:25 +00002197 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002198 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002199 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002200 // If we know the sign bits of both operands are zero, strength reduce to a
2201 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002202 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002203 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002204 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002205 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002206
Dan Gohman9a693412007-11-26 23:46:11 +00002207 // If X/C can be simplified by the division-by-constant logic, lower
2208 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002209 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002210 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002211 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002212 SDValue OptimizedDiv = combine(Div.getNode());
2213 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002214 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002215 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002216 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002217 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002218 return Sub;
2219 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002220 }
Scott Michelcf0da6c2009-02-17 22:15:04 +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::visitUREM(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002235 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2236 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002237 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002238
Nate Begeman21158fc2005-09-01 00:19:25 +00002239 // fold (urem c1, c2) -> c1%c2
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::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002242 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002243 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002244 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002245 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002246 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2247 if (N1.getOpcode() == ISD::SHL) {
2248 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002249 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002250 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002251 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002252 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002253 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002254 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002255 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002256 }
2257 }
2258 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002259
Dan Gohman9a693412007-11-26 23:46:11 +00002260 // If X/C can be simplified by the division-by-constant logic, lower
2261 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002262 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002263 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002264 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002265 SDValue OptimizedDiv = combine(Div.getNode());
2266 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002267 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002268 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002269 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002270 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002271 return Sub;
2272 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002273 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002274
Dan Gohman06563a82007-07-03 14:03:57 +00002275 // undef % X -> 0
2276 if (N0.getOpcode() == ISD::UNDEF)
2277 return DAG.getConstant(0, VT);
2278 // X % undef -> undef
2279 if (N1.getOpcode() == ISD::UNDEF)
2280 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002281
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002282 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002283}
2284
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002285SDValue DAGCombiner::visitMULHS(SDNode *N) {
2286 SDValue N0 = N->getOperand(0);
2287 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002288 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002289 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002290 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002291
Nate Begeman21158fc2005-09-01 00:19:25 +00002292 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002293 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002294 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002295 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002296 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002297 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002298 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002299 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002300 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002301 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002302 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002303
Chris Lattner10bd29f2010-12-13 08:39:01 +00002304 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2305 // plus a shift.
2306 if (VT.isSimple() && !VT.isVector()) {
2307 MVT Simple = VT.getSimpleVT();
2308 unsigned SimpleSize = Simple.getSizeInBits();
2309 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2310 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2311 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2312 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2313 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002314 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002315 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002316 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2317 }
2318 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002320 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002321}
2322
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002323SDValue DAGCombiner::visitMULHU(SDNode *N) {
2324 SDValue N0 = N->getOperand(0);
2325 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002326 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002327 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002328 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002329
Nate Begeman21158fc2005-09-01 00:19:25 +00002330 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002331 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002332 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002333 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002334 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002335 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002336 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002337 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002338 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002339
Chris Lattner10bd29f2010-12-13 08:39:01 +00002340 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2341 // plus a shift.
2342 if (VT.isSimple() && !VT.isVector()) {
2343 MVT Simple = VT.getSimpleVT();
2344 unsigned SimpleSize = Simple.getSizeInBits();
2345 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2346 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2347 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2348 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2349 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2350 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002351 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002352 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2353 }
2354 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002355
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002356 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002357}
2358
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002359/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2360/// give the opcodes for the two computations that are being performed. Return
2361/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002362SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002363 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002364 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002365 bool HiExists = N->hasAnyUseOfValue(1);
2366 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002367 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002368 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002369 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002370 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002371 }
2372
2373 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002374 bool LoExists = N->hasAnyUseOfValue(0);
2375 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002376 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002377 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002378 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002379 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002380 }
2381
Evan Chengece4c682007-11-08 09:25:29 +00002382 // If both halves are used, return as it is.
2383 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002384 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002385
2386 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002387 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002388 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002389 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002390 SDValue LoOpt = combine(Lo.getNode());
2391 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002392 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002393 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002394 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002395 }
2396
Evan Chengece4c682007-11-08 09:25:29 +00002397 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002398 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002399 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002400 SDValue HiOpt = combine(Hi.getNode());
2401 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002402 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002403 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002404 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002405 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002406
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002407 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002408}
2409
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002410SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2411 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002412 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002413
Chris Lattner15090e12010-12-15 06:04:19 +00002414 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002415 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002416
2417 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2418 // plus a shift.
2419 if (VT.isSimple() && !VT.isVector()) {
2420 MVT Simple = VT.getSimpleVT();
2421 unsigned SimpleSize = Simple.getSizeInBits();
2422 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2423 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2424 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2425 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2426 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2427 // Compute the high part as N1.
2428 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002429 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002430 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2431 // Compute the low part as N0.
2432 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2433 return CombineTo(N, Lo, Hi);
2434 }
2435 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002436
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002437 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002438}
2439
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002440SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2441 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002442 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002443
Chris Lattner15090e12010-12-15 06:04:19 +00002444 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002445 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002446
Chris Lattner15090e12010-12-15 06:04:19 +00002447 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2448 // plus a shift.
2449 if (VT.isSimple() && !VT.isVector()) {
2450 MVT Simple = VT.getSimpleVT();
2451 unsigned SimpleSize = Simple.getSizeInBits();
2452 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2453 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2454 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2455 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2456 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2457 // Compute the high part as N1.
2458 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002459 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002460 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2461 // Compute the low part as N0.
2462 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2463 return CombineTo(N, Lo, Hi);
2464 }
2465 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002466
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002467 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002468}
2469
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002470SDValue DAGCombiner::visitSMULO(SDNode *N) {
2471 // (smulo x, 2) -> (saddo x, x)
2472 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2473 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002474 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002475 N->getOperand(0), N->getOperand(0));
2476
2477 return SDValue();
2478}
2479
2480SDValue DAGCombiner::visitUMULO(SDNode *N) {
2481 // (umulo x, 2) -> (uaddo x, x)
2482 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2483 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002484 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002485 N->getOperand(0), N->getOperand(0));
2486
2487 return SDValue();
2488}
2489
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002490SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2491 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002492 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002493
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002494 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002495}
2496
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002497SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2498 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002499 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002500
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002501 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002502}
2503
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002504/// If this is a binary operator with two operands of the same opcode, try to
2505/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002506SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2507 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002508 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002509 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002510
Dan Gohmandd5286d2010-01-14 03:08:49 +00002511 // Bail early if none of these transforms apply.
2512 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2513
Chris Lattner002ee912006-05-05 06:31:05 +00002514 // For each of OP in AND/OR/XOR:
2515 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2516 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2517 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002518 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002519 //
2520 // do not sink logical op inside of a vector extend, since it may combine
2521 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002522 EVT Op0VT = N0.getOperand(0).getValueType();
2523 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002524 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002525 // Avoid infinite looping with PromoteIntBinOp.
2526 (N0.getOpcode() == ISD::ANY_EXTEND &&
2527 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002528 (N0.getOpcode() == ISD::TRUNCATE &&
2529 (!TLI.isZExtFree(VT, Op0VT) ||
2530 !TLI.isTruncateFree(Op0VT, VT)) &&
2531 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002532 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002533 Op0VT == N1.getOperand(0).getValueType() &&
2534 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002535 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002536 N0.getOperand(0).getValueType(),
2537 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002538 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002539 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002540 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002541
Chris Lattner5ac42932006-05-05 06:10:43 +00002542 // For each of OP in SHL/SRL/SRA/AND...
2543 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2544 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2545 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002546 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002547 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002548 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002549 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002550 N0.getOperand(0).getValueType(),
2551 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002552 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002553 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002554 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002555 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002556
Nadav Rotemb0783502012-04-01 19:31:22 +00002557 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2558 // Only perform this optimization after type legalization and before
2559 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2560 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2561 // we don't want to undo this promotion.
2562 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2563 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002564 if ((N0.getOpcode() == ISD::BITCAST ||
2565 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2566 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002567 SDValue In0 = N0.getOperand(0);
2568 SDValue In1 = N1.getOperand(0);
2569 EVT In0Ty = In0.getValueType();
2570 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002571 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002572 // If both incoming values are integers, and the original types are the
2573 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002574 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002575 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2576 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002577 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002578 return BC;
2579 }
2580 }
2581
2582 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2583 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2584 // If both shuffles use the same mask, and both shuffle within a single
2585 // vector, then it is worthwhile to move the swizzle after the operation.
2586 // The type-legalizer generates this pattern when loading illegal
2587 // vector types from memory. In many cases this allows additional shuffle
2588 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002589 // There are other cases where moving the shuffle after the xor/and/or
2590 // is profitable even if shuffles don't perform a swizzle.
2591 // If both shuffles use the same mask, and both shuffles have the same first
2592 // or second operand, then it might still be profitable to move the shuffle
2593 // after the xor/and/or operation.
2594 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002595 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2596 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002597
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002598 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002599 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002600
Nadav Rotemb0783502012-04-01 19:31:22 +00002601 // Check that both shuffles use the same mask. The masks are known to be of
2602 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002603 // Check also that shuffles have only one use to avoid introducing extra
2604 // instructions.
2605 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2606 SVN0->getMask().equals(SVN1->getMask())) {
2607 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002608
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002609 // Don't try to fold this node if it requires introducing a
2610 // build vector of all zeros that might be illegal at this stage.
2611 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2612 if (!LegalTypes)
2613 ShOp = DAG.getConstant(0, VT);
2614 else
2615 ShOp = SDValue();
2616 }
2617
2618 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2619 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2620 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2621 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2622 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2623 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002624 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002625 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2626 &SVN0->getMask()[0]);
2627 }
2628
2629 // Don't try to fold this node if it requires introducing a
2630 // build vector of all zeros that might be illegal at this stage.
2631 ShOp = N0->getOperand(0);
2632 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2633 if (!LegalTypes)
2634 ShOp = DAG.getConstant(0, VT);
2635 else
2636 ShOp = SDValue();
2637 }
2638
2639 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2640 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2641 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2642 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2643 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2644 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002645 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002646 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2647 &SVN0->getMask()[0]);
2648 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002649 }
2650 }
Craig Topper9c3da312012-04-09 07:19:09 +00002651
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002652 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002653}
2654
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002655SDValue DAGCombiner::visitAND(SDNode *N) {
2656 SDValue N0 = N->getOperand(0);
2657 SDValue N1 = N->getOperand(1);
2658 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002659 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2660 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002661 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002662 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002663
Dan Gohmana8665142007-06-25 16:23:39 +00002664 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002665 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002666 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002667 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002668
2669 // fold (and x, 0) -> 0, vector edition
2670 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2671 return N0;
2672 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2673 return N1;
2674
2675 // fold (and x, -1) -> x, vector edition
2676 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2677 return N1;
2678 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2679 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002680 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002681
Dan Gohman06563a82007-07-03 14:03:57 +00002682 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002683 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002684 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002685 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002686 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002687 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002688 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002689 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002690 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002691 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002692 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002693 return N0;
2694 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002695 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002696 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002697 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002698 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002699 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002700 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002701 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002702 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002703 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002704 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002705 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002706 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002707 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2708 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002709 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002710 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002711 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002712 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002713 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002714 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002715
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002716 // Replace uses of the AND with uses of the Zero extend node.
2717 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002718
Chris Lattner49beaf42006-02-02 07:17:31 +00002719 // We actually want to replace all uses of the any_extend with the
2720 // zero_extend, to avoid duplicating things. This will later cause this
2721 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002722 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002723 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002724 }
2725 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002726 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002727 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2728 // already be zero by virtue of the width of the base type of the load.
2729 //
2730 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2731 // more cases.
2732 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2733 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2734 N0.getOpcode() == ISD::LOAD) {
2735 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2736 N0 : N0.getOperand(0) );
2737
2738 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2739 // This can be a pure constant or a vector splat, in which case we treat the
2740 // vector as a scalar and use the splat value.
2741 APInt Constant = APInt::getNullValue(1);
2742 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2743 Constant = C->getAPIntValue();
2744 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2745 APInt SplatValue, SplatUndef;
2746 unsigned SplatBitSize;
2747 bool HasAnyUndefs;
2748 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2749 SplatBitSize, HasAnyUndefs);
2750 if (IsSplat) {
2751 // Undef bits can contribute to a possible optimisation if set, so
2752 // set them.
2753 SplatValue |= SplatUndef;
2754
2755 // The splat value may be something like "0x00FFFFFF", which means 0 for
2756 // the first vector value and FF for the rest, repeating. We need a mask
2757 // that will apply equally to all members of the vector, so AND all the
2758 // lanes of the constant together.
2759 EVT VT = Vector->getValueType(0);
2760 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002761
2762 // If the splat value has been compressed to a bitlength lower
2763 // than the size of the vector lane, we need to re-expand it to
2764 // the lane size.
2765 if (BitWidth > SplatBitSize)
2766 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2767 SplatBitSize < BitWidth;
2768 SplatBitSize = SplatBitSize * 2)
2769 SplatValue |= SplatValue.shl(SplatBitSize);
2770
James Molloy862fe492012-02-20 12:02:38 +00002771 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002772 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002773 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2774 }
2775 }
2776
2777 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2778 // actually legal and isn't going to get expanded, else this is a false
2779 // optimisation.
2780 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2781 Load->getMemoryVT());
2782
2783 // Resize the constant to the same size as the original memory access before
2784 // extension. If it is still the AllOnesValue then this AND is completely
2785 // unneeded.
2786 Constant =
2787 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2788
2789 bool B;
2790 switch (Load->getExtensionType()) {
2791 default: B = false; break;
2792 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2793 case ISD::ZEXTLOAD:
2794 case ISD::NON_EXTLOAD: B = true; break;
2795 }
2796
2797 if (B && Constant.isAllOnesValue()) {
2798 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2799 // preserve semantics once we get rid of the AND.
2800 SDValue NewLoad(Load, 0);
2801 if (Load->getExtensionType() == ISD::EXTLOAD) {
2802 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002803 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002804 Load->getChain(), Load->getBasePtr(),
2805 Load->getOffset(), Load->getMemoryVT(),
2806 Load->getMemOperand());
2807 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002808 if (Load->getNumValues() == 3) {
2809 // PRE/POST_INC loads have 3 values.
2810 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2811 NewLoad.getValue(2) };
2812 CombineTo(Load, To, 3, true);
2813 } else {
2814 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2815 }
James Molloy862fe492012-02-20 12:02:38 +00002816 }
2817
2818 // Fold the AND away, taking care not to fold to the old load node if we
2819 // replaced it.
2820 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2821
2822 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2823 }
2824 }
Nate Begeman049b7482005-09-09 19:49:52 +00002825 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2826 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2827 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2828 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002829
Tom Stellard7783b0a2014-06-12 16:04:47 +00002830 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002831 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002832 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002833 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002834 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002835 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002836 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002837 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002838 }
Bill Wendling86171912009-01-30 20:43:18 +00002839 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002840 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002841 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002842 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002843 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002844 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002845 }
Bill Wendling86171912009-01-30 20:43:18 +00002846 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002847 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002848 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002849 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002850 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002851 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002852 }
2853 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002854 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2855 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2856 Op0 == Op1 && LL.getValueType().isInteger() &&
2857 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2858 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2859 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2860 cast<ConstantSDNode>(RR)->isNullValue()))) {
2861 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2862 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002863 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002864 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2865 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2866 }
Nate Begeman049b7482005-09-09 19:49:52 +00002867 // canonicalize equivalent to ll == rl
2868 if (LL == RR && LR == RL) {
2869 Op1 = ISD::getSetCCSwappedOperands(Op1);
2870 std::swap(RL, RR);
2871 }
2872 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002873 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002874 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002875 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002876 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002877 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2878 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002879 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002880 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002881 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002882 }
2883 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002884
Bill Wendling86171912009-01-30 20:43:18 +00002885 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002886 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002887 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002888 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002889 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002890
Nate Begemandc7bba92006-02-03 22:24:05 +00002891 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2892 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002893 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002894 SimplifyDemandedBits(SDValue(N, 0)))
2895 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002896
Nate Begeman02b23c62005-10-13 03:11:28 +00002897 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002898 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002899 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002900 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002901 // If we zero all the possible extended bits, then we can turn this into
2902 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002903 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002904 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002905 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002906 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002907 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002908 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002909 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002910 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002911 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002912 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002914 }
2915 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002916 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002917 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002918 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002919 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002920 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002921 // If we zero all the possible extended bits, then we can turn this into
2922 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002923 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002924 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002925 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002926 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002927 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002928 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002929 LN0->getChain(), LN0->getBasePtr(),
2930 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002931 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002932 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002933 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002934 }
2935 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002936
Chris Lattnerf0032b32006-02-28 06:49:37 +00002937 // fold (and (load x), 255) -> (zextload x, i8)
2938 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002939 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2940 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2941 (N0.getOpcode() == ISD::ANY_EXTEND &&
2942 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2943 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2944 LoadSDNode *LN0 = HasAnyExt
2945 ? cast<LoadSDNode>(N0.getOperand(0))
2946 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002947 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002948 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002949 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002950 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2951 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2952 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002953
Evan Cheng166a4e62010-01-06 19:38:29 +00002954 if (ExtVT == LoadedVT &&
2955 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002956 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002957
2958 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002959 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002960 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2961 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002962 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002963 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2964 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2965 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002966
Chris Lattner88de3842010-01-07 21:53:27 +00002967 // Do not change the width of a volatile load.
2968 // Do not generate loads of non-round integer types since these can
2969 // be expensive (and would be wrong if the type is not byte sized).
2970 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2971 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2972 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002973
Chris Lattner88de3842010-01-07 21:53:27 +00002974 unsigned Alignment = LN0->getAlignment();
2975 SDValue NewPtr = LN0->getBasePtr();
2976
2977 // For big endian targets, we need to add an offset to the pointer
2978 // to load the correct bytes. For little endian systems, we merely
2979 // need to read fewer bytes from the same pointer.
2980 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002981 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2982 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2983 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002984 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002985 NewPtr, DAG.getConstant(PtrOff, PtrType));
2986 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002987 }
Chris Lattner88de3842010-01-07 21:53:27 +00002988
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002989 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002990
Chris Lattner88de3842010-01-07 21:53:27 +00002991 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2992 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002993 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002994 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002995 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002996 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00002997 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002998 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002999 CombineTo(LN0, Load, Load.getValue(1));
3000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003001 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003002 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003003 }
3004 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003005
Evan Chenge6a3b032012-07-17 18:54:11 +00003006 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3007 VT.getSizeInBits() <= 64) {
3008 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3009 APInt ADDC = ADDI->getAPIntValue();
3010 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3011 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3012 // immediate for an add, but it is legal if its top c2 bits are set,
3013 // transform the ADD so the immediate doesn't need to be materialized
3014 // in a register.
3015 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3016 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3017 SRLI->getZExtValue());
3018 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3019 ADDC |= Mask;
3020 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3021 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003022 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00003023 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3024 CombineTo(N0.getNode(), NewAdd);
3025 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3026 }
3027 }
3028 }
3029 }
3030 }
3031 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003032
Tim Northover819bfb52013-08-27 13:46:45 +00003033 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3034 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3035 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3036 N0.getOperand(1), false);
3037 if (BSwap.getNode())
3038 return BSwap;
3039 }
3040
Evan Chengf1005572010-04-28 07:10:39 +00003041 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003042}
3043
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003044/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003045SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3046 bool DemandHighBits) {
3047 if (!LegalOperations)
3048 return SDValue();
3049
3050 EVT VT = N->getValueType(0);
3051 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3052 return SDValue();
3053 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3054 return SDValue();
3055
3056 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3057 bool LookPassAnd0 = false;
3058 bool LookPassAnd1 = false;
3059 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3060 std::swap(N0, N1);
3061 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3062 std::swap(N0, N1);
3063 if (N0.getOpcode() == ISD::AND) {
3064 if (!N0.getNode()->hasOneUse())
3065 return SDValue();
3066 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3067 if (!N01C || N01C->getZExtValue() != 0xFF00)
3068 return SDValue();
3069 N0 = N0.getOperand(0);
3070 LookPassAnd0 = true;
3071 }
3072
3073 if (N1.getOpcode() == ISD::AND) {
3074 if (!N1.getNode()->hasOneUse())
3075 return SDValue();
3076 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3077 if (!N11C || N11C->getZExtValue() != 0xFF)
3078 return SDValue();
3079 N1 = N1.getOperand(0);
3080 LookPassAnd1 = true;
3081 }
3082
3083 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3084 std::swap(N0, N1);
3085 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3086 return SDValue();
3087 if (!N0.getNode()->hasOneUse() ||
3088 !N1.getNode()->hasOneUse())
3089 return SDValue();
3090
3091 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3092 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3093 if (!N01C || !N11C)
3094 return SDValue();
3095 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3096 return SDValue();
3097
3098 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3099 SDValue N00 = N0->getOperand(0);
3100 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3101 if (!N00.getNode()->hasOneUse())
3102 return SDValue();
3103 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3104 if (!N001C || N001C->getZExtValue() != 0xFF)
3105 return SDValue();
3106 N00 = N00.getOperand(0);
3107 LookPassAnd0 = true;
3108 }
3109
3110 SDValue N10 = N1->getOperand(0);
3111 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3112 if (!N10.getNode()->hasOneUse())
3113 return SDValue();
3114 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3115 if (!N101C || N101C->getZExtValue() != 0xFF00)
3116 return SDValue();
3117 N10 = N10.getOperand(0);
3118 LookPassAnd1 = true;
3119 }
3120
3121 if (N00 != N10)
3122 return SDValue();
3123
Tim Northover819bfb52013-08-27 13:46:45 +00003124 // Make sure everything beyond the low halfword gets set to zero since the SRL
3125 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003126 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003127 if (DemandHighBits && OpSizeInBits > 16) {
3128 // If the left-shift isn't masked out then the only way this is a bswap is
3129 // if all bits beyond the low 8 are 0. In that case the entire pattern
3130 // reduces to a left shift anyway: leave it for other parts of the combiner.
3131 if (!LookPassAnd0)
3132 return SDValue();
3133
3134 // However, if the right shift isn't masked out then it might be because
3135 // it's not needed. See if we can spot that too.
3136 if (!LookPassAnd1 &&
3137 !DAG.MaskedValueIsZero(
3138 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3139 return SDValue();
3140 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003141
Andrew Trickef9de2a2013-05-25 02:42:55 +00003142 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003143 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003144 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003145 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3146 return Res;
3147}
3148
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003149/// Return true if the specified node is an element that makes up a 32-bit
3150/// packed halfword byteswap.
3151/// ((x & 0x000000ff) << 8) |
3152/// ((x & 0x0000ff00) >> 8) |
3153/// ((x & 0x00ff0000) << 8) |
3154/// ((x & 0xff000000) >> 8)
Craig Topperb94011f2013-07-14 04:42:23 +00003155static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003156 if (!N.getNode()->hasOneUse())
3157 return false;
3158
3159 unsigned Opc = N.getOpcode();
3160 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3161 return false;
3162
3163 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3164 if (!N1C)
3165 return false;
3166
3167 unsigned Num;
3168 switch (N1C->getZExtValue()) {
3169 default:
3170 return false;
3171 case 0xFF: Num = 0; break;
3172 case 0xFF00: Num = 1; break;
3173 case 0xFF0000: Num = 2; break;
3174 case 0xFF000000: Num = 3; break;
3175 }
3176
3177 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3178 SDValue N0 = N.getOperand(0);
3179 if (Opc == ISD::AND) {
3180 if (Num == 0 || Num == 2) {
3181 // (x >> 8) & 0xff
3182 // (x >> 8) & 0xff0000
3183 if (N0.getOpcode() != ISD::SRL)
3184 return false;
3185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3186 if (!C || C->getZExtValue() != 8)
3187 return false;
3188 } else {
3189 // (x << 8) & 0xff00
3190 // (x << 8) & 0xff000000
3191 if (N0.getOpcode() != ISD::SHL)
3192 return false;
3193 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3194 if (!C || C->getZExtValue() != 8)
3195 return false;
3196 }
3197 } else if (Opc == ISD::SHL) {
3198 // (x & 0xff) << 8
3199 // (x & 0xff0000) << 8
3200 if (Num != 0 && Num != 2)
3201 return false;
3202 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3203 if (!C || C->getZExtValue() != 8)
3204 return false;
3205 } else { // Opc == ISD::SRL
3206 // (x & 0xff00) >> 8
3207 // (x & 0xff000000) >> 8
3208 if (Num != 1 && Num != 3)
3209 return false;
3210 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3211 if (!C || C->getZExtValue() != 8)
3212 return false;
3213 }
3214
3215 if (Parts[Num])
3216 return false;
3217
3218 Parts[Num] = N0.getOperand(0).getNode();
3219 return true;
3220}
3221
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003222/// Match a 32-bit packed halfword bswap. That is
3223/// ((x & 0x000000ff) << 8) |
3224/// ((x & 0x0000ff00) >> 8) |
3225/// ((x & 0x00ff0000) << 8) |
3226/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003227/// => (rotl (bswap x), 16)
3228SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3229 if (!LegalOperations)
3230 return SDValue();
3231
3232 EVT VT = N->getValueType(0);
3233 if (VT != MVT::i32)
3234 return SDValue();
3235 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3236 return SDValue();
3237
Craig Topperc0196b12014-04-14 00:51:57 +00003238 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003239 // Look for either
3240 // (or (or (and), (and)), (or (and), (and)))
3241 // (or (or (or (and), (and)), (and)), (and))
3242 if (N0.getOpcode() != ISD::OR)
3243 return SDValue();
3244 SDValue N00 = N0.getOperand(0);
3245 SDValue N01 = N0.getOperand(1);
3246
Evan Chengbf0baa92012-12-13 01:34:32 +00003247 if (N1.getOpcode() == ISD::OR &&
3248 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003249 // (or (or (and), (and)), (or (and), (and)))
3250 SDValue N000 = N00.getOperand(0);
3251 if (!isBSwapHWordElement(N000, Parts))
3252 return SDValue();
3253
3254 SDValue N001 = N00.getOperand(1);
3255 if (!isBSwapHWordElement(N001, Parts))
3256 return SDValue();
3257 SDValue N010 = N01.getOperand(0);
3258 if (!isBSwapHWordElement(N010, Parts))
3259 return SDValue();
3260 SDValue N011 = N01.getOperand(1);
3261 if (!isBSwapHWordElement(N011, Parts))
3262 return SDValue();
3263 } else {
3264 // (or (or (or (and), (and)), (and)), (and))
3265 if (!isBSwapHWordElement(N1, Parts))
3266 return SDValue();
3267 if (!isBSwapHWordElement(N01, Parts))
3268 return SDValue();
3269 if (N00.getOpcode() != ISD::OR)
3270 return SDValue();
3271 SDValue N000 = N00.getOperand(0);
3272 if (!isBSwapHWordElement(N000, Parts))
3273 return SDValue();
3274 SDValue N001 = N00.getOperand(1);
3275 if (!isBSwapHWordElement(N001, Parts))
3276 return SDValue();
3277 }
3278
3279 // Make sure the parts are all coming from the same node.
3280 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3281 return SDValue();
3282
Andrew Trickef9de2a2013-05-25 02:42:55 +00003283 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003284 SDValue(Parts[0],0));
3285
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003286 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003287 // do (x << 16) | (x >> 16).
3288 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3289 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003290 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003291 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003292 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3293 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3294 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3295 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003296}
3297
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003298SDValue DAGCombiner::visitOR(SDNode *N) {
3299 SDValue N0 = N->getOperand(0);
3300 SDValue N1 = N->getOperand(1);
3301 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003302 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3303 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003304 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003305
Dan Gohmana8665142007-06-25 16:23:39 +00003306 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003307 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003308 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003309 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003310
3311 // fold (or x, 0) -> x, vector edition
3312 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3313 return N1;
3314 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3315 return N0;
3316
3317 // fold (or x, -1) -> -1, vector edition
3318 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3319 return N0;
3320 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3321 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003322
3323 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3324 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3325 // Do this only if the resulting shuffle is legal.
3326 if (isa<ShuffleVectorSDNode>(N0) &&
3327 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003328 // Avoid folding a node with illegal type.
3329 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003330 N0->getOperand(1) == N1->getOperand(1) &&
3331 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3332 bool CanFold = true;
3333 unsigned NumElts = VT.getVectorNumElements();
3334 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3335 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3336 // We construct two shuffle masks:
3337 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3338 // and N1 as the second operand.
3339 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3340 // and N0 as the second operand.
3341 // We do this because OR is commutable and therefore there might be
3342 // two ways to fold this node into a shuffle.
3343 SmallVector<int,4> Mask1;
3344 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003345
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003346 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3347 int M0 = SV0->getMaskElt(i);
3348 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003349
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003350 // Both shuffle indexes are undef. Propagate Undef.
3351 if (M0 < 0 && M1 < 0) {
3352 Mask1.push_back(M0);
3353 Mask2.push_back(M0);
3354 continue;
3355 }
3356
3357 if (M0 < 0 || M1 < 0 ||
3358 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3359 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3360 CanFold = false;
3361 break;
3362 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003363
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003364 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3365 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3366 }
3367
3368 if (CanFold) {
3369 // Fold this sequence only if the resulting shuffle is 'legal'.
3370 if (TLI.isShuffleMaskLegal(Mask1, VT))
3371 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3372 N1->getOperand(0), &Mask1[0]);
3373 if (TLI.isShuffleMaskLegal(Mask2, VT))
3374 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3375 N0->getOperand(0), &Mask2[0]);
3376 }
3377 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003378 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003379
Dan Gohman06563a82007-07-03 14:03:57 +00003380 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003381 if (!LegalOperations &&
3382 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003383 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3384 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3385 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003386 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003387 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003388 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003389 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003390 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003391 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003392 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003393 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003394 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003395 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003396 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003397 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003398 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003399 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003400 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003401
3402 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3403 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003404 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003405 return BSwap;
3406 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003407 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003408 return BSwap;
3409
Nate Begeman22e251a2006-02-03 06:46:56 +00003410 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003411 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003412 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003413 return ROR;
3414 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003415 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003416 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003417 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003418 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003419 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3420 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3421 if (!COR.getNode())
3422 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003423 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3424 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003425 N0.getOperand(0), N1), COR);
3426 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003427 }
Nate Begeman049b7482005-09-09 19:49:52 +00003428 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3429 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3430 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3431 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003432
Nate Begeman049b7482005-09-09 19:49:52 +00003433 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003434 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003435 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3436 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003437 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003438 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003439 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003440 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003441 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003442 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003443 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003444 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3445 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003446 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003447 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003448 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003449 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003450 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003451 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003452 }
3453 }
3454 // canonicalize equivalent to ll == rl
3455 if (LL == RR && LR == RL) {
3456 Op1 = ISD::getSetCCSwappedOperands(Op1);
3457 std::swap(RL, RR);
3458 }
3459 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003460 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003461 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003462 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003463 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003464 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3465 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003466 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003467 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003468 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003469 }
3470 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003471
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003472 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003473 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003474 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003475 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003476 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003477
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003478 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003479 if (N0.getOpcode() == ISD::AND &&
3480 N1.getOpcode() == ISD::AND &&
3481 N0.getOperand(1).getOpcode() == ISD::Constant &&
3482 N1.getOperand(1).getOpcode() == ISD::Constant &&
3483 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003484 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003485 // We can only do this xform if we know that bits from X that are set in C2
3486 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003487 const APInt &LHSMask =
3488 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3489 const APInt &RHSMask =
3490 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003491
Dan Gohman309d3d52007-06-22 14:59:07 +00003492 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3493 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003494 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003495 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003496 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003497 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003498 }
3499 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003500
Chris Lattner97614c82006-09-14 20:50:57 +00003501 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003502 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003503 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003504
Dan Gohman600f62b2010-06-24 14:30:44 +00003505 // Simplify the operands using demanded-bits information.
3506 if (!VT.isVector() &&
3507 SimplifyDemandedBits(SDValue(N, 0)))
3508 return SDValue(N, 0);
3509
Evan Chengf1005572010-04-28 07:10:39 +00003510 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003511}
3512
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003513/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003514static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003515 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003516 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003517 Mask = Op.getOperand(1);
3518 Op = Op.getOperand(0);
3519 } else {
3520 return false;
3521 }
3522 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003523
Chris Lattner97614c82006-09-14 20:50:57 +00003524 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3525 Shift = Op;
3526 return true;
3527 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003528
Scott Michelcf0da6c2009-02-17 22:15:04 +00003529 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003530}
3531
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003532// Return true if we can prove that, whenever Neg and Pos are both in the
3533// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003534// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3535//
3536// (or (shift1 X, Neg), (shift2 X, Pos))
3537//
Adam Nemetc6553a82014-03-07 23:56:24 +00003538// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3539// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3540// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003541static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003542 // If OpSize is a power of 2 then:
3543 //
3544 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3545 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3546 //
3547 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3548 // for the stronger condition:
3549 //
3550 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3551 //
3552 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3553 // we can just replace Neg with Neg' for the rest of the function.
3554 //
3555 // In other cases we check for the even stronger condition:
3556 //
3557 // Neg == OpSize - Pos [B]
3558 //
3559 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3560 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003561 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003562 // We could actually use [A] whenever OpSize is a power of 2, but the
3563 // only extra cases that it would match are those uninteresting ones
3564 // where Neg and Pos are never in range at the same time. E.g. for
3565 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3566 // as well as (sub 32, Pos), but:
3567 //
3568 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3569 //
3570 // always invokes undefined behavior for 32-bit X.
3571 //
3572 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003573 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003574 if (Neg.getOpcode() == ISD::AND &&
3575 isPowerOf2_64(OpSize) &&
3576 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3577 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3578 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003579 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003580 }
3581
Richard Sandiford0f264db2014-01-09 10:49:40 +00003582 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3583 if (Neg.getOpcode() != ISD::SUB)
3584 return 0;
3585 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3586 if (!NegC)
3587 return 0;
3588 SDValue NegOp1 = Neg.getOperand(1);
3589
Adam Nemet5117f5d2014-03-07 23:56:28 +00003590 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3591 // Pos'. The truncation is redundant for the purpose of the equality.
3592 if (MaskLoBits &&
3593 Pos.getOpcode() == ISD::AND &&
3594 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3595 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3596 Pos = Pos.getOperand(0);
3597
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003598 // The condition we need is now:
3599 //
3600 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3601 //
3602 // If NegOp1 == Pos then we need:
3603 //
3604 // OpSize & Mask == NegC & Mask
3605 //
3606 // (because "x & Mask" is a truncation and distributes through subtraction).
3607 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003608 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003609 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003610 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3611 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003612 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003613 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3614 //
3615 // which, again because "x & Mask" is a truncation, becomes:
3616 //
3617 // NegC & Mask == (OpSize - PosC) & Mask
3618 // OpSize & Mask == (NegC + PosC) & Mask
3619 else if (Pos.getOpcode() == ISD::ADD &&
3620 Pos.getOperand(0) == NegOp1 &&
3621 Pos.getOperand(1).getOpcode() == ISD::Constant)
3622 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3623 NegC->getAPIntValue());
3624 else
3625 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003626
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003627 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003628 if (MaskLoBits)
3629 // Opsize & Mask is 0 since Mask is Opsize - 1.
3630 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003631 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003632}
3633
Richard Sandiford95c864d2014-01-08 15:40:47 +00003634// A subroutine of MatchRotate used once we have found an OR of two opposite
3635// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3636// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3637// former being preferred if supported. InnerPos and InnerNeg are Pos and
3638// Neg with outer conversions stripped away.
3639SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3640 SDValue Neg, SDValue InnerPos,
3641 SDValue InnerNeg, unsigned PosOpcode,
3642 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003643 // fold (or (shl x, (*ext y)),
3644 // (srl x, (*ext (sub 32, y)))) ->
3645 // (rotl x, y) or (rotr x, (sub 32, y))
3646 //
3647 // fold (or (shl x, (*ext (sub 32, y))),
3648 // (srl x, (*ext y))) ->
3649 // (rotr x, y) or (rotl x, (sub 32, y))
3650 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003651 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003652 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3653 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3654 HasPos ? Pos : Neg).getNode();
3655 }
3656
Craig Topperc0196b12014-04-14 00:51:57 +00003657 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003658}
3659
Chris Lattner97614c82006-09-14 20:50:57 +00003660// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3661// idioms for rotate, and if the target supports rotation instructions, generate
3662// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003663SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003664 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003665 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003666 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003667
3668 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003669 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3670 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003671 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003672
Chris Lattner97614c82006-09-14 20:50:57 +00003673 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003674 SDValue LHSShift; // The shift.
3675 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003676 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003677 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003678
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003679 SDValue RHSShift; // The shift.
3680 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003681 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003682 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003683
Chris Lattner97614c82006-09-14 20:50:57 +00003684 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003685 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003686
3687 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003688 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003689
Chris Lattner97614c82006-09-14 20:50:57 +00003690 // Canonicalize shl to left side in a shl/srl pair.
3691 if (RHSShift.getOpcode() == ISD::SHL) {
3692 std::swap(LHS, RHS);
3693 std::swap(LHSShift, RHSShift);
3694 std::swap(LHSMask , RHSMask );
3695 }
3696
Duncan Sands13237ac2008-06-06 12:08:01 +00003697 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003698 SDValue LHSShiftArg = LHSShift.getOperand(0);
3699 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003700 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003701 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003702
3703 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3704 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003705 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3706 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003707 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3708 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003709 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003710 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003711
Craig Topper65161fa2012-09-29 06:54:22 +00003712 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3713 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003714
Chris Lattner97614c82006-09-14 20:50:57 +00003715 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003716 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003717 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003718
Gabor Greiff304a7a2008-08-28 21:40:38 +00003719 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003720 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3721 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003722 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003723 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003724 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3725 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003726 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003727
Bill Wendling35972a92009-01-30 21:14:50 +00003728 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003729 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003730
Gabor Greiff304a7a2008-08-28 21:40:38 +00003731 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003732 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003733
Chris Lattner97614c82006-09-14 20:50:57 +00003734 // If there is a mask here, and we have a variable shift, we can't be sure
3735 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003736 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003737 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003738
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003739 // If the shift amount is sign/zext/any-extended just peel it off.
3740 SDValue LExtOp0 = LHSShiftAmt;
3741 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003742 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3743 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3744 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3745 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3746 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3747 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3748 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3749 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003750 LExtOp0 = LHSShiftAmt.getOperand(0);
3751 RExtOp0 = RHSShiftAmt.getOperand(0);
3752 }
3753
Richard Sandiford95c864d2014-01-08 15:40:47 +00003754 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3755 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3756 if (TryL)
3757 return TryL;
3758
3759 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3760 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3761 if (TryR)
3762 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003763
Craig Topperc0196b12014-04-14 00:51:57 +00003764 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003765}
3766
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003767SDValue DAGCombiner::visitXOR(SDNode *N) {
3768 SDValue N0 = N->getOperand(0);
3769 SDValue N1 = N->getOperand(1);
3770 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003771 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3772 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003773 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003774
Dan Gohmana8665142007-06-25 16:23:39 +00003775 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003776 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003777 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003778 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003779
3780 // fold (xor x, 0) -> x, vector edition
3781 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3782 return N1;
3783 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3784 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003785 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003786
Evan Chengdf1690d2008-03-25 20:08:07 +00003787 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3788 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3789 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003790 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003791 if (N0.getOpcode() == ISD::UNDEF)
3792 return N0;
3793 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003794 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003795 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003796 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003797 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003798 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003799 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003800 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003801 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003802 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003803 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003804 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003805 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003806 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003807 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003808
Nate Begeman21158fc2005-09-01 00:19:25 +00003809 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003810 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003811 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003812 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3813 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003814
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003815 if (!LegalOperations ||
3816 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003817 switch (N0.getOpcode()) {
3818 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003819 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003820 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003821 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003822 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003823 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003824 N0.getOperand(3), NotCC);
3825 }
3826 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003827 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003828
Chris Lattner58c227b2007-09-10 21:39:07 +00003829 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003830 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003831 N0.getNode()->hasOneUse() &&
3832 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003833 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003834 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003835 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003836 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003837 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003838 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003839
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003840 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003841 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003842 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003843 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003844 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3845 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003846 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3847 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003848 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003849 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003850 }
3851 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003852 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003853 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003854 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003855 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003856 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3857 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003858 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3859 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003860 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003861 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003862 }
3863 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003864 // fold (xor (and x, y), y) -> (and (not x), y)
3865 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003866 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003867 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003868 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003869 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003870 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003871 }
Bill Wendling35972a92009-01-30 21:14:50 +00003872 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003873 if (N1C && N0.getOpcode() == ISD::XOR) {
3874 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3875 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3876 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003877 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003878 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003879 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003880 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003881 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003882 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003883 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003884 }
3885 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003886 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003887 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003888
Chris Lattner8d6fc202006-05-05 05:51:50 +00003889 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3890 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003891 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003892 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003893 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003894
Chris Lattner098c01e2006-04-08 04:15:24 +00003895 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003896 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003897 SimplifyDemandedBits(SDValue(N, 0)))
3898 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003899
Evan Chengf1005572010-04-28 07:10:39 +00003900 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003901}
3902
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003903/// Handle transforms common to the three shifts, when the shift amount is a
3904/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003905SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003906 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003907 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003908 return SDValue();
3909
Gabor Greiff304a7a2008-08-28 21:40:38 +00003910 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003911 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003912
Chris Lattner7c709a52007-12-06 07:33:36 +00003913 // We want to pull some binops through shifts, so that we have (and (shift))
3914 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3915 // thing happens with address calculations, so it's important to canonicalize
3916 // it.
3917 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003918
Chris Lattner7c709a52007-12-06 07:33:36 +00003919 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003920 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003921 case ISD::OR:
3922 case ISD::XOR:
3923 HighBitSet = false; // We can only transform sra if the high bit is clear.
3924 break;
3925 case ISD::AND:
3926 HighBitSet = true; // We can only transform sra if the high bit is set.
3927 break;
3928 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003929 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003930 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003931 HighBitSet = false; // We can only transform sra if the high bit is clear.
3932 break;
3933 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003934
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003935 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003936 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003937 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003938
3939 // FIXME: disable this unless the input to the binop is a shift by a constant.
3940 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003941 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003942 // void foo(int *X, int i) { X[i & 1235] = 1; }
3943 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003944 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003945 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003946 BinOpLHSVal->getOpcode() != ISD::SRA &&
3947 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3948 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003949 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003950
Owen Anderson53aa7a92009-08-10 22:56:29 +00003951 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003952
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003953 // If this is a signed shift right, and the high bit is modified by the
3954 // logical operation, do not perform the transformation. The highBitSet
3955 // boolean indicates the value of the high bit of the constant which would
3956 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003957 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003958 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3959 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003960 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003961 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003962
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003963 if (!TLI.isDesirableToCommuteWithShift(LHS))
3964 return SDValue();
3965
Chris Lattner7c709a52007-12-06 07:33:36 +00003966 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003967 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003968 N->getValueType(0),
3969 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003970 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003971
3972 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003973 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003974 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003975 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003976
3977 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003978 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003979}
3980
Adam Nemet67483892014-03-04 23:28:31 +00003981SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3982 assert(N->getOpcode() == ISD::TRUNCATE);
3983 assert(N->getOperand(0).getOpcode() == ISD::AND);
3984
3985 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3986 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3987 SDValue N01 = N->getOperand(0).getOperand(1);
3988
Matt Arsenault985b9de2014-03-17 18:58:01 +00003989 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003990 EVT TruncVT = N->getValueType(0);
3991 SDValue N00 = N->getOperand(0).getOperand(0);
3992 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003993 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003994
3995 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3996 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3997 DAG.getConstant(TruncC, TruncVT));
3998 }
3999 }
4000
4001 return SDValue();
4002}
Adam Nemet7f928f12014-03-07 23:56:30 +00004003
4004SDValue DAGCombiner::visitRotate(SDNode *N) {
4005 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4006 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4007 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4008 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4009 if (NewOp1.getNode())
4010 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4011 N->getOperand(0), NewOp1);
4012 }
4013 return SDValue();
4014}
4015
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004016SDValue DAGCombiner::visitSHL(SDNode *N) {
4017 SDValue N0 = N->getOperand(0);
4018 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004019 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4020 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004021 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004022 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004023
Daniel Sandersa1840d22013-11-11 17:23:41 +00004024 // fold vector ops
4025 if (VT.isVector()) {
4026 SDValue FoldedVOp = SimplifyVBinOp(N);
4027 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004028
4029 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4030 // If setcc produces all-one true value then:
4031 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004032 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004033 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004034 SDValue N00 = N0->getOperand(0);
4035 SDValue N01 = N0->getOperand(1);
4036 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004037
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004038 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4039 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4040 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004041 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4042 if (C.getNode())
4043 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4044 }
4045 } else {
4046 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004047 }
4048 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004049 }
4050
Nate Begeman21158fc2005-09-01 00:19:25 +00004051 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004052 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004053 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004054 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004055 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004056 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004057 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004058 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004059 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004060 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004061 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004062 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004063 // fold (shl undef, x) -> 0
4064 if (N0.getOpcode() == ISD::UNDEF)
4065 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004066 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004067 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004068 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004069 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004070 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004071 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004072 N1.getOperand(0).getOpcode() == ISD::AND) {
4073 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4074 if (NewOp1.getNode())
4075 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004076 }
4077
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004078 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4079 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004080
4081 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004082 if (N1C && N0.getOpcode() == ISD::SHL) {
4083 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4084 uint64_t c1 = N0C1->getZExtValue();
4085 uint64_t c2 = N1C->getZExtValue();
4086 if (c1 + c2 >= OpSizeInBits)
4087 return DAG.getConstant(0, VT);
4088 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4089 DAG.getConstant(c1 + c2, N1.getValueType()));
4090 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004091 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004092
4093 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4094 // For this to be valid, the second form must not preserve any of the bits
4095 // that are shifted out by the inner shift in the first form. This means
4096 // the outer shift size must be >= the number of bits added by the ext.
4097 // As a corollary, we don't care what kind of ext it is.
4098 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4099 N0.getOpcode() == ISD::ANY_EXTEND ||
4100 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004101 N0.getOperand(0).getOpcode() == ISD::SHL) {
4102 SDValue N0Op0 = N0.getOperand(0);
4103 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4104 uint64_t c1 = N0Op0C1->getZExtValue();
4105 uint64_t c2 = N1C->getZExtValue();
4106 EVT InnerShiftVT = N0Op0.getValueType();
4107 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4108 if (c2 >= OpSizeInBits - InnerShiftSize) {
4109 if (c1 + c2 >= OpSizeInBits)
4110 return DAG.getConstant(0, VT);
4111 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4112 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4113 N0Op0->getOperand(0)),
4114 DAG.getConstant(c1 + c2, N1.getValueType()));
4115 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004116 }
4117 }
4118
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004119 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4120 // Only fold this if the inner zext has no other uses to avoid increasing
4121 // the total number of instructions.
4122 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004123 N0.getOperand(0).getOpcode() == ISD::SRL) {
4124 SDValue N0Op0 = N0.getOperand(0);
4125 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4126 uint64_t c1 = N0Op0C1->getZExtValue();
4127 if (c1 < VT.getScalarSizeInBits()) {
4128 uint64_t c2 = N1C->getZExtValue();
4129 if (c1 == c2) {
4130 SDValue NewOp0 = N0.getOperand(0);
4131 EVT CountVT = NewOp0.getOperand(1).getValueType();
4132 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4133 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004134 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004135 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4136 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004137 }
4138 }
4139 }
4140
Eli Friedman1877ac92011-06-09 22:14:44 +00004141 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4142 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004143 // Only fold this if the inner shift has no other uses -- if it does, folding
4144 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004145 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4146 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4147 uint64_t c1 = N0C1->getZExtValue();
4148 if (c1 < OpSizeInBits) {
4149 uint64_t c2 = N1C->getZExtValue();
4150 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4151 SDValue Shift;
4152 if (c2 > c1) {
4153 Mask = Mask.shl(c2 - c1);
4154 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4155 DAG.getConstant(c2 - c1, N1.getValueType()));
4156 } else {
4157 Mask = Mask.lshr(c1 - c2);
4158 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4159 DAG.getConstant(c1 - c2, N1.getValueType()));
4160 }
4161 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4162 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004163 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004164 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004165 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004166 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004167 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004168 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004169 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004170 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4171 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004172 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004173 HiBitsMask);
4174 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004175
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004176 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004177 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004178 if (NewSHL.getNode())
4179 return NewSHL;
4180 }
4181
Evan Chengf1005572010-04-28 07:10:39 +00004182 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004183}
4184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004185SDValue DAGCombiner::visitSRA(SDNode *N) {
4186 SDValue N0 = N->getOperand(0);
4187 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004188 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4189 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004190 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004191 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004192
Daniel Sandersa1840d22013-11-11 17:23:41 +00004193 // fold vector ops
4194 if (VT.isVector()) {
4195 SDValue FoldedVOp = SimplifyVBinOp(N);
4196 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004197
4198 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004199 }
4200
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004201 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004202 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004203 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004204 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004205 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004206 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004207 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004208 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004209 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004210 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004211 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004212 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004213 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004214 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004215 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004216 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4217 // sext_inreg.
4218 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004219 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004220 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4221 if (VT.isVector())
4222 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4223 ExtVT, VT.getVectorNumElements());
4224 if ((!LegalOperations ||
4225 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004226 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004227 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004228 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004229
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004230 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004231 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004232 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004233 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004234 if (Sum >= OpSizeInBits)
4235 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004236 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004237 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004238 }
4239 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004240
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004241 // fold (sra (shl X, m), (sub result_size, n))
4242 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004243 // result_size - n != m.
4244 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004245 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004246 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004247 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004248 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4249 if (N01C) {
4250 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004251 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004252 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4253
4254 if (VT.isVector())
4255 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4256
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004257 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004258 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004259
Scott Michelcf0da6c2009-02-17 22:15:04 +00004260 // If the shift is not a no-op (in which case this should be just a sign
4261 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004262 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004263 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004264 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004265 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4266 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004267 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004268
Owen Andersonb2c80da2011-02-25 21:41:48 +00004269 SDValue Amt = DAG.getConstant(ShiftAmt,
4270 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004271 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004272 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004273 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004274 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004275 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004276 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004277 }
4278 }
4279 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004280
Duncan Sands3ed76882009-02-01 18:06:53 +00004281 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004282 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004283 N1.getOperand(0).getOpcode() == ISD::AND) {
4284 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4285 if (NewOp1.getNode())
4286 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004287 }
4288
Matt Arsenault985b9de2014-03-17 18:58:01 +00004289 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004290 // if c1 is equal to the number of bits the trunc removes
4291 if (N0.getOpcode() == ISD::TRUNCATE &&
4292 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4293 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4294 N0.getOperand(0).hasOneUse() &&
4295 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004296 N1C) {
4297 SDValue N0Op0 = N0.getOperand(0);
4298 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4299 unsigned LargeShiftVal = LargeShift->getZExtValue();
4300 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004301
Matt Arsenault985b9de2014-03-17 18:58:01 +00004302 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4303 SDValue Amt =
4304 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4305 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4306 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4307 N0Op0.getOperand(0), Amt);
4308 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4309 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004310 }
4311 }
4312
Scott Michelcf0da6c2009-02-17 22:15:04 +00004313 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004314 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4315 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004316
4317
Nate Begeman21158fc2005-09-01 00:19:25 +00004318 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004319 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004320 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004321
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004322 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004323 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004324 if (NewSRA.getNode())
4325 return NewSRA;
4326 }
4327
Evan Chengf1005572010-04-28 07:10:39 +00004328 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004329}
4330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004331SDValue DAGCombiner::visitSRL(SDNode *N) {
4332 SDValue N0 = N->getOperand(0);
4333 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004334 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4335 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004336 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004337 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004338
Daniel Sandersa1840d22013-11-11 17:23:41 +00004339 // fold vector ops
4340 if (VT.isVector()) {
4341 SDValue FoldedVOp = SimplifyVBinOp(N);
4342 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004343
4344 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004345 }
4346
Nate Begeman21158fc2005-09-01 00:19:25 +00004347 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004348 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004349 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004350 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004351 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004352 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004353 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004354 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004355 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004356 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004357 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004358 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004359 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004360 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004361 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004362 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004363
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004364 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004365 if (N1C && N0.getOpcode() == ISD::SRL) {
4366 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4367 uint64_t c1 = N01C->getZExtValue();
4368 uint64_t c2 = N1C->getZExtValue();
4369 if (c1 + c2 >= OpSizeInBits)
4370 return DAG.getConstant(0, VT);
4371 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4372 DAG.getConstant(c1 + c2, N1.getValueType()));
4373 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004374 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004375
Dale Johannesencd538af2010-12-17 21:45:49 +00004376 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004377 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4378 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004379 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004380 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004381 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4382 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004383 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4384 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004385 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004386 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004387 if (c1 + OpSizeInBits == InnerShiftSize) {
4388 if (c1 + c2 >= InnerShiftSize)
4389 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004390 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4391 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004392 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004393 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004394 }
4395 }
4396
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004397 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004398 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4399 unsigned BitSize = N0.getScalarValueSizeInBits();
4400 if (BitSize <= 64) {
4401 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4402 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4403 DAG.getConstant(~0ULL >> ShAmt, VT));
4404 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004405 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004406
Michael Liao62ebfd82013-06-21 18:45:27 +00004407 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004408 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4409 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004410 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004411 unsigned BitSize = SmallVT.getScalarSizeInBits();
4412 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004413 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004414
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004415 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004416 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004417 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004418 N0.getOperand(0),
4419 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004420 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004421 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004422 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4423 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4424 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004425 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004426 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004427
Chris Lattner2e33fb42006-10-12 20:23:19 +00004428 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4429 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004430 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004431 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004432 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004433 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004434
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004435 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004436 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004437 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004438 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004439 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004440
Chris Lattner49932492006-04-02 06:11:11 +00004441 // If any of the input bits are KnownOne, then the input couldn't be all
4442 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004443 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004444
Chris Lattner49932492006-04-02 06:11:11 +00004445 // If all of the bits input the to ctlz node are known to be zero, then
4446 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004447 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004448 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004449
Chris Lattner49932492006-04-02 06:11:11 +00004450 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004451 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004452 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004453 // could be set on input to the CTLZ node. If this bit is set, the SRL
4454 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4455 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004456 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004457 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004458
Chris Lattner49932492006-04-02 06:11:11 +00004459 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004460 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004461 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004462 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004463 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004464
Andrew Trickef9de2a2013-05-25 02:42:55 +00004465 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004466 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004467 }
4468 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004469
Duncan Sands3ed76882009-02-01 18:06:53 +00004470 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004471 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004472 N1.getOperand(0).getOpcode() == ISD::AND) {
4473 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4474 if (NewOp1.getNode())
4475 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004476 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004477
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004478 // fold operands of srl based on knowledge that the low bits are not
4479 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004480 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4481 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004482
Evan Chengb175de62009-12-18 21:31:31 +00004483 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004484 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004485 if (NewSRL.getNode())
4486 return NewSRL;
4487 }
4488
Dan Gohman600f62b2010-06-24 14:30:44 +00004489 // Attempt to convert a srl of a load into a narrower zero-extending load.
4490 SDValue NarrowLoad = ReduceLoadWidth(N);
4491 if (NarrowLoad.getNode())
4492 return NarrowLoad;
4493
Evan Chengb175de62009-12-18 21:31:31 +00004494 // Here is a common situation. We want to optimize:
4495 //
4496 // %a = ...
4497 // %b = and i32 %a, 2
4498 // %c = srl i32 %b, 1
4499 // brcond i32 %c ...
4500 //
4501 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004502 //
Evan Chengb175de62009-12-18 21:31:31 +00004503 // %a = ...
4504 // %b = and %a, 2
4505 // %c = setcc eq %b, 0
4506 // brcond %c ...
4507 //
4508 // However when after the source operand of SRL is optimized into AND, the SRL
4509 // itself may not be optimized further. Look for it and add the BRCOND into
4510 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004511 if (N->hasOneUse()) {
4512 SDNode *Use = *N->use_begin();
4513 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004514 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004515 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4516 // Also look pass the truncate.
4517 Use = *Use->use_begin();
4518 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004519 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004520 }
4521 }
Evan Chengb175de62009-12-18 21:31:31 +00004522
Evan Chengf1005572010-04-28 07:10:39 +00004523 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004524}
4525
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004526SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4527 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004528 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004529
4530 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004531 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004532 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004533 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004534}
4535
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004536SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4537 SDValue N0 = N->getOperand(0);
4538 EVT VT = N->getValueType(0);
4539
4540 // fold (ctlz_zero_undef c1) -> c2
4541 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004542 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004543 return SDValue();
4544}
4545
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004546SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4547 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004548 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004549
Nate Begeman21158fc2005-09-01 00:19:25 +00004550 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004551 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004552 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004553 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004554}
4555
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004556SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4557 SDValue N0 = N->getOperand(0);
4558 EVT VT = N->getValueType(0);
4559
4560 // fold (cttz_zero_undef c1) -> c2
4561 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004562 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004563 return SDValue();
4564}
4565
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004566SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4567 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004568 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004569
Nate Begeman21158fc2005-09-01 00:19:25 +00004570 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004571 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004572 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004573 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004574}
4575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004576SDValue DAGCombiner::visitSELECT(SDNode *N) {
4577 SDValue N0 = N->getOperand(0);
4578 SDValue N1 = N->getOperand(1);
4579 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004580 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4581 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4582 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004583 EVT VT = N->getValueType(0);
4584 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004585
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004586 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004587 if (N1 == N2)
4588 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004589 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004590 if (N0C && !N0C->isNullValue())
4591 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004592 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004593 if (N0C && N0C->isNullValue())
4594 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004595 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004596 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004597 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004598 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004599 // We can't do this reliably if integer based booleans have different contents
4600 // to floating point based booleans. This is because we can't tell whether we
4601 // have an integer-based boolean or a floating-point-based boolean unless we
4602 // can find the SETCC that produced it and inspect its operands. This is
4603 // fairly easy if C is the SETCC node, but it can potentially be
4604 // undiscoverable (or not reasonably discoverable). For example, it could be
4605 // in another basic block or it could require searching a complicated
4606 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004607 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004608 (VT0 == MVT::i1 || (VT0.isInteger() &&
4609 TLI.getBooleanContents(false, false) ==
4610 TLI.getBooleanContents(false, true) &&
4611 TLI.getBooleanContents(false, false) ==
4612 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004613 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004614 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004615 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004616 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004617 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004618 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004619 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004620 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004621 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004622 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4623 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004624 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004625 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004626 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004627 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004628 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004629 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004630 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004631 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004632 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004633 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004634 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004635 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004636 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004637 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004638 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004639 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004640 // fold (select X, X, Y) -> (or X, Y)
4641 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004642 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004643 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004644 // fold (select X, Y, X) -> (and X, Y)
4645 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004646 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004647 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004648
Chris Lattner6c14c352005-10-18 06:04:22 +00004649 // If we can fold this based on the true/false value, do so.
4650 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004651 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004652
Nate Begemanc760f802005-09-19 22:34:01 +00004653 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004654 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004655 if ((!LegalOperations &&
4656 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4657 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004658 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004659 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004660 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004661 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004662 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004664 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004665}
4666
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004667static
4668std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4669 SDLoc DL(N);
4670 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004671 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004672
4673 // Split the inputs.
4674 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004675 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4676 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004677
4678 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4679 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4680
4681 return std::make_pair(Lo, Hi);
4682}
4683
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004684// This function assumes all the vselect's arguments are CONCAT_VECTOR
4685// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4686static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4687 SDLoc dl(N);
4688 SDValue Cond = N->getOperand(0);
4689 SDValue LHS = N->getOperand(1);
4690 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004691 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004692 int NumElems = VT.getVectorNumElements();
4693 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4694 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4695 Cond.getOpcode() == ISD::BUILD_VECTOR);
4696
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004697 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4698 // binary ones here.
4699 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4700 return SDValue();
4701
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004702 // We're sure we have an even number of elements due to the
4703 // concat_vectors we have as arguments to vselect.
4704 // Skip BV elements until we find one that's not an UNDEF
4705 // After we find an UNDEF element, keep looping until we get to half the
4706 // length of the BV and see if all the non-undef nodes are the same.
4707 ConstantSDNode *BottomHalf = nullptr;
4708 for (int i = 0; i < NumElems / 2; ++i) {
4709 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4710 continue;
4711
4712 if (BottomHalf == nullptr)
4713 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4714 else if (Cond->getOperand(i).getNode() != BottomHalf)
4715 return SDValue();
4716 }
4717
4718 // Do the same for the second half of the BuildVector
4719 ConstantSDNode *TopHalf = nullptr;
4720 for (int i = NumElems / 2; i < NumElems; ++i) {
4721 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4722 continue;
4723
4724 if (TopHalf == nullptr)
4725 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4726 else if (Cond->getOperand(i).getNode() != TopHalf)
4727 return SDValue();
4728 }
4729
4730 assert(TopHalf && BottomHalf &&
4731 "One half of the selector was all UNDEFs and the other was all the "
4732 "same value. This should have been addressed before this function.");
4733 return DAG.getNode(
4734 ISD::CONCAT_VECTORS, dl, VT,
4735 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4736 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4737}
4738
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004739SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4740 SDValue N0 = N->getOperand(0);
4741 SDValue N1 = N->getOperand(1);
4742 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004743 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004744
4745 // Canonicalize integer abs.
4746 // vselect (setg[te] X, 0), X, -X ->
4747 // vselect (setgt X, -1), X, -X ->
4748 // vselect (setl[te] X, 0), -X, X ->
4749 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4750 if (N0.getOpcode() == ISD::SETCC) {
4751 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4752 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4753 bool isAbs = false;
4754 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4755
4756 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4757 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4758 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4759 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4760 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4761 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4762 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4763
4764 if (isAbs) {
4765 EVT VT = LHS.getValueType();
4766 SDValue Shift = DAG.getNode(
4767 ISD::SRA, DL, VT, LHS,
4768 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4769 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004770 AddToWorklist(Shift.getNode());
4771 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004772 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4773 }
4774 }
4775
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004776 // If the VSELECT result requires splitting and the mask is provided by a
4777 // SETCC, then split both nodes and its operands before legalization. This
4778 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4779 // and enables future optimizations (e.g. min/max pattern matching on X86).
4780 if (N0.getOpcode() == ISD::SETCC) {
4781 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004782
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004783 // Check if any splitting is required.
4784 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4785 TargetLowering::TypeSplitVector)
4786 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004787
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004788 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004789 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4790 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4791 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004792
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004793 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4794 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004795
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004796 // Add the new VSELECT nodes to the work list in case they need to be split
4797 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004798 AddToWorklist(Lo.getNode());
4799 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004800
4801 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004802 }
4803
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004804 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4805 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4806 return N1;
4807 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4808 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4809 return N2;
4810
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004811 // The ConvertSelectToConcatVector function is assuming both the above
4812 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4813 // and addressed.
4814 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4815 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4816 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4817 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4818 if (CV.getNode())
4819 return CV;
4820 }
4821
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004822 return SDValue();
4823}
4824
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004825SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4826 SDValue N0 = N->getOperand(0);
4827 SDValue N1 = N->getOperand(1);
4828 SDValue N2 = N->getOperand(2);
4829 SDValue N3 = N->getOperand(3);
4830 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004831 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004832
Nate Begemanc760f802005-09-19 22:34:01 +00004833 // fold select_cc lhs, rhs, x, x, cc -> x
4834 if (N2 == N3)
4835 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004836
Chris Lattner8b68dec2006-09-20 06:19:26 +00004837 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004838 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004839 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004840 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004841 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004842
Stephen Lin605207f2013-06-15 04:03:33 +00004843 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4844 if (!SCCC->isNullValue())
4845 return N2; // cond always true -> true val
4846 else
4847 return N3; // cond always false -> false val
4848 }
4849
4850 // Fold to a simpler select_cc
4851 if (SCC.getOpcode() == ISD::SETCC)
4852 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4853 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4854 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004855 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004856
Chris Lattner6c14c352005-10-18 06:04:22 +00004857 // If we can fold this based on the true/false value, do so.
4858 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004859 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004860
Nate Begemanc760f802005-09-19 22:34:01 +00004861 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004862 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004863}
4864
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004865SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004866 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004867 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004868 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004869}
4870
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004871// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4872// dag node into a ConstantSDNode or a build_vector of constants.
4873// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004874// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004875// Vector extends are not folded if operations are legal; this is to
4876// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004877static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4878 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004879 bool LegalOperations) {
4880 unsigned Opcode = N->getOpcode();
4881 SDValue N0 = N->getOperand(0);
4882 EVT VT = N->getValueType(0);
4883
4884 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4885 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4886
4887 // fold (sext c1) -> c1
4888 // fold (zext c1) -> c1
4889 // fold (aext c1) -> c1
4890 if (isa<ConstantSDNode>(N0))
4891 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4892
4893 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4894 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4895 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004896 EVT SVT = VT.getScalarType();
4897 if (!(VT.isVector() &&
4898 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004899 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004900 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004901
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004902 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004903 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004904 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4905 unsigned ShAmt = VTBits - EVTBits;
4906 SmallVector<SDValue, 8> Elts;
4907 unsigned NumElts = N0->getNumOperands();
4908 SDLoc DL(N);
4909
4910 for (unsigned i=0; i != NumElts; ++i) {
4911 SDValue Op = N0->getOperand(i);
4912 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004913 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004914 continue;
4915 }
4916
4917 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4918 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4919 if (Opcode == ISD::SIGN_EXTEND)
4920 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004921 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004922 else
4923 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004924 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004925 }
4926
Craig Topper48d114b2014-04-26 18:35:24 +00004927 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004928}
4929
Evan Chenge106e2f2007-10-29 19:58:20 +00004930// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004931// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004932// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004933// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004934static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004935 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004936 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004937 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004938 bool HasCopyToRegUses = false;
4939 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004940 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4941 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004942 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004943 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004944 if (User == N)
4945 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004946 if (UI.getUse().getResNo() != N0.getResNo())
4947 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004948 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004949 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004950 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4951 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4952 // Sign bits will be lost after a zext.
4953 return false;
4954 bool Add = false;
4955 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004956 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004957 if (UseOp == N0)
4958 continue;
4959 if (!isa<ConstantSDNode>(UseOp))
4960 return false;
4961 Add = true;
4962 }
4963 if (Add)
4964 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004965 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004966 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004967 // If truncates aren't free and there are users we can't
4968 // extend, it isn't worthwhile.
4969 if (!isTruncFree)
4970 return false;
4971 // Remember if this value is live-out.
4972 if (User->getOpcode() == ISD::CopyToReg)
4973 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004974 }
4975
4976 if (HasCopyToRegUses) {
4977 bool BothLiveOut = false;
4978 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4979 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004980 SDUse &Use = UI.getUse();
4981 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4982 BothLiveOut = true;
4983 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004984 }
4985 }
4986 if (BothLiveOut)
4987 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004988 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004989 return ExtendNodes.size();
4990 }
4991 return true;
4992}
4993
Craig Toppere0b71182013-07-13 07:43:40 +00004994void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004995 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004996 ISD::NodeType ExtType) {
4997 // Extend SetCC uses if necessary.
4998 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4999 SDNode *SetCC = SetCCs[i];
5000 SmallVector<SDValue, 4> Ops;
5001
5002 for (unsigned j = 0; j != 2; ++j) {
5003 SDValue SOp = SetCC->getOperand(j);
5004 if (SOp == Trunc)
5005 Ops.push_back(ExtLoad);
5006 else
5007 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5008 }
5009
5010 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005011 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005012 }
5013}
5014
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005015SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5016 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005017 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005018
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005019 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5020 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005021 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005022
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005023 // fold (sext (sext x)) -> (sext x)
5024 // fold (sext (aext x)) -> (sext x)
5025 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005026 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005027 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005028
Chris Lattnerfce448f2007-02-26 03:13:59 +00005029 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005030 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5031 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005032 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5033 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005034 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5035 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005036 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005037 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005038 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005039 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005040 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005041 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005042
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005043 // See if the value being truncated is already sign extended. If so, just
5044 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005045 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005046 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5047 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5048 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005049 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005050
Chris Lattnerfce448f2007-02-26 03:13:59 +00005051 if (OpBits == DestBits) {
5052 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5053 // bits, it is already ready.
5054 if (NumSignBits > DestBits-MidBits)
5055 return Op;
5056 } else if (OpBits < DestBits) {
5057 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5058 // bits, just sext from i32.
5059 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005060 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005061 } else {
5062 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5063 // bits, just truncate to i32.
5064 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005065 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005066 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005067
Chris Lattnerfce448f2007-02-26 03:13:59 +00005068 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005069 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5070 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005071 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005072 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005073 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005074 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5075 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005076 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005077 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005078 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005079
Evan Chengbce7c472005-12-14 02:19:23 +00005080 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005081 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005082 // on vectors in one instruction. We only perform this transformation on
5083 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005084 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005085 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005086 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005087 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005088 bool DoXform = true;
5089 SmallVector<SDNode*, 4> SetCCs;
5090 if (!N0.hasOneUse())
5091 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5092 if (DoXform) {
5093 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005094 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005095 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005096 LN0->getBasePtr(), N0.getValueType(),
5097 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005098 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005099 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005100 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005101 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005102 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005103 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005104 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005105 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005106 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005107
5108 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5109 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005110 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5111 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005112 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005113 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005114 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005115 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005116 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005117 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005118 LN0->getBasePtr(), MemVT,
5119 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005120 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005121 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005122 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005123 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005124 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005125 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005126 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005127 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005128
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005129 // fold (sext (and/or/xor (load x), cst)) ->
5130 // (and/or/xor (sextload x), (sext cst))
5131 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5132 N0.getOpcode() == ISD::XOR) &&
5133 isa<LoadSDNode>(N0.getOperand(0)) &&
5134 N0.getOperand(1).getOpcode() == ISD::Constant &&
5135 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5136 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5137 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005138 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005139 bool DoXform = true;
5140 SmallVector<SDNode*, 4> SetCCs;
5141 if (!N0.hasOneUse())
5142 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5143 SetCCs, TLI);
5144 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005145 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005146 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005147 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005148 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005149 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5150 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005151 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005152 ExtLoad, DAG.getConstant(Mask, VT));
5153 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005154 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005155 N0.getOperand(0).getValueType(), ExtLoad);
5156 CombineTo(N, And);
5157 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005158 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005159 ISD::SIGN_EXTEND);
5160 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5161 }
5162 }
5163 }
5164
Chris Lattner65786b02007-04-11 05:32:27 +00005165 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005166 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005167 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005168 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005169 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005170 TLI.getBooleanContents(N0VT) ==
5171 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005172 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5173 // of the same size as the compared operands. Only optimize sext(setcc())
5174 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005175 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005176
5177 // We know that the # elements of the results is the same as the
5178 // # elements of the compare (and the # elements of the compare result
5179 // for that matter). Check to see that they are the same size. If so,
5180 // we know that the element size of the sext'd result matches the
5181 // element size of the compare operands.
5182 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005183 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005184 N0.getOperand(1),
5185 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005186
Dan Gohmane82c25e2010-04-30 17:19:19 +00005187 // If the desired elements are smaller or larger than the source
5188 // elements we can use a matching integer vector type and then
5189 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005190 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005191 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005192 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005193 N0.getOperand(0), N0.getOperand(1),
5194 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005195 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005196 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005197 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005198
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005199 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005200 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005201 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005202 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005203 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005204 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005205 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005206 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005207 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005208
5209 if (!VT.isVector()) {
5210 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5211 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5212 SDLoc DL(N);
5213 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5214 SDValue SetCC = DAG.getSetCC(DL,
5215 SetCCVT,
5216 N0.getOperand(0), N0.getOperand(1), CC);
5217 EVT SelectVT = getSetCCResultType(VT);
5218 return DAG.getSelect(DL, VT,
5219 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5220 NegOne, DAG.getConstant(0, VT));
5221
5222 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005223 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005224 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005225
Dan Gohman3eb10f72008-04-28 16:58:24 +00005226 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005227 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005228 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005229 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005230
Evan Chengf1005572010-04-28 07:10:39 +00005231 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005232}
5233
Rafael Espindola8f62b322012-04-09 16:06:03 +00005234// isTruncateOf - If N is a truncate of some other value, return true, record
5235// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5236// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005237// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005238static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5239 APInt &KnownZero) {
5240 APInt KnownOne;
5241 if (N->getOpcode() == ISD::TRUNCATE) {
5242 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005243 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005244 return true;
5245 }
5246
5247 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5248 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5249 return false;
5250
5251 SDValue Op0 = N->getOperand(0);
5252 SDValue Op1 = N->getOperand(1);
5253 assert(Op0.getValueType() == Op1.getValueType());
5254
5255 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5256 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005257 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005258 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005259 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005260 Op = Op0;
5261 else
5262 return false;
5263
Jay Foada0653a32014-05-14 21:14:37 +00005264 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005265
5266 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5267 return false;
5268
5269 return true;
5270}
5271
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005272SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5273 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005274 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005275
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005276 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5277 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005278 return SDValue(Res, 0);
5279
Nate Begeman21158fc2005-09-01 00:19:25 +00005280 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005281 // fold (zext (aext x)) -> (zext x)
5282 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005283 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005284 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005285
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005286 // fold (zext (truncate x)) -> (zext x) or
5287 // (zext (truncate x)) -> (truncate x)
5288 // This is valid when the truncated bits of x are already zero.
5289 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005290 SDValue Op;
5291 APInt KnownZero;
5292 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5293 APInt TruncatedBits =
5294 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5295 APInt(Op.getValueSizeInBits(), 0) :
5296 APInt::getBitsSet(Op.getValueSizeInBits(),
5297 N0.getValueSizeInBits(),
5298 std::min(Op.getValueSizeInBits(),
5299 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005300 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005301 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005302 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005303 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005304 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005305
5306 return Op;
5307 }
5308 }
5309
Evan Cheng464dc9b2007-03-22 01:54:19 +00005310 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5311 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005312 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005313 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5314 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005315 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5316 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005317 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005318 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005319 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005320 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005321 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005322 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005323 }
5324
Chris Lattnera31f0a62006-09-21 06:00:20 +00005325 // fold (zext (truncate x)) -> (and x, mask)
5326 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005327 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005328
5329 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5330 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5331 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5332 if (NarrowLoad.getNode()) {
5333 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5334 if (NarrowLoad.getNode() != N0.getNode()) {
5335 CombineTo(N0.getNode(), NarrowLoad);
5336 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005337 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005338 }
5339 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5340 }
5341
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005342 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005343 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005344 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005345 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005346 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005347 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005348 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005349 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005350 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005351 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005352 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005353
Dan Gohmanad3e5492009-04-08 00:15:30 +00005354 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5355 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005356 if (N0.getOpcode() == ISD::AND &&
5357 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005358 N0.getOperand(1).getOpcode() == ISD::Constant &&
5359 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5360 N0.getValueType()) ||
5361 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005362 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005363 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005364 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005365 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005366 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005367 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005368 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005369 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005370 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005371 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005372 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005373
Evan Chengbce7c472005-12-14 02:19:23 +00005374 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005375 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005376 // on vectors in one instruction. We only perform this transformation on
5377 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005378 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005379 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005380 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005381 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005382 bool DoXform = true;
5383 SmallVector<SDNode*, 4> SetCCs;
5384 if (!N0.hasOneUse())
5385 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5386 if (DoXform) {
5387 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005388 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005389 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005390 LN0->getBasePtr(), N0.getValueType(),
5391 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005392 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005393 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005394 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005395 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005396
Andrew Trickef9de2a2013-05-25 02:42:55 +00005397 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005398 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005399 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005400 }
Evan Chengbce7c472005-12-14 02:19:23 +00005401 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005402
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005403 // fold (zext (and/or/xor (load x), cst)) ->
5404 // (and/or/xor (zextload x), (zext cst))
5405 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5406 N0.getOpcode() == ISD::XOR) &&
5407 isa<LoadSDNode>(N0.getOperand(0)) &&
5408 N0.getOperand(1).getOpcode() == ISD::Constant &&
5409 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5410 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5411 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005412 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005413 bool DoXform = true;
5414 SmallVector<SDNode*, 4> SetCCs;
5415 if (!N0.hasOneUse())
5416 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5417 SetCCs, TLI);
5418 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005419 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005420 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005421 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005422 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005423 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5424 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005425 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005426 ExtLoad, DAG.getConstant(Mask, VT));
5427 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005428 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005429 N0.getOperand(0).getValueType(), ExtLoad);
5430 CombineTo(N, And);
5431 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005432 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005433 ISD::ZERO_EXTEND);
5434 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5435 }
5436 }
5437 }
5438
Chris Lattner7dac1082005-12-14 19:05:06 +00005439 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5440 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005441 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5442 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005443 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005444 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005445 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005446 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005447 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005448 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005449 LN0->getBasePtr(), MemVT,
5450 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005451 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005452 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005453 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005454 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005455 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005456 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005457 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005458 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005459
Chris Lattner65786b02007-04-11 05:32:27 +00005460 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005461 if (!LegalOperations && VT.isVector() &&
5462 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005463 EVT N0VT = N0.getOperand(0).getValueType();
5464 if (getSetCCResultType(N0VT) == N0.getValueType())
5465 return SDValue();
5466
Evan Chengabd0ad52010-05-19 01:08:17 +00005467 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5468 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005469 EVT EltVT = VT.getVectorElementType();
5470 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5471 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005472 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005473 // We know that the # elements of the results is the same as the
5474 // # elements of the compare (and the # elements of the compare result
5475 // for that matter). Check to see that they are the same size. If so,
5476 // we know that the element size of the sext'd result matches the
5477 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005478 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5479 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005480 N0.getOperand(1),
5481 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005482 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005483 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005484
5485 // If the desired elements are smaller or larger than the source
5486 // elements we can use a matching integer vector type and then
5487 // truncate/sign extend
5488 EVT MatchingElementType =
5489 EVT::getIntegerVT(*DAG.getContext(),
5490 N0VT.getScalarType().getSizeInBits());
5491 EVT MatchingVectorType =
5492 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5493 N0VT.getVectorNumElements());
5494 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005495 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005496 N0.getOperand(1),
5497 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005498 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5499 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005500 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005501 }
5502
5503 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005504 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005505 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005506 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005507 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005508 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005509 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005510
Evan Cheng852c4862009-12-15 03:00:32 +00005511 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005512 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005513 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005514 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5515 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005516 SDValue ShAmt = N0.getOperand(1);
5517 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005518 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005519 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005520 // If the original shl may be shifting out bits, do not perform this
5521 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005522 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5523 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5524 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005525 return SDValue();
5526 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005527
Andrew Trickef9de2a2013-05-25 02:42:55 +00005528 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005529
5530 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005531 if (VT.getSizeInBits() >= 256)
5532 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005533
Chris Lattnere95d1952011-02-13 19:09:16 +00005534 return DAG.getNode(N0.getOpcode(), DL, VT,
5535 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5536 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005537 }
5538
Evan Chengf1005572010-04-28 07:10:39 +00005539 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005540}
5541
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005542SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5543 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005544 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005545
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005546 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5547 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005548 return SDValue(Res, 0);
5549
Chris Lattner812646a2006-05-05 05:58:59 +00005550 // fold (aext (aext x)) -> (aext x)
5551 // fold (aext (zext x)) -> (zext x)
5552 // fold (aext (sext x)) -> (sext x)
5553 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5554 N0.getOpcode() == ISD::ZERO_EXTEND ||
5555 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005556 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005557
Evan Cheng464dc9b2007-03-22 01:54:19 +00005558 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5559 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5560 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005561 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5562 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005563 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5564 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005565 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005566 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005567 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005568 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005569 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005570 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005571 }
5572
Chris Lattner8746e2c2006-09-20 06:29:17 +00005573 // fold (aext (truncate x))
5574 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005575 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005576 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005577 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005578 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005579 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5580 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005581 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005582
Dan Gohmanad3e5492009-04-08 00:15:30 +00005583 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5584 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005585 if (N0.getOpcode() == ISD::AND &&
5586 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005587 N0.getOperand(1).getOpcode() == ISD::Constant &&
5588 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5589 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005590 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005591 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005592 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005593 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005594 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005595 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005596 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005597 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005598 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005599 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005600 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005601
Chris Lattner812646a2006-05-05 05:58:59 +00005602 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005603 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005604 // on vectors in one instruction. We only perform this transformation on
5605 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005606 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005607 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005608 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005609 bool DoXform = true;
5610 SmallVector<SDNode*, 4> SetCCs;
5611 if (!N0.hasOneUse())
5612 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5613 if (DoXform) {
5614 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005615 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005616 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005617 LN0->getBasePtr(), N0.getValueType(),
5618 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005619 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005620 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005621 N0.getValueType(), ExtLoad);
5622 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005623 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005624 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005625 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5626 }
Chris Lattner812646a2006-05-05 05:58:59 +00005627 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005628
Chris Lattner812646a2006-05-05 05:58:59 +00005629 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5630 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5631 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005632 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005633 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005634 N0.hasOneUse()) {
5635 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005636 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005637 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005638 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5639 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5640 VT, LN0->getChain(), LN0->getBasePtr(),
5641 MemVT, LN0->getMemOperand());
5642 CombineTo(N, ExtLoad);
5643 CombineTo(N0.getNode(),
5644 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5645 N0.getValueType(), ExtLoad),
5646 ExtLoad.getValue(1));
5647 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5648 }
Chris Lattner812646a2006-05-05 05:58:59 +00005649 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005650
Chris Lattner65786b02007-04-11 05:32:27 +00005651 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005652 // For vectors:
5653 // aext(setcc) -> vsetcc
5654 // aext(setcc) -> truncate(vsetcc)
5655 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005656 // Only do this before legalize for now.
5657 if (VT.isVector() && !LegalOperations) {
5658 EVT N0VT = N0.getOperand(0).getValueType();
5659 // We know that the # elements of the results is the same as the
5660 // # elements of the compare (and the # elements of the compare result
5661 // for that matter). Check to see that they are the same size. If so,
5662 // we know that the element size of the sext'd result matches the
5663 // element size of the compare operands.
5664 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005665 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005666 N0.getOperand(1),
5667 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005668 // If the desired elements are smaller or larger than the source
5669 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005670 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005671 else {
Hao Liuc636d152014-04-22 09:57:06 +00005672 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005673 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005674 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005675 N0.getOperand(1),
5676 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005677 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005678 }
5679 }
5680
5681 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005682 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005683 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005684 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005685 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005686 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005687 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005688 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005689
Evan Chengf1005572010-04-28 07:10:39 +00005690 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005691}
5692
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005693/// See if the specified operand can be simplified with the knowledge that only
5694/// the bits specified by Mask are used. If so, return the simpler operand,
5695/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005696SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005697 switch (V.getOpcode()) {
5698 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005699 case ISD::Constant: {
5700 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005701 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005702 const APInt &CVal = CV->getAPIntValue();
5703 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005704 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005705 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005706 break;
5707 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005708 case ISD::OR:
5709 case ISD::XOR:
5710 // If the LHS or RHS don't contribute bits to the or, drop them.
5711 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5712 return V.getOperand(1);
5713 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5714 return V.getOperand(0);
5715 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005716 case ISD::SRL:
5717 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005718 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005719 break;
5720 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5721 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005722 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005723
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005724 // Watch out for shift count overflow though.
5725 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005726 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005727 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005728 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005729 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005730 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005731 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005732 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005733 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005734}
5735
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005736/// If the result of a wider load is shifted to right of N bits and then
5737/// truncated to a narrower type and where N is a multiple of number of bits of
5738/// the narrower type, transform it to a narrower load from address + N / num of
5739/// bits of new type. If the result is to be extended, also fold the extension
5740/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005741SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005742 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005743
Evan Cheng464dc9b2007-03-22 01:54:19 +00005744 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005745 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005746 EVT VT = N->getValueType(0);
5747 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005748
Dan Gohman550c9af2008-08-14 20:04:46 +00005749 // This transformation isn't valid for vector loads.
5750 if (VT.isVector())
5751 return SDValue();
5752
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005753 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005754 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005755 if (Opc == ISD::SIGN_EXTEND_INREG) {
5756 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005757 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005758 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005759 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005760 ExtType = ISD::ZEXTLOAD;
5761 N0 = SDValue(N, 0);
5762 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5763 if (!N01) return SDValue();
5764 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5765 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005766 }
Richard Osborne272e0842011-01-31 17:41:44 +00005767 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5768 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005769
Owen Anderson53aa7a92009-08-10 22:56:29 +00005770 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005771
Chris Lattner9a499e92010-12-22 08:01:44 +00005772 // Do not generate loads of non-round integer types since these can
5773 // be expensive (and would be wrong if the type is not byte sized).
5774 if (!ExtVT.isRound())
5775 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005776
Evan Cheng464dc9b2007-03-22 01:54:19 +00005777 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005778 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005779 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005780 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005781 // Is the shift amount a multiple of size of VT?
5782 if ((ShAmt & (EVTBits-1)) == 0) {
5783 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005784 // Is the load width a multiple of size of VT?
5785 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005786 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005787 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005788
Chris Lattnercafc1e62010-12-22 08:02:57 +00005789 // At this point, we must have a load or else we can't do the transform.
5790 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005791
Chandler Carruthb27041c2012-12-11 00:36:57 +00005792 // Because a SRL must be assumed to *need* to zero-extend the high bits
5793 // (as opposed to anyext the high bits), we can't combine the zextload
5794 // lowering of SRL and an sextload.
5795 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5796 return SDValue();
5797
Chris Lattnera2050552010-10-01 05:36:09 +00005798 // If the shift amount is larger than the input type then we're not
5799 // accessing any of the loaded bytes. If the load was a zextload/extload
5800 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005801 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005802 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005803 }
5804 }
5805
Dan Gohman68fb0042010-11-03 01:47:46 +00005806 // If the load is shifted left (and the result isn't shifted back right),
5807 // we can fold the truncate through the shift.
5808 unsigned ShLeftAmt = 0;
5809 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005810 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005811 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5812 ShLeftAmt = N01->getZExtValue();
5813 N0 = N0.getOperand(0);
5814 }
5815 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005816
Chris Lattner222374d2010-12-22 07:36:50 +00005817 // If we haven't found a load, we can't narrow it. Don't transform one with
5818 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005819 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5820 return SDValue();
5821
5822 // Don't change the width of a volatile load.
5823 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5824 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005825 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005826
Chris Lattner9a499e92010-12-22 08:01:44 +00005827 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005828 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005829 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005830
Bill Schmidtd006c692013-01-14 22:04:38 +00005831 // For the transform to be legal, the load must produce only two values
5832 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005833 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005834 // transformation is not equivalent, and the downstream logic to replace
5835 // uses gets things wrong.
5836 if (LN0->getNumValues() > 2)
5837 return SDValue();
5838
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005839 // If the load that we're shrinking is an extload and we're not just
5840 // discarding the extension we can't simply shrink the load. Bail.
5841 // TODO: It would be possible to merge the extensions in some cases.
5842 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5843 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5844 return SDValue();
5845
Chris Lattner222374d2010-12-22 07:36:50 +00005846 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005847
Evan Cheng4c6f9172012-06-26 01:19:33 +00005848 if (PtrType == MVT::Untyped || PtrType.isExtended())
5849 // It's not possible to generate a constant of extended or untyped type.
5850 return SDValue();
5851
Chris Lattner222374d2010-12-22 07:36:50 +00005852 // For big endian targets, we need to adjust the offset to the pointer to
5853 // load the correct bytes.
5854 if (TLI.isBigEndian()) {
5855 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5856 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5857 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005858 }
5859
Chris Lattner222374d2010-12-22 07:36:50 +00005860 uint64_t PtrOff = ShAmt / 8;
5861 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005862 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005863 PtrType, LN0->getBasePtr(),
5864 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005865 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00005866
Chris Lattner9a499e92010-12-22 08:01:44 +00005867 SDValue Load;
5868 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005869 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005870 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005871 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00005872 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005873 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005874 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005875 LN0->getPointerInfo().getWithOffset(PtrOff),
5876 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00005877 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005878
5879 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005880 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005881 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005882
5883 // Shift the result left, if we've swallowed a left shift.
5884 SDValue Result = Load;
5885 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005886 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005887 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5888 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005889 // If the shift amount is as large as the result size (but, presumably,
5890 // no larger than the source) then the useful bits of the result are
5891 // zero; we can't simply return the shortened shift, because the result
5892 // of that operation is undefined.
5893 if (ShLeftAmt >= VT.getSizeInBits())
5894 Result = DAG.getConstant(0, VT);
5895 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005896 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005897 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005898 }
5899
5900 // Return the new loaded value.
5901 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005902}
5903
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005904SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5905 SDValue N0 = N->getOperand(0);
5906 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005907 EVT VT = N->getValueType(0);
5908 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005909 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005910 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005911
Nate Begeman21158fc2005-09-01 00:19:25 +00005912 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005913 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005914 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005915
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005916 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005917 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005918 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005919
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005920 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5921 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005922 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005923 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005924 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005925
Dan Gohman345d63c2008-07-31 00:50:31 +00005926 // fold (sext_in_reg (sext x)) -> (sext x)
5927 // fold (sext_in_reg (aext x)) -> (sext x)
5928 // if x is small enough.
5929 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5930 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005931 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5932 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005933 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005934 }
5935
Chris Lattner9ad59152007-04-17 19:03:21 +00005936 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005937 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005938 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005939
Chris Lattner9ad59152007-04-17 19:03:21 +00005940 // fold operands of sext_in_reg based on knowledge that the top bits are not
5941 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005942 if (SimplifyDemandedBits(SDValue(N, 0)))
5943 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005944
Evan Cheng464dc9b2007-03-22 01:54:19 +00005945 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5946 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005947 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005948 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005949 return NarrowLoad;
5950
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005951 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005952 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005953 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5954 if (N0.getOpcode() == ISD::SRL) {
5955 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005956 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005957 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005958 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005959 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005960 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005961 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005962 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005963 }
5964 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005965
Nate Begeman02b23c62005-10-13 03:11:28 +00005966 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005967 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005968 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005969 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005970 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005971 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005972 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005973 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005974 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005975 LN0->getBasePtr(), EVT,
5976 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005977 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005978 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005979 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005980 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005981 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005982 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005983 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005984 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005985 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005986 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005987 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005988 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005989 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005990 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005991 LN0->getBasePtr(), EVT,
5992 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005993 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005994 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005995 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005996 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005997
5998 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5999 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6000 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6001 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006002 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006003 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006004 BSwap, N1);
6005 }
6006
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006007 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6008 // into a build_vector.
6009 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6010 SmallVector<SDValue, 8> Elts;
6011 unsigned NumElts = N0->getNumOperands();
6012 unsigned ShAmt = VTBits - EVTBits;
6013
6014 for (unsigned i = 0; i != NumElts; ++i) {
6015 SDValue Op = N0->getOperand(i);
6016 if (Op->getOpcode() == ISD::UNDEF) {
6017 Elts.push_back(Op);
6018 continue;
6019 }
6020
6021 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006022 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6023 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006024 Op.getValueType()));
6025 }
6026
Craig Topper48d114b2014-04-26 18:35:24 +00006027 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006028 }
6029
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006030 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006031}
6032
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006033SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6034 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006035 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006036 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006037
6038 // noop truncate
6039 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006040 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006041 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006042 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006043 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006044 // fold (truncate (truncate x)) -> (truncate x)
6045 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006046 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006047 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006048 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6049 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006050 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006051 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006052 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006053 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006054 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006055 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006056 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006057 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006058 // if the source and dest are the same type, we can drop both the extend
6059 // and the truncate.
6060 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006061 }
Evan Chengd63baea2007-03-21 20:14:05 +00006062
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006063 // Fold extract-and-trunc into a narrow extract. For example:
6064 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6065 // i32 y = TRUNCATE(i64 x)
6066 // -- becomes --
6067 // v16i8 b = BITCAST (v2i64 val)
6068 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6069 //
6070 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006071 // creates this pattern) and before operation legalization after which
6072 // we need to be more careful about the vector instructions that we generate.
6073 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006074 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006075
6076 EVT VecTy = N0.getOperand(0).getValueType();
6077 EVT ExTy = N0.getValueType();
6078 EVT TrTy = N->getValueType(0);
6079
6080 unsigned NumElem = VecTy.getVectorNumElements();
6081 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6082
6083 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6084 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6085
6086 SDValue EltNo = N0->getOperand(1);
6087 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6088 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006089 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006090 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6091
Andrew Trickef9de2a2013-05-25 02:42:55 +00006092 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006093 NVT, N0.getOperand(0));
6094
6095 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006096 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006097 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006098 }
6099 }
6100
Matt Arsenault3332b702014-07-10 18:21:04 +00006101 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6102 if (N0.getOpcode() == ISD::SELECT) {
6103 EVT SrcVT = N0.getValueType();
6104 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6105 TLI.isTruncateFree(SrcVT, VT)) {
6106 SDLoc SL(N0);
6107 SDValue Cond = N0.getOperand(0);
6108 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6109 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6110 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6111 }
6112 }
6113
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006114 // Fold a series of buildvector, bitcast, and truncate if possible.
6115 // For example fold
6116 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6117 // (2xi32 (buildvector x, y)).
6118 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6119 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6120 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6121 N0.getOperand(0).hasOneUse()) {
6122
6123 SDValue BuildVect = N0.getOperand(0);
6124 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6125 EVT TruncVecEltTy = VT.getVectorElementType();
6126
6127 // Check that the element types match.
6128 if (BuildVectEltTy == TruncVecEltTy) {
6129 // Now we only need to compute the offset of the truncated elements.
6130 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6131 unsigned TruncVecNumElts = VT.getVectorNumElements();
6132 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6133
6134 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6135 "Invalid number of elements");
6136
6137 SmallVector<SDValue, 8> Opnds;
6138 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6139 Opnds.push_back(BuildVect.getOperand(i));
6140
Craig Topper48d114b2014-04-26 18:35:24 +00006141 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006142 }
6143 }
6144
Chris Lattner5e6fe052007-10-13 06:35:54 +00006145 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006146 // only the low bits are being used.
6147 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006148 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006149 // may have different active low bits.
6150 if (!VT.isVector()) {
6151 SDValue Shorter =
6152 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6153 VT.getSizeInBits()));
6154 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006155 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006156 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006157 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006158 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006159 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6160 SDValue Reduced = ReduceLoadWidth(N);
6161 if (Reduced.getNode())
6162 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006163 // Handle the case where the load remains an extending load even
6164 // after truncation.
6165 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6166 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6167 if (!LN0->isVolatile() &&
6168 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6169 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6170 VT, LN0->getChain(), LN0->getBasePtr(),
6171 LN0->getMemoryVT(),
6172 LN0->getMemOperand());
6173 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6174 return NewLoad;
6175 }
6176 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006177 }
Michael Liao3ac82012012-10-17 23:45:54 +00006178 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6179 // where ... are all 'undef'.
6180 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6181 SmallVector<EVT, 8> VTs;
6182 SDValue V;
6183 unsigned Idx = 0;
6184 unsigned NumDefs = 0;
6185
6186 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6187 SDValue X = N0.getOperand(i);
6188 if (X.getOpcode() != ISD::UNDEF) {
6189 V = X;
6190 Idx = i;
6191 NumDefs++;
6192 }
6193 // Stop if more than one members are non-undef.
6194 if (NumDefs > 1)
6195 break;
6196 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6197 VT.getVectorElementType(),
6198 X.getValueType().getVectorNumElements()));
6199 }
6200
6201 if (NumDefs == 0)
6202 return DAG.getUNDEF(VT);
6203
6204 if (NumDefs == 1) {
6205 assert(V.getNode() && "The single defined operand is empty!");
6206 SmallVector<SDValue, 8> Opnds;
6207 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6208 if (i != Idx) {
6209 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6210 continue;
6211 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006212 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006213 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006214 Opnds.push_back(NV);
6215 }
Craig Topper48d114b2014-04-26 18:35:24 +00006216 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006217 }
6218 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006219
6220 // Simplify the operands using demanded-bits information.
6221 if (!VT.isVector() &&
6222 SimplifyDemandedBits(SDValue(N, 0)))
6223 return SDValue(N, 0);
6224
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006225 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006226}
6227
Evan Chengb980f6f2008-05-12 23:04:07 +00006228static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006229 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006230 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006231 return Elt.getNode();
6232 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006233}
6234
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006235/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006236/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006237SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006238 assert(N->getOpcode() == ISD::BUILD_PAIR);
6239
Nate Begeman624690c2009-06-05 21:37:30 +00006240 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6241 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006242 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006243 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006244 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006245 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006246
Evan Chengb980f6f2008-05-12 23:04:07 +00006247 if (ISD::isNON_EXTLoad(LD2) &&
6248 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006249 // If both are volatile this would reduce the number of volatile loads.
6250 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006251 !LD1->isVolatile() &&
6252 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006253 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006254 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006255 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006256 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006257
Duncan Sands8651e9c2008-06-13 19:07:40 +00006258 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006259 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006260 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006261 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006262 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006263 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006264
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006265 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006266}
6267
Wesley Peck527da1b2010-11-23 03:31:01 +00006268SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006269 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006270 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006271
Dan Gohmana8665142007-06-25 16:23:39 +00006272 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6273 // Only do this before legalize, since afterward the target may be depending
6274 // on the bitconvert.
6275 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006276 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006277 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006278 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006279 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006280
Owen Anderson53aa7a92009-08-10 22:56:29 +00006281 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006282 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006283 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006284 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006285 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006286 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006287
Dan Gohman921ddd62008-09-05 01:58:21 +00006288 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006289 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006290 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006291 if (Res.getNode() != N) {
6292 if (!LegalOperations ||
6293 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6294 return Res;
6295
6296 // Folding it resulted in an illegal node, and it's too late to
6297 // do that. Clean up the old node and forego the transformation.
6298 // Ideally this won't happen very often, because instcombine
6299 // and the earlier dagcombine runs (where illegal nodes are
6300 // permitted) should have folded most of them already.
Chandler Carruth18066972014-08-02 10:02:07 +00006301 deleteAndRecombine(Res.getNode());
Dan Gohman733a64d2009-08-10 23:15:10 +00006302 }
Chris Lattnera1874602005-12-23 05:30:37 +00006303 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006304
Bill Wendling4e0a6152009-01-30 22:44:24 +00006305 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006306 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006307 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006308 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006309
Chris Lattner54560f62005-12-23 05:44:41 +00006310 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006311 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006312 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006313 // Do not change the width of a volatile load.
6314 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006315 // Do not remove the cast if the types differ in endian layout.
6316 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6317 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006318 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6319 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006320 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006321 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006322 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006323 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006324
Evan Chenga4cf58a2007-05-07 21:27:48 +00006325 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006326 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006327 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006328 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006329 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006330 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006331 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006332 return Load;
6333 }
Chris Lattner54560f62005-12-23 05:44:41 +00006334 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006335
Bill Wendling4e0a6152009-01-30 22:44:24 +00006336 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6337 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006338 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006339 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6340 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006341 N0.getNode()->hasOneUse() && VT.isInteger() &&
6342 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006343 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006344 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006345 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006346
Duncan Sands13237ac2008-06-06 12:08:01 +00006347 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006348 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006349 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006350 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006351 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006352 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006353 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006354 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006355
Bill Wendling4e0a6152009-01-30 22:44:24 +00006356 // fold (bitconvert (fcopysign cst, x)) ->
6357 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6358 // Note that we don't handle (copysign x, cst) because this can always be
6359 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006360 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006361 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006362 VT.isInteger() && !VT.isVector()) {
6363 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006364 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006365 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006366 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006367 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006368 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006369
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006370 // If X has a different width than the result/lhs, sext it or truncate it.
6371 unsigned VTWidth = VT.getSizeInBits();
6372 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006373 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006374 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006375 } else if (OrigXWidth > VTWidth) {
6376 // To get the sign bit in the right place, we have to shift it right
6377 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006378 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006379 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006380 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006381 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006382 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006383 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006384 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006385
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006386 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006387 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006388 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006389 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006390
Andrew Trickef9de2a2013-05-25 02:42:55 +00006391 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006392 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006393 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006394 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006395 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006396
Andrew Trickef9de2a2013-05-25 02:42:55 +00006397 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006398 }
Chris Lattner888560d2008-01-27 17:42:27 +00006399 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006400
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006401 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006402 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006403 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6404 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006405 return CombineLD;
6406 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006407
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006408 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006409}
6410
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006411SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006412 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006413 return CombineConsecutiveLoads(N, VT);
6414}
6415
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006416/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6417/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006418SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006419ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006420 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006421
Chris Lattnere4e64b62006-04-02 02:53:43 +00006422 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006423 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006424
Duncan Sands13237ac2008-06-06 12:08:01 +00006425 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6426 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006427
Chris Lattnere4e64b62006-04-02 02:53:43 +00006428 // If this is a conversion of N elements of one type to N elements of another
6429 // type, convert each element. This handles FP<->INT cases.
6430 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006431 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6432 BV->getValueType(0).getVectorNumElements());
6433
6434 // Due to the FP element handling below calling this routine recursively,
6435 // we can end up with a scalar-to-vector node here.
6436 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006437 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6438 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006439 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006440
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006441 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006442 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006443 SDValue Op = BV->getOperand(i);
6444 // If the vector element type is not legal, the BUILD_VECTOR operands
6445 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006446 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006447 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6448 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006449 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006450 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006451 }
Craig Topper48d114b2014-04-26 18:35:24 +00006452 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006453 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006454
Chris Lattnere4e64b62006-04-02 02:53:43 +00006455 // Otherwise, we're growing or shrinking the elements. To avoid having to
6456 // handle annoying details of growing/shrinking FP values, we convert them to
6457 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006458 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006459 // Convert the input float vector to a int vector where the elements are the
6460 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006461 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006462 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006463 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006464 SrcEltVT = IntVT;
6465 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006466
Chris Lattnere4e64b62006-04-02 02:53:43 +00006467 // Now we know the input is an integer vector. If the output is a FP type,
6468 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006469 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006470 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006471 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006472 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006473
Chris Lattnere4e64b62006-04-02 02:53:43 +00006474 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006475 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006476 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006477
Chris Lattnere4e64b62006-04-02 02:53:43 +00006478 // Okay, we know the src/dst types are both integers of differing types.
6479 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006480 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006481 if (SrcBitSize < DstBitSize) {
6482 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006483
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006484 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006485 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006486 i += NumInputsPerOutput) {
6487 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006488 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006489 bool EltIsUndef = true;
6490 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6491 // Shift the previously computed bits over.
6492 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006493 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006494 if (Op.getOpcode() == ISD::UNDEF) continue;
6495 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006496
Jay Foad583abbc2010-12-07 08:25:19 +00006497 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006498 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006499 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006500
Chris Lattnere4e64b62006-04-02 02:53:43 +00006501 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006502 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006503 else
6504 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6505 }
6506
Owen Anderson117c9e82009-08-12 00:36:31 +00006507 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006508 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006509 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006510
Chris Lattnere4e64b62006-04-02 02:53:43 +00006511 // Finally, this must be the case where we are shrinking elements: each input
6512 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006513 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006514 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006515 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6516 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006517 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006518
Dan Gohmana8665142007-06-25 16:23:39 +00006519 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006520 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6521 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006522 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006523 continue;
6524 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006525
Jay Foad583abbc2010-12-07 08:25:19 +00006526 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6527 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006528
Chris Lattnere4e64b62006-04-02 02:53:43 +00006529 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006530 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006531 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006532 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006533 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006534 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006535 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006536 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006537 }
6538
6539 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006540 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006541 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6542 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006543
Craig Topper48d114b2014-04-26 18:35:24 +00006544 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006545}
6546
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006547SDValue DAGCombiner::visitFADD(SDNode *N) {
6548 SDValue N0 = N->getOperand(0);
6549 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006550 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6551 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006552 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006553 const TargetOptions &Options = DAG.getTarget().Options;
Sanjay Patel159f1272014-08-27 21:42:42 +00006554
Dan Gohmana8665142007-06-25 16:23:39 +00006555 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006556 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006557 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006558 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006559 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006560
Lang Hamesa33db652012-06-14 20:37:15 +00006561 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006562 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006563 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006564 // canonicalize constant to RHS
6565 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006566 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006567 // fold (fadd A, 0) -> A
Sanjay Patel78614bf2014-08-28 15:53:16 +00006568 if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006569 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006570 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006571 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel78614bf2014-08-28 15:53:16 +00006572 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006573 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006574 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006575 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006576 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel78614bf2014-08-28 15:53:16 +00006577 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006578 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006579 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006580
Chris Lattner0199fd62007-01-08 23:04:05 +00006581 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006582 if (Options.UnsafeFPMath && N1CFP &&
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006583 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6584 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006585 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6586 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006587 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006588
Shuxin Yang93b1f122013-03-25 22:52:29 +00006589 // No FP constant should be created after legalization as Instruction
6590 // Selection pass has hard time in dealing with FP constant.
6591 //
6592 // We don't need test this condition for transformation like following, as
6593 // the DAG being transformed implies it is legal to take FP constant as
6594 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006595 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006596 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006597 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006598 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6599
Owen Andersonb351c8d2012-11-01 02:00:53 +00006600 // If allow, fold (fadd (fneg x), x) -> 0.0
Sanjay Patel78614bf2014-08-28 15:53:16 +00006601 if (AllowNewFpConst && Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006602 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006603 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006604
Sanjay Patel159f1272014-08-27 21:42:42 +00006605 // If allow, fold (fadd x, (fneg x)) -> 0.0
Sanjay Patel78614bf2014-08-28 15:53:16 +00006606 if (AllowNewFpConst && Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006607 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006608 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006609
Owen Andersoncc61f872012-08-30 23:35:16 +00006610 // In unsafe math mode, we can fold chains of FADD's of the same value
6611 // into multiplications. This transform is not safe in general because
6612 // we are reducing the number of rounding steps.
Sanjay Patel78614bf2014-08-28 15:53:16 +00006613 if (Options.UnsafeFPMath && TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006614 !N0CFP && !N1CFP) {
6615 if (N0.getOpcode() == ISD::FMUL) {
6616 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6617 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6618
Stephen Line31f2d22013-06-14 18:17:35 +00006619 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006620 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006621 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006622 SDValue(CFP00, 0),
6623 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006624 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006625 N1, NewCFP);
6626 }
6627
Stephen Line31f2d22013-06-14 18:17:35 +00006628 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006629 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006630 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006631 SDValue(CFP01, 0),
6632 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006633 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006634 N1, NewCFP);
6635 }
6636
Stephen Line31f2d22013-06-14 18:17:35 +00006637 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006638 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6639 N1.getOperand(0) == N1.getOperand(1) &&
6640 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006641 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006642 SDValue(CFP00, 0),
6643 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006644 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006645 N0.getOperand(1), NewCFP);
6646 }
6647
Stephen Line31f2d22013-06-14 18:17:35 +00006648 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006649 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6650 N1.getOperand(0) == N1.getOperand(1) &&
6651 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006652 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006653 SDValue(CFP01, 0),
6654 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006655 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006656 N0.getOperand(0), NewCFP);
6657 }
6658 }
6659
6660 if (N1.getOpcode() == ISD::FMUL) {
6661 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6662 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6663
Stephen Line31f2d22013-06-14 18:17:35 +00006664 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006665 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006666 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006667 SDValue(CFP10, 0),
6668 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006669 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006670 N0, NewCFP);
6671 }
6672
Stephen Line31f2d22013-06-14 18:17:35 +00006673 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006674 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006675 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006676 SDValue(CFP11, 0),
6677 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006678 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006679 N0, NewCFP);
6680 }
6681
Owen Andersoncc61f872012-08-30 23:35:16 +00006682
Stephen Line31f2d22013-06-14 18:17:35 +00006683 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6684 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6685 N0.getOperand(0) == N0.getOperand(1) &&
6686 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006687 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006688 SDValue(CFP10, 0),
6689 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006690 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006691 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006692 }
6693
Stephen Line31f2d22013-06-14 18:17:35 +00006694 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6695 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6696 N0.getOperand(0) == N0.getOperand(1) &&
6697 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006698 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006699 SDValue(CFP11, 0),
6700 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006701 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006702 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006703 }
6704 }
6705
Shuxin Yang93b1f122013-03-25 22:52:29 +00006706 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006707 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006708 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006709 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006710 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006711 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006712 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006713 }
6714
Shuxin Yang93b1f122013-03-25 22:52:29 +00006715 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006716 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006717 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006718 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006719 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006720 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006721 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006722 }
6723
Stephen Lin4e69d012013-06-14 21:33:58 +00006724 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006725 if (AllowNewFpConst &&
6726 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006727 N0.getOperand(0) == N0.getOperand(1) &&
6728 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006729 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006730 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006731 N0.getOperand(0),
6732 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006733 }
6734
Lang Hames39fb1d02012-06-19 22:51:23 +00006735 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006736 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherd9134482014-08-04 21:25:23 +00006737 DAG.getTarget()
6738 .getSubtargetImpl()
6739 ->getTargetLowering()
6740 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006741 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006742
6743 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006744 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006745 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006746 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006747
Michael Liaoec3850122012-09-01 04:09:16 +00006748 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006749 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006750 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006751 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006752 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006753 }
6754
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006755 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006756}
6757
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006758SDValue DAGCombiner::visitFSUB(SDNode *N) {
6759 SDValue N0 = N->getOperand(0);
6760 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006761 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6762 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006763 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006764 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006765 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006766
Dan Gohmana8665142007-06-25 16:23:39 +00006767 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006768 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006769 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006770 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006771 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006772
Nate Begeman418c6e42005-10-18 00:28:13 +00006773 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006774 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006775 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00006776
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006777 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006778 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006779 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006780 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006781
Sanjay Patelae402a32014-08-27 20:57:52 +00006782 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00006783 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00006784 // (fsub A, 0) -> A
6785 if (N1CFP && N1CFP->getValueAPF().isZero())
6786 return N0;
6787
6788 // (fsub 0, B) -> -B
6789 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00006790 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00006791 return GetNegatedExpression(N1, DAG, LegalOperations);
6792 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6793 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6794 }
6795
6796 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00006797 if (N0 == N1)
6798 return DAG.getConstantFP(0.0f, VT);
6799
Sanjay Patelae402a32014-08-27 20:57:52 +00006800 // (fsub x, (fadd x, y)) -> (fneg y)
6801 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00006802 if (N1.getOpcode() == ISD::FADD) {
6803 SDValue N10 = N1->getOperand(0);
6804 SDValue N11 = N1->getOperand(1);
6805
Sanjay Patel78614bf2014-08-28 15:53:16 +00006806 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006807 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006808
Sanjay Patel78614bf2014-08-28 15:53:16 +00006809 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006810 return GetNegatedExpression(N10, DAG, LegalOperations);
6811 }
6812 }
6813
Lang Hames39fb1d02012-06-19 22:51:23 +00006814 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006815 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Sanjay Patela828f2b2014-08-27 20:40:31 +00006816 DAG.getTarget().getSubtargetImpl()
Eric Christopherd9134482014-08-04 21:25:23 +00006817 ->getTargetLowering()
6818 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006819 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006820
6821 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006822 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006823 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006824 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006825 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006826
6827 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6828 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006829 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006830 return DAG.getNode(ISD::FMA, dl, VT,
6831 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006832 N1.getOperand(0)),
6833 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006834
Stephen Lin8e8424e2013-07-09 00:44:49 +00006835 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006836 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006837 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6838 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6839 SDValue N00 = N0.getOperand(0).getOperand(0);
6840 SDValue N01 = N0.getOperand(0).getOperand(1);
6841 return DAG.getNode(ISD::FMA, dl, VT,
6842 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6843 DAG.getNode(ISD::FNEG, dl, VT, N1));
6844 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006845 }
6846
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006847 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006848}
6849
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006850SDValue DAGCombiner::visitFMUL(SDNode *N) {
6851 SDValue N0 = N->getOperand(0);
6852 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00006853 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6854 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006855 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006856 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006857
Dan Gohmana8665142007-06-25 16:23:39 +00006858 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006859 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006860 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006861 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006862 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006863
Nate Begemanec48a1b2005-10-17 20:40:11 +00006864 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006865 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006866 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006867 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006868 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006869 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006870 // fold (fmul A, 0) -> 0
Sanjay Patel78614bf2014-08-28 15:53:16 +00006871 if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006872 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006873 // fold (fmul A, 1.0) -> A
6874 if (N1CFP && N1CFP->isExactlyValue(1.0))
6875 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00006876
Nate Begemanec48a1b2005-10-17 20:40:11 +00006877 // fold (fmul X, 2.0) -> (fadd X, X)
6878 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006879 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006880 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006881 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006882 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006883 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006884
Bill Wendling3dc5d242009-01-30 22:57:07 +00006885 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006886 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6887 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006888 // Both can be negated for free, check to see if at least one is cheaper
6889 // negated.
6890 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006891 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006892 GetNegatedExpression(N0, DAG, LegalOperations),
6893 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006894 }
6895 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006896
Chris Lattner0199fd62007-01-08 23:04:05 +00006897 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006898 if (Options.UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
Matt Arsenault6cc00422014-08-16 10:14:19 +00006899 N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006900 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6901 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006902 N0.getOperand(1), N1));
Matt Arsenault6cc00422014-08-16 10:14:19 +00006903 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006904
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006905 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006906}
6907
Owen Anderson41b06652012-05-02 22:17:40 +00006908SDValue DAGCombiner::visitFMA(SDNode *N) {
6909 SDValue N0 = N->getOperand(0);
6910 SDValue N1 = N->getOperand(1);
6911 SDValue N2 = N->getOperand(2);
6912 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6913 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6914 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006915 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006916 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00006917
6918 // Constant fold FMA.
6919 if (isa<ConstantFPSDNode>(N0) &&
6920 isa<ConstantFPSDNode>(N1) &&
6921 isa<ConstantFPSDNode>(N2)) {
6922 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6923 }
6924
Sanjay Patel78614bf2014-08-28 15:53:16 +00006925 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00006926 if (N0CFP && N0CFP->isZero())
6927 return N2;
6928 if (N1CFP && N1CFP->isZero())
6929 return N2;
6930 }
Owen Anderson41b06652012-05-02 22:17:40 +00006931 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006932 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006933 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006934 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006935
Owen Andersonc7aaf522012-05-30 18:50:39 +00006936 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006937 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006938 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006939
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006940 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006941 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006942 N2.getOpcode() == ISD::FMUL &&
6943 N0 == N2.getOperand(0) &&
6944 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6945 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6946 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6947 }
6948
6949
6950 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006951 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006952 N0.getOpcode() == ISD::FMUL && N1CFP &&
6953 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6954 return DAG.getNode(ISD::FMA, dl, VT,
6955 N0.getOperand(0),
6956 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6957 N2);
6958 }
6959
6960 // (fma x, 1, y) -> (fadd x, y)
6961 // (fma x, -1, y) -> (fadd (fneg x), y)
6962 if (N1CFP) {
6963 if (N1CFP->isExactlyValue(1.0))
6964 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6965
6966 if (N1CFP->isExactlyValue(-1.0) &&
6967 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6968 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006969 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006970 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6971 }
6972 }
6973
6974 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006975 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006976 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006977 DAG.getNode(ISD::FADD, dl, VT,
6978 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006979
6980 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006981 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006982 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6983 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006984 DAG.getNode(ISD::FADD, dl, VT,
6985 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006986
6987
Owen Anderson41b06652012-05-02 22:17:40 +00006988 return SDValue();
6989}
6990
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006991SDValue DAGCombiner::visitFDIV(SDNode *N) {
6992 SDValue N0 = N->getOperand(0);
6993 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006994 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6995 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006996 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006997 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006998
Dan Gohmana8665142007-06-25 16:23:39 +00006999 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007000 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007001 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007002 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007003 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007004
Nate Begeman569c4392006-01-18 22:35:16 +00007005 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007006 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007007 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007008
Duncan Sands2f1dc382012-04-08 18:08:12 +00007009 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007010 if (N1CFP && Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00007011 // Compute the reciprocal 1.0 / c2.
7012 APFloat N1APF = N1CFP->getValueAPF();
7013 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7014 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00007015 // Only do the transform if the reciprocal is a legal fp immediate that
7016 // isn't too nasty (eg NaN, denormal, ...).
7017 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00007018 (!LegalOperations ||
7019 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7020 // backend)... we should handle this gracefully after Legalize.
7021 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7022 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7023 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007024 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00007025 DAG.getConstantFP(Recip, VT));
7026 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007027
Bill Wendling3dc5d242009-01-30 22:57:07 +00007028 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007029 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7030 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007031 // Both can be negated for free, check to see if at least one is cheaper
7032 // negated.
7033 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007034 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007035 GetNegatedExpression(N0, DAG, LegalOperations),
7036 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007037 }
7038 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007039
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007040 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007041}
7042
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007043SDValue DAGCombiner::visitFREM(SDNode *N) {
7044 SDValue N0 = N->getOperand(0);
7045 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007046 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7047 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007048 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007049
Nate Begeman569c4392006-01-18 22:35:16 +00007050 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007051 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007052 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007053
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007054 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007055}
7056
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007057SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7058 SDValue N0 = N->getOperand(0);
7059 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007060 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7061 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007062 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007063
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007064 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007065 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007066
Chris Lattner3bc40502006-03-05 05:30:57 +00007067 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007068 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007069 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7070 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007071 if (!V.isNegative()) {
7072 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007073 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007074 } else {
7075 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007076 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7077 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007078 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007079 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007080
Chris Lattner3bc40502006-03-05 05:30:57 +00007081 // copysign(fabs(x), y) -> copysign(x, y)
7082 // copysign(fneg(x), y) -> copysign(x, y)
7083 // copysign(copysign(x,z), y) -> copysign(x, y)
7084 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7085 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007086 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007087 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007088
7089 // copysign(x, abs(y)) -> abs(x)
7090 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007091 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007092
Chris Lattner3bc40502006-03-05 05:30:57 +00007093 // copysign(x, copysign(y,z)) -> copysign(x, z)
7094 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007095 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007096 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007097
Chris Lattner3bc40502006-03-05 05:30:57 +00007098 // copysign(x, fp_extend(y)) -> copysign(x, y)
7099 // copysign(x, fp_round(y)) -> copysign(x, y)
7100 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007101 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007102 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007103
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007104 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007105}
7106
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007107SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007109 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007110 EVT VT = N->getValueType(0);
7111 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007112
Nate Begeman21158fc2005-09-01 00:19:25 +00007113 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007114 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007115 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007116 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007117 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007118 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007119
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007120 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7121 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007122 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7123 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007124 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007125 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007126 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007127 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007128
Alp Tokercb402912014-01-24 17:20:08 +00007129 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007130 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007131 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7132 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7133 !VT.isVector() &&
7134 (!LegalOperations ||
7135 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7136 SDValue Ops[] =
7137 { N0.getOperand(0), N0.getOperand(1),
7138 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7139 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007140 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007141 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007142
Nadav Rotem90560762012-07-23 07:59:50 +00007143 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7144 // (select_cc x, y, 1.0, 0.0,, cc)
7145 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7146 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7147 (!LegalOperations ||
7148 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7149 SDValue Ops[] =
7150 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7151 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7152 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007153 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007154 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007155 }
7156
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007157 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007158}
7159
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007160SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7161 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007162 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007163 EVT VT = N->getValueType(0);
7164 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007165
Nate Begeman21158fc2005-09-01 00:19:25 +00007166 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007167 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007168 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007169 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007170 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007171 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007172
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007173 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7174 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007175 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7176 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007177 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007178 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007179 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007180 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007181
Alp Tokercb402912014-01-24 17:20:08 +00007182 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007183 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007184 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007185
Nadav Rotem90560762012-07-23 07:59:50 +00007186 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7187 (!LegalOperations ||
7188 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7189 SDValue Ops[] =
7190 { N0.getOperand(0), N0.getOperand(1),
7191 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7192 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007193 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007194 }
7195 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007196
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007197 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007198}
7199
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007200SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7201 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007202 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007203 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007204
Nate Begeman21158fc2005-09-01 00:19:25 +00007205 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007206 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007207 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007208
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007209 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007210}
7211
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007212SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7213 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007214 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007215 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007216
Nate Begeman21158fc2005-09-01 00:19:25 +00007217 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007218 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007219 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007220
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007221 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007222}
7223
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007224SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7225 SDValue N0 = N->getOperand(0);
7226 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007227 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007228 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007229
Nate Begeman21158fc2005-09-01 00:19:25 +00007230 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007231 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007232 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007233
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007234 // fold (fp_round (fp_extend x)) -> x
7235 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7236 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007237
Chris Lattner0feb1b02008-01-24 06:45:35 +00007238 // fold (fp_round (fp_round x)) -> (fp_round x)
7239 if (N0.getOpcode() == ISD::FP_ROUND) {
7240 // This is a value preserving truncation if both round's are.
7241 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007242 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007243 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007244 DAG.getIntPtrConstant(IsTrunc));
7245 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007246
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007247 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007248 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007249 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007250 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007251 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007252 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007253 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007254 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007255
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007256 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007257}
7258
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007259SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7260 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007261 EVT VT = N->getValueType(0);
7262 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007263 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007264
Nate Begeman21158fc2005-09-01 00:19:25 +00007265 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007266 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007267 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007268 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007269 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007270
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007271 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007272}
7273
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007274SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7275 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007276 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007277 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007278
Chris Lattner5919b482007-12-29 06:55:23 +00007279 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007280 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007281 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007282 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007283
Nate Begeman21158fc2005-09-01 00:19:25 +00007284 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007285 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007286 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007287
7288 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7289 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007290 if (N0.getOpcode() == ISD::FP_ROUND
7291 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007292 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007293 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007294 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007295 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007296 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007297 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007298 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007299
Chris Lattner72733e52008-01-17 07:00:52 +00007300 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007301 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007302 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007303 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007304 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007305 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007306 LN0->getBasePtr(), N0.getValueType(),
7307 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007308 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007309 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007310 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007311 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007312 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007313 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007314 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007315
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007316 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007317}
7318
Sanjay Patelccd26762014-08-28 21:51:37 +00007319SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7320 SDValue N0 = N->getOperand(0);
7321 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7322 EVT VT = N->getValueType(0);
7323
7324 // fold (fceil c1) -> fceil(c1)
7325 if (N0CFP)
7326 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7327
7328 return SDValue();
7329}
7330
7331SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7332 SDValue N0 = N->getOperand(0);
7333 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7334 EVT VT = N->getValueType(0);
7335
7336 // fold (ftrunc c1) -> ftrunc(c1)
7337 if (N0CFP)
7338 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7339
7340 return SDValue();
7341}
7342
7343SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7344 SDValue N0 = N->getOperand(0);
7345 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7346 EVT VT = N->getValueType(0);
7347
7348 // fold (ffloor c1) -> ffloor(c1)
7349 if (N0CFP)
7350 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7351
7352 return SDValue();
7353}
7354
7355// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007356SDValue DAGCombiner::visitFNEG(SDNode *N) {
7357 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007358 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007359
Craig Topper82384612012-09-11 01:45:21 +00007360 if (VT.isVector()) {
7361 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7362 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007363 }
7364
Sanjay Patelccd26762014-08-28 21:51:37 +00007365 // Constant fold FNEG.
7366 if (isa<ConstantFPSDNode>(N0))
7367 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7368
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007369 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7370 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007371 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007372
Sanjay Patel35d31332014-08-14 15:15:28 +00007373 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007374 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00007375 if (!TLI.isFNegFree(VT) &&
7376 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00007377 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007378 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007379 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007380 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00007381 APInt SignMask;
7382 if (N0.getValueType().isVector()) {
7383 // For a vector, get a mask such as 0x80... per scalar element
7384 // and splat it.
7385 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7386 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7387 } else {
7388 // For a scalar, just generate 0x80...
7389 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7390 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007391 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00007392 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007393 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00007394 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007395 }
7396 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007397
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007398 // (fneg (fmul c, x)) -> (fmul -c, x)
7399 if (N0.getOpcode() == ISD::FMUL) {
7400 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007401 if (CFP1) {
7402 APFloat CVal = CFP1->getValueAPF();
7403 CVal.changeSign();
7404 if (Level >= AfterLegalizeDAG &&
7405 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7406 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7407 return DAG.getNode(
7408 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7409 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7410 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007411 }
7412
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007413 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007414}
7415
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007416SDValue DAGCombiner::visitFABS(SDNode *N) {
7417 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007418 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007419
Craig Topper82384612012-09-11 01:45:21 +00007420 if (VT.isVector()) {
7421 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7422 if (FoldedVOp.getNode()) return FoldedVOp;
7423 }
7424
Nate Begeman21158fc2005-09-01 00:19:25 +00007425 // fold (fabs c1) -> fabs(c1)
Sanjay Patelccd26762014-08-28 21:51:37 +00007426 if (isa<ConstantFPSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007427 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007428
Nate Begeman21158fc2005-09-01 00:19:25 +00007429 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007430 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007431 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007432
Nate Begeman21158fc2005-09-01 00:19:25 +00007433 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007434 // fold (fabs (fcopysign x, y)) -> (fabs x)
7435 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007436 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007437
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007438 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007439 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007440 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007441 N0.getOpcode() == ISD::BITCAST &&
7442 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007443 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007444 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007445 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007446 APInt SignMask;
7447 if (N0.getValueType().isVector()) {
7448 // For a vector, get a mask such as 0x7f... per scalar element
7449 // and splat it.
7450 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7451 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7452 } else {
7453 // For a scalar, just generate 0x7f...
7454 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7455 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007456 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007457 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007458 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007459 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007460 }
7461 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007463 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007464}
7465
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007466SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7467 SDValue Chain = N->getOperand(0);
7468 SDValue N1 = N->getOperand(1);
7469 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007470
Dan Gohman82e80012009-11-17 00:47:23 +00007471 // If N is a constant we could fold this into a fallthrough or unconditional
7472 // branch. However that doesn't happen very often in normal code, because
7473 // Instcombine/SimplifyCFG should have handled the available opportunities.
7474 // If we did this folding here, it would be necessary to update the
7475 // MachineBasicBlock CFG, which is awkward.
7476
Nate Begeman7e7f4392006-02-01 07:19:44 +00007477 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7478 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007479 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007480 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7481 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007482 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007483 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007484 N1.getOperand(0), N1.getOperand(1), N2);
7485 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007486
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007487 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7488 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7489 (N1.getOperand(0).hasOneUse() &&
7490 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007491 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007492 if (N1.getOpcode() == ISD::TRUNCATE) {
7493 // Look pass the truncate.
7494 Trunc = N1.getNode();
7495 N1 = N1.getOperand(0);
7496 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007497
Bill Wendlingaa28be62009-03-26 06:14:09 +00007498 // Match this pattern so that we can generate simpler code:
7499 //
7500 // %a = ...
7501 // %b = and i32 %a, 2
7502 // %c = srl i32 %b, 1
7503 // brcond i32 %c ...
7504 //
7505 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007506 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007507 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007508 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007509 // %c = setcc eq %b, 0
7510 // brcond %c ...
7511 //
7512 // This applies only when the AND constant value has one bit set and the
7513 // SRL constant is equal to the log2 of the AND constant. The back-end is
7514 // smart enough to convert the result into a TEST/JMP sequence.
7515 SDValue Op0 = N1.getOperand(0);
7516 SDValue Op1 = N1.getOperand(1);
7517
7518 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007519 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007520 SDValue AndOp1 = Op0.getOperand(1);
7521
7522 if (AndOp1.getOpcode() == ISD::Constant) {
7523 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7524
7525 if (AndConst.isPowerOf2() &&
7526 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7527 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007528 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007529 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007530 Op0, DAG.getConstant(0, Op0.getValueType()),
7531 ISD::SETNE);
7532
Andrew Trickef9de2a2013-05-25 02:42:55 +00007533 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007534 MVT::Other, Chain, SetCC, N2);
7535 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7536 // will convert it back to (X & C1) >> C2.
7537 CombineTo(N, NewBRCond, false);
7538 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00007539 if (Trunc)
7540 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007541 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007542 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007543 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007544 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007545 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007546 }
7547 }
7548 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007549
7550 if (Trunc)
7551 // Restore N1 if the above transformation doesn't match.
7552 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007553 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007554
Evan Cheng228c31f2010-02-27 07:36:59 +00007555 // Transform br(xor(x, y)) -> br(x != y)
7556 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7557 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7558 SDNode *TheXor = N1.getNode();
7559 SDValue Op0 = TheXor->getOperand(0);
7560 SDValue Op1 = TheXor->getOperand(1);
7561 if (Op0.getOpcode() == Op1.getOpcode()) {
7562 // Avoid missing important xor optimizations.
7563 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007564 if (Tmp.getNode()) {
7565 if (Tmp.getNode() != TheXor) {
7566 DEBUG(dbgs() << "\nReplacing.8 ";
7567 TheXor->dump(&DAG);
7568 dbgs() << "\nWith: ";
7569 Tmp.getNode()->dump(&DAG);
7570 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007571 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007572 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00007573 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007574 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007575 MVT::Other, Chain, Tmp, N2);
7576 }
7577
Benjamin Kramer93354432013-03-30 21:28:18 +00007578 // visitXOR has changed XOR's operands or replaced the XOR completely,
7579 // bail out.
7580 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007581 }
7582 }
7583
7584 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7585 bool Equal = false;
7586 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7587 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7588 Op0.getOpcode() == ISD::XOR) {
7589 TheXor = Op0.getNode();
7590 Equal = true;
7591 }
7592
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007593 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007594 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007595 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007596 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007597 SetCCVT,
7598 Op0, Op1,
7599 Equal ? ISD::SETEQ : ISD::SETNE);
7600 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007601 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007602 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007603 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007604 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007605 MVT::Other, Chain, SetCC, N2);
7606 }
7607 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007608
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007609 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007610}
7611
Chris Lattnera49e16f2005-10-05 06:47:48 +00007612// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7613//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007614SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007615 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007616 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007617
Dan Gohman82e80012009-11-17 00:47:23 +00007618 // If N is a constant we could fold this into a fallthrough or unconditional
7619 // branch. However that doesn't happen very often in normal code, because
7620 // Instcombine/SimplifyCFG should have handled the available opportunities.
7621 // If we did this folding here, it would be necessary to update the
7622 // MachineBasicBlock CFG, which is awkward.
7623
Duncan Sands93b66092008-06-09 11:32:28 +00007624 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007625 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007626 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007627 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007628 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007629
Nate Begemanbd7df032005-10-05 21:43:42 +00007630 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007631 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007632 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007633 N->getOperand(0), Simp.getOperand(2),
7634 Simp.getOperand(0), Simp.getOperand(1),
7635 N->getOperand(4));
7636
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007637 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007638}
7639
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007640/// Return true if 'Use' is a load or a store that uses N as its base pointer
7641/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007642static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7643 SelectionDAG &DAG,
7644 const TargetLowering &TLI) {
7645 EVT VT;
7646 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7647 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7648 return false;
7649 VT = Use->getValueType(0);
7650 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7651 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7652 return false;
7653 VT = ST->getValue().getValueType();
7654 } else
7655 return false;
7656
Chandler Carruth95f83e02013-01-07 15:14:13 +00007657 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007658 if (N->getOpcode() == ISD::ADD) {
7659 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7660 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007661 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007662 AM.BaseOffs = Offset->getSExtValue();
7663 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007664 // [reg +/- reg]
7665 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007666 } else if (N->getOpcode() == ISD::SUB) {
7667 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7668 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007669 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007670 AM.BaseOffs = -Offset->getSExtValue();
7671 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007672 // [reg +/- reg]
7673 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007674 } else
7675 return false;
7676
7677 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7678}
7679
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007680/// Try turning a load/store into a pre-indexed load/store when the base
7681/// pointer is an add or subtract and it has other uses besides the load/store.
7682/// After the transformation, the new indexed load/store has effectively folded
7683/// the add/subtract in and all of its other uses are redirected to the
7684/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00007685bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007686 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007687 return false;
7688
7689 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007690 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007691 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007692 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007693 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007694 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007695 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007696 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007697 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7698 return false;
7699 Ptr = LD->getBasePtr();
7700 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007701 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007702 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007703 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007704 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7705 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7706 return false;
7707 Ptr = ST->getBasePtr();
7708 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007709 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007710 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007711 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007712
Chris Lattnereabc15c2006-11-11 00:56:29 +00007713 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7714 // out. There is no reason to make this a preinc/predec.
7715 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007716 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007717 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007718
Chris Lattnereabc15c2006-11-11 00:56:29 +00007719 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007720 SDValue BasePtr;
7721 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007722 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7723 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7724 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007725
7726 // Backends without true r+i pre-indexed forms may need to pass a
7727 // constant base with a variable offset so that constant coercion
7728 // will work with the patterns in canonical form.
7729 bool Swapped = false;
7730 if (isa<ConstantSDNode>(BasePtr)) {
7731 std::swap(BasePtr, Offset);
7732 Swapped = true;
7733 }
7734
Evan Cheng044a0a82007-05-03 23:52:19 +00007735 // Don't create a indexed load / store with zero offset.
7736 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007737 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007738 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007739
Chris Lattnera0a80032006-11-11 01:00:15 +00007740 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007741 // 1) The new base ptr is a frame index.
7742 // 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 +00007743 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007744 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007745 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007746 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007747
Chris Lattnera0a80032006-11-11 01:00:15 +00007748 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7749 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007750 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007751 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007752
Chris Lattnera0a80032006-11-11 01:00:15 +00007753 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007754 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007755 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007756 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007757 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007758 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007759
Hal Finkel25819052013-02-08 21:35:47 +00007760 // If the offset is a constant, there may be other adds of constants that
7761 // can be folded with this one. We should do this to avoid having to keep
7762 // a copy of the original base pointer.
7763 SmallVector<SDNode *, 16> OtherUses;
7764 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007765 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007766 if (Use == Ptr.getNode())
7767 continue;
7768
7769 if (Use->isPredecessorOf(N))
7770 continue;
7771
7772 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7773 OtherUses.clear();
7774 break;
7775 }
7776
7777 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7778 if (Op1.getNode() == BasePtr.getNode())
7779 std::swap(Op0, Op1);
7780 assert(Op0.getNode() == BasePtr.getNode() &&
7781 "Use of ADD/SUB but not an operand");
7782
7783 if (!isa<ConstantSDNode>(Op1)) {
7784 OtherUses.clear();
7785 break;
7786 }
7787
7788 // FIXME: In some cases, we can be smarter about this.
7789 if (Op1.getValueType() != Offset.getValueType()) {
7790 OtherUses.clear();
7791 break;
7792 }
7793
7794 OtherUses.push_back(Use);
7795 }
7796
7797 if (Swapped)
7798 std::swap(BasePtr, Offset);
7799
Evan Chenga4d187b2007-05-24 02:35:39 +00007800 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007801 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007802
7803 // Caches for hasPredecessorHelper
7804 SmallPtrSet<const SDNode *, 32> Visited;
7805 SmallVector<const SDNode *, 16> Worklist;
7806
Jim Grosbache8160032014-04-11 01:13:13 +00007807 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007808 if (Use == N)
7809 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007810 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007811 return false;
7812
Evan Chengfa832632012-01-13 01:37:24 +00007813 // If Ptr may be folded in addressing mode of other use, then it's
7814 // not profitable to do this transformation.
7815 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007816 RealUse = true;
7817 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007818
Chris Lattnereabc15c2006-11-11 00:56:29 +00007819 if (!RealUse)
7820 return false;
7821
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007822 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007823 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007824 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007825 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007826 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007827 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007828 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007829 ++PreIndexedNodes;
7830 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007831 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007832 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007833 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007834 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007835 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007836 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007837 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007838 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7839 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007840 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007841 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007842 }
7843
Chris Lattnereabc15c2006-11-11 00:56:29 +00007844 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00007845 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007846
Hal Finkel25819052013-02-08 21:35:47 +00007847 if (Swapped)
7848 std::swap(BasePtr, Offset);
7849
7850 // Replace other uses of BasePtr that can be updated to use Ptr
7851 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7852 unsigned OffsetIdx = 1;
7853 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7854 OffsetIdx = 0;
7855 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7856 BasePtr.getNode() && "Expected BasePtr operand");
7857
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007858 // We need to replace ptr0 in the following expression:
7859 // x0 * offset0 + y0 * ptr0 = t0
7860 // knowing that
7861 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007862 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007863 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7864 // indexed load/store and the expresion that needs to be re-written.
7865 //
7866 // Therefore, we have:
7867 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007868
7869 ConstantSDNode *CN =
7870 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007871 int X0, X1, Y0, Y1;
7872 APInt Offset0 = CN->getAPIntValue();
7873 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007874
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007875 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7876 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7877 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7878 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007879
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007880 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7881
7882 APInt CNV = Offset0;
7883 if (X0 < 0) CNV = -CNV;
7884 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7885 else CNV = CNV - Offset1;
7886
7887 // We can now generate the new expression.
7888 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7889 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7890
7891 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007892 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007893 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7894 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00007895 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00007896 }
7897
Chris Lattnereabc15c2006-11-11 00:56:29 +00007898 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007899 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00007900 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007901
7902 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007903}
7904
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007905/// Try to combine a load/store with a add/sub of the base pointer node into a
7906/// post-indexed load/store. The transformation folded the add/subtract into the
7907/// new indexed load/store effectively and all of its uses are redirected to the
7908/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00007909bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007910 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007911 return false;
7912
7913 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007914 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007915 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007916 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007917 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007918 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007919 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007920 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7921 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7922 return false;
7923 Ptr = LD->getBasePtr();
7924 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007925 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007926 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007927 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007928 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7929 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7930 return false;
7931 Ptr = ST->getBasePtr();
7932 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007933 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007934 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007935 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007936
Gabor Greiff304a7a2008-08-28 21:40:38 +00007937 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007938 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007939
Jim Grosbache8160032014-04-11 01:13:13 +00007940 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007941 if (Op == N ||
7942 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7943 continue;
7944
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007945 SDValue BasePtr;
7946 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007947 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7948 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007949 // Don't create a indexed load / store with zero offset.
7950 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007951 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007952 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007953
Chris Lattnereabc15c2006-11-11 00:56:29 +00007954 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007955 // 1) All uses are load / store ops that use it as base ptr (and
7956 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007957 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7958 // nor a successor of N. Otherwise, if Op is folded that would
7959 // create a cycle.
7960
Evan Chengcfc05132009-05-06 18:25:01 +00007961 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7962 continue;
7963
Chris Lattnereabc15c2006-11-11 00:56:29 +00007964 // Check for #1.
7965 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007966 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007967 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007968 continue;
7969
Chris Lattnereabc15c2006-11-11 00:56:29 +00007970 // If all the uses are load / store addresses, then don't do the
7971 // transformation.
7972 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7973 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007974 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007975 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007976 RealUse = true;
7977 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007978
Chris Lattnereabc15c2006-11-11 00:56:29 +00007979 if (!RealUse) {
7980 TryNext = true;
7981 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007982 }
7983 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007984 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007985
Chris Lattnereabc15c2006-11-11 00:56:29 +00007986 if (TryNext)
7987 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007988
Chris Lattnereabc15c2006-11-11 00:56:29 +00007989 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007990 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007991 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007992 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007993 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007994 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007995 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007996 ++PostIndexedNodes;
7997 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007998 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007999 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008000 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008001 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008002 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008003 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008004 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008005 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8006 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008007 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008008 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008009 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008010
Chris Lattnereabc15c2006-11-11 00:56:29 +00008011 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008012 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008013
8014 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008015 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008016 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008017 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008018 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008019 }
8020 }
8021 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008022
Chris Lattnerffad2162006-11-11 00:39:41 +00008023 return false;
8024}
8025
Hal Finkel51e6fa22014-09-02 06:24:04 +00008026/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8027SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8028 ISD::MemIndexedMode AM = LD->getAddressingMode();
8029 assert(AM != ISD::UNINDEXED);
8030 SDValue BP = LD->getOperand(1);
8031 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008032
8033 // Some backends use TargetConstants for load offsets, but don't expect
8034 // TargetConstants in general ADD nodes. We can convert these constants into
8035 // regular Constants (if the constant is not opaque).
8036 assert((Inc.getOpcode() != ISD::TargetConstant ||
8037 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8038 "Cannot split out indexing using opaque target constants");
8039 if (Inc.getOpcode() == ISD::TargetConstant) {
8040 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8041 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8042 ConstInc->getValueType(0));
8043 }
8044
Hal Finkel51e6fa22014-09-02 06:24:04 +00008045 unsigned Opc =
8046 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8047 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8048}
8049
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008050SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008051 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008052 SDValue Chain = LD->getChain();
8053 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008054
Evan Chenga684cd22007-05-01 00:38:21 +00008055 // If load is not volatile and there are no uses of the loaded value (and
8056 // the updated indexed value in case of indexed loads), change uses of the
8057 // chain value into uses of the chain input (i.e. delete the dead load).
8058 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008059 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008060 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008061 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008062 // It's not safe to use the two value CombineTo variant here. e.g.
8063 // v1, chain2 = load chain1, loc
8064 // v2, chain3 = load chain2, loc
8065 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008066 // Now we replace use of chain2 with chain1. This makes the second load
8067 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008068 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008069 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008070 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008071 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008072 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008073 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008074 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008075
Chandler Carruth18066972014-08-02 10:02:07 +00008076 if (N->use_empty())
8077 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008078
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008079 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008080 }
Evan Chengb68343c2007-05-01 08:53:39 +00008081 } else {
8082 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008083 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008084
Hal Finkele19006e2014-09-02 16:05:23 +00008085 // If this load has an opaque TargetConstant offset, then we cannot split
8086 // the indexing into an add/sub directly (that TargetConstant may not be
8087 // valid for a different type of node, and we cannot convert an opaque
8088 // target constant into a regular constant).
8089 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8090 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00008091
8092 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00008093 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00008094 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00008095 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00008096 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00008097 Index = SplitIndexingFromLoad(LD);
8098 // Try to fold the base pointer arithmetic into subsequent loads and
8099 // stores.
8100 AddUsersToWorklist(N);
8101 } else
8102 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00008103 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008104 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008105 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008106 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008107 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008108 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008109 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00008110 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008111 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008112 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008113 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008114 }
Evan Chenga684cd22007-05-01 00:38:21 +00008115 }
8116 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008117
Chris Lattnere260ed82005-10-10 22:04:48 +00008118 // If this load is directly stored, replace the load value with the stored
8119 // value.
8120 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008121 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008122 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008123 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008124 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8125 if (PrevST->getBasePtr() == Ptr &&
8126 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008127 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008128 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008129 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008130
Evan Cheng43cd9e32010-04-01 06:04:33 +00008131 // Try to infer better alignment information than the load already has.
8132 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008133 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008134 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8135 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008136 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008137 LD->getValueType(0),
8138 Chain, Ptr, LD->getPointerInfo(),
8139 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008140 LD->isVolatile(), LD->isNonTemporal(),
8141 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008142 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8143 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008144 }
8145 }
8146
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008147 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8148 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008149#ifndef NDEBUG
8150 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8151 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8152 UseAA = false;
8153#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008154 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008155 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008156 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008157
Jim Laskey708d0db2006-10-04 16:53:27 +00008158 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008159 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008160 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008161
Jim Laskeyd07be232006-09-25 16:29:54 +00008162 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008163 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008164 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008165 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008166 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008167 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008168 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008169 BetterChain, Ptr, LD->getMemoryVT(),
8170 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008171 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008172
Jim Laskey708d0db2006-10-04 16:53:27 +00008173 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008174 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008175 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008176
Nate Begeman879d8f12009-09-15 00:18:30 +00008177 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008178 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008179
Jim Laskeydcf983c2006-10-13 23:32:28 +00008180 // Replace uses with load result and token factor. Don't add users
8181 // to work list.
8182 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008183 }
8184 }
8185
Evan Cheng357017f2006-11-03 03:06:21 +00008186 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008187 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008188 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008189
Quentin Colombetde0e0622013-10-11 18:29:42 +00008190 // Try to slice up N to more direct loads if the slices are mapped to
8191 // different register banks or pairing can take place.
8192 if (SliceUpLoad(N))
8193 return SDValue(N, 0);
8194
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008195 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008196}
8197
Quentin Colombetde0e0622013-10-11 18:29:42 +00008198namespace {
8199/// \brief Helper structure used to slice a load in smaller loads.
8200/// Basically a slice is obtained from the following sequence:
8201/// Origin = load Ty1, Base
8202/// Shift = srl Ty1 Origin, CstTy Amount
8203/// Inst = trunc Shift to Ty2
8204///
8205/// Then, it will be rewriten into:
8206/// Slice = load SliceTy, Base + SliceOffset
8207/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8208///
8209/// SliceTy is deduced from the number of bits that are actually used to
8210/// build Inst.
8211struct LoadedSlice {
8212 /// \brief Helper structure used to compute the cost of a slice.
8213 struct Cost {
8214 /// Are we optimizing for code size.
8215 bool ForCodeSize;
8216 /// Various cost.
8217 unsigned Loads;
8218 unsigned Truncates;
8219 unsigned CrossRegisterBanksCopies;
8220 unsigned ZExts;
8221 unsigned Shift;
8222
8223 Cost(bool ForCodeSize = false)
8224 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8225 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8226
8227 /// \brief Get the cost of one isolated slice.
8228 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8229 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8230 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8231 EVT TruncType = LS.Inst->getValueType(0);
8232 EVT LoadedType = LS.getLoadedType();
8233 if (TruncType != LoadedType &&
8234 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8235 ZExts = 1;
8236 }
8237
8238 /// \brief Account for slicing gain in the current cost.
8239 /// Slicing provide a few gains like removing a shift or a
8240 /// truncate. This method allows to grow the cost of the original
8241 /// load with the gain from this slice.
8242 void addSliceGain(const LoadedSlice &LS) {
8243 // Each slice saves a truncate.
8244 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8245 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8246 LS.Inst->getOperand(0).getValueType()))
8247 ++Truncates;
8248 // If there is a shift amount, this slice gets rid of it.
8249 if (LS.Shift)
8250 ++Shift;
8251 // If this slice can merge a cross register bank copy, account for it.
8252 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8253 ++CrossRegisterBanksCopies;
8254 }
8255
8256 Cost &operator+=(const Cost &RHS) {
8257 Loads += RHS.Loads;
8258 Truncates += RHS.Truncates;
8259 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8260 ZExts += RHS.ZExts;
8261 Shift += RHS.Shift;
8262 return *this;
8263 }
8264
8265 bool operator==(const Cost &RHS) const {
8266 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8267 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8268 ZExts == RHS.ZExts && Shift == RHS.Shift;
8269 }
8270
8271 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8272
8273 bool operator<(const Cost &RHS) const {
8274 // Assume cross register banks copies are as expensive as loads.
8275 // FIXME: Do we want some more target hooks?
8276 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8277 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8278 // Unless we are optimizing for code size, consider the
8279 // expensive operation first.
8280 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8281 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8282 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8283 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8284 }
8285
8286 bool operator>(const Cost &RHS) const { return RHS < *this; }
8287
8288 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8289
8290 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8291 };
8292 // The last instruction that represent the slice. This should be a
8293 // truncate instruction.
8294 SDNode *Inst;
8295 // The original load instruction.
8296 LoadSDNode *Origin;
8297 // The right shift amount in bits from the original load.
8298 unsigned Shift;
8299 // The DAG from which Origin came from.
8300 // This is used to get some contextual information about legal types, etc.
8301 SelectionDAG *DAG;
8302
Craig Topperc0196b12014-04-14 00:51:57 +00008303 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8304 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008305 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8306
8307 LoadedSlice(const LoadedSlice &LS)
8308 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8309
8310 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8311 /// \return Result is \p BitWidth and has used bits set to 1 and
8312 /// not used bits set to 0.
8313 APInt getUsedBits() const {
8314 // Reproduce the trunc(lshr) sequence:
8315 // - Start from the truncated value.
8316 // - Zero extend to the desired bit width.
8317 // - Shift left.
8318 assert(Origin && "No original load to compare against.");
8319 unsigned BitWidth = Origin->getValueSizeInBits(0);
8320 assert(Inst && "This slice is not bound to an instruction");
8321 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8322 "Extracted slice is bigger than the whole type!");
8323 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8324 UsedBits.setAllBits();
8325 UsedBits = UsedBits.zext(BitWidth);
8326 UsedBits <<= Shift;
8327 return UsedBits;
8328 }
8329
8330 /// \brief Get the size of the slice to be loaded in bytes.
8331 unsigned getLoadedSize() const {
8332 unsigned SliceSize = getUsedBits().countPopulation();
8333 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8334 return SliceSize / 8;
8335 }
8336
8337 /// \brief Get the type that will be loaded for this slice.
8338 /// Note: This may not be the final type for the slice.
8339 EVT getLoadedType() const {
8340 assert(DAG && "Missing context");
8341 LLVMContext &Ctxt = *DAG->getContext();
8342 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8343 }
8344
8345 /// \brief Get the alignment of the load used for this slice.
8346 unsigned getAlignment() const {
8347 unsigned Alignment = Origin->getAlignment();
8348 unsigned Offset = getOffsetFromBase();
8349 if (Offset != 0)
8350 Alignment = MinAlign(Alignment, Alignment + Offset);
8351 return Alignment;
8352 }
8353
8354 /// \brief Check if this slice can be rewritten with legal operations.
8355 bool isLegal() const {
8356 // An invalid slice is not legal.
8357 if (!Origin || !Inst || !DAG)
8358 return false;
8359
8360 // Offsets are for indexed load only, we do not handle that.
8361 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8362 return false;
8363
8364 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8365
8366 // Check that the type is legal.
8367 EVT SliceType = getLoadedType();
8368 if (!TLI.isTypeLegal(SliceType))
8369 return false;
8370
8371 // Check that the load is legal for this type.
8372 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8373 return false;
8374
8375 // Check that the offset can be computed.
8376 // 1. Check its type.
8377 EVT PtrType = Origin->getBasePtr().getValueType();
8378 if (PtrType == MVT::Untyped || PtrType.isExtended())
8379 return false;
8380
8381 // 2. Check that it fits in the immediate.
8382 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8383 return false;
8384
8385 // 3. Check that the computation is legal.
8386 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8387 return false;
8388
8389 // Check that the zext is legal if it needs one.
8390 EVT TruncateType = Inst->getValueType(0);
8391 if (TruncateType != SliceType &&
8392 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8393 return false;
8394
8395 return true;
8396 }
8397
8398 /// \brief Get the offset in bytes of this slice in the original chunk of
8399 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008400 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008401 uint64_t getOffsetFromBase() const {
8402 assert(DAG && "Missing context.");
8403 bool IsBigEndian =
8404 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8405 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8406 uint64_t Offset = Shift / 8;
8407 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8408 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8409 "The size of the original loaded type is not a multiple of a"
8410 " byte.");
8411 // If Offset is bigger than TySizeInBytes, it means we are loading all
8412 // zeros. This should have been optimized before in the process.
8413 assert(TySizeInBytes > Offset &&
8414 "Invalid shift amount for given loaded size");
8415 if (IsBigEndian)
8416 Offset = TySizeInBytes - Offset - getLoadedSize();
8417 return Offset;
8418 }
8419
8420 /// \brief Generate the sequence of instructions to load the slice
8421 /// represented by this object and redirect the uses of this slice to
8422 /// this new sequence of instructions.
8423 /// \pre this->Inst && this->Origin are valid Instructions and this
8424 /// object passed the legal check: LoadedSlice::isLegal returned true.
8425 /// \return The last instruction of the sequence used to load the slice.
8426 SDValue loadSlice() const {
8427 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8428 const SDValue &OldBaseAddr = Origin->getBasePtr();
8429 SDValue BaseAddr = OldBaseAddr;
8430 // Get the offset in that chunk of bytes w.r.t. the endianess.
8431 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8432 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8433 if (Offset) {
8434 // BaseAddr = BaseAddr + Offset.
8435 EVT ArithType = BaseAddr.getValueType();
8436 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8437 DAG->getConstant(Offset, ArithType));
8438 }
8439
8440 // Create the type of the loaded slice according to its size.
8441 EVT SliceType = getLoadedType();
8442
8443 // Create the load for the slice.
8444 SDValue LastInst = DAG->getLoad(
8445 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8446 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8447 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8448 // If the final type is not the same as the loaded type, this means that
8449 // we have to pad with zero. Create a zero extend for that.
8450 EVT FinalType = Inst->getValueType(0);
8451 if (SliceType != FinalType)
8452 LastInst =
8453 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8454 return LastInst;
8455 }
8456
8457 /// \brief Check if this slice can be merged with an expensive cross register
8458 /// bank copy. E.g.,
8459 /// i = load i32
8460 /// f = bitcast i32 i to float
8461 bool canMergeExpensiveCrossRegisterBankCopy() const {
8462 if (!Inst || !Inst->hasOneUse())
8463 return false;
8464 SDNode *Use = *Inst->use_begin();
8465 if (Use->getOpcode() != ISD::BITCAST)
8466 return false;
8467 assert(DAG && "Missing context");
8468 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8469 EVT ResVT = Use->getValueType(0);
8470 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8471 const TargetRegisterClass *ArgRC =
8472 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8473 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8474 return false;
8475
8476 // At this point, we know that we perform a cross-register-bank copy.
8477 // Check if it is expensive.
Eric Christopherd9134482014-08-04 21:25:23 +00008478 const TargetRegisterInfo *TRI =
8479 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00008480 // Assume bitcasts are cheap, unless both register classes do not
8481 // explicitly share a common sub class.
8482 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8483 return false;
8484
8485 // Check if it will be merged with the load.
8486 // 1. Check the alignment constraint.
8487 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8488 ResVT.getTypeForEVT(*DAG->getContext()));
8489
8490 if (RequiredAlignment > getAlignment())
8491 return false;
8492
8493 // 2. Check that the load is a legal operation for that type.
8494 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8495 return false;
8496
8497 // 3. Check that we do not have a zext in the way.
8498 if (Inst->getValueType(0) != getLoadedType())
8499 return false;
8500
8501 return true;
8502 }
8503};
8504}
8505
Quentin Colombetde0e0622013-10-11 18:29:42 +00008506/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8507/// \p UsedBits looks like 0..0 1..1 0..0.
8508static bool areUsedBitsDense(const APInt &UsedBits) {
8509 // If all the bits are one, this is dense!
8510 if (UsedBits.isAllOnesValue())
8511 return true;
8512
8513 // Get rid of the unused bits on the right.
8514 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8515 // Get rid of the unused bits on the left.
8516 if (NarrowedUsedBits.countLeadingZeros())
8517 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8518 // Check that the chunk of bits is completely used.
8519 return NarrowedUsedBits.isAllOnesValue();
8520}
8521
8522/// \brief Check whether or not \p First and \p Second are next to each other
8523/// in memory. This means that there is no hole between the bits loaded
8524/// by \p First and the bits loaded by \p Second.
8525static bool areSlicesNextToEachOther(const LoadedSlice &First,
8526 const LoadedSlice &Second) {
8527 assert(First.Origin == Second.Origin && First.Origin &&
8528 "Unable to match different memory origins.");
8529 APInt UsedBits = First.getUsedBits();
8530 assert((UsedBits & Second.getUsedBits()) == 0 &&
8531 "Slices are not supposed to overlap.");
8532 UsedBits |= Second.getUsedBits();
8533 return areUsedBitsDense(UsedBits);
8534}
8535
8536/// \brief Adjust the \p GlobalLSCost according to the target
8537/// paring capabilities and the layout of the slices.
8538/// \pre \p GlobalLSCost should account for at least as many loads as
8539/// there is in the slices in \p LoadedSlices.
8540static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8541 LoadedSlice::Cost &GlobalLSCost) {
8542 unsigned NumberOfSlices = LoadedSlices.size();
8543 // If there is less than 2 elements, no pairing is possible.
8544 if (NumberOfSlices < 2)
8545 return;
8546
8547 // Sort the slices so that elements that are likely to be next to each
8548 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008549 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8550 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8551 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8552 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8553 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008554 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8555 // First (resp. Second) is the first (resp. Second) potentially candidate
8556 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008557 const LoadedSlice *First = nullptr;
8558 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008559 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8560 // Set the beginning of the pair.
8561 First = Second) {
8562
8563 Second = &LoadedSlices[CurrSlice];
8564
8565 // If First is NULL, it means we start a new pair.
8566 // Get to the next slice.
8567 if (!First)
8568 continue;
8569
8570 EVT LoadedType = First->getLoadedType();
8571
8572 // If the types of the slices are different, we cannot pair them.
8573 if (LoadedType != Second->getLoadedType())
8574 continue;
8575
8576 // Check if the target supplies paired loads for this type.
8577 unsigned RequiredAlignment = 0;
8578 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8579 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008580 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008581 continue;
8582 }
8583 // Check if we meet the alignment requirement.
8584 if (RequiredAlignment > First->getAlignment())
8585 continue;
8586
8587 // Check that both loads are next to each other in memory.
8588 if (!areSlicesNextToEachOther(*First, *Second))
8589 continue;
8590
8591 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8592 --GlobalLSCost.Loads;
8593 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008594 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008595 }
8596}
8597
8598/// \brief Check the profitability of all involved LoadedSlice.
8599/// Currently, it is considered profitable if there is exactly two
8600/// involved slices (1) which are (2) next to each other in memory, and
8601/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8602///
8603/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8604/// the elements themselves.
8605///
8606/// FIXME: When the cost model will be mature enough, we can relax
8607/// constraints (1) and (2).
8608static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8609 const APInt &UsedBits, bool ForCodeSize) {
8610 unsigned NumberOfSlices = LoadedSlices.size();
8611 if (StressLoadSlicing)
8612 return NumberOfSlices > 1;
8613
8614 // Check (1).
8615 if (NumberOfSlices != 2)
8616 return false;
8617
8618 // Check (2).
8619 if (!areUsedBitsDense(UsedBits))
8620 return false;
8621
8622 // Check (3).
8623 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8624 // The original code has one big load.
8625 OrigCost.Loads = 1;
8626 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8627 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8628 // Accumulate the cost of all the slices.
8629 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8630 GlobalSlicingCost += SliceCost;
8631
8632 // Account as cost in the original configuration the gain obtained
8633 // with the current slices.
8634 OrigCost.addSliceGain(LS);
8635 }
8636
8637 // If the target supports paired load, adjust the cost accordingly.
8638 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8639 return OrigCost > GlobalSlicingCost;
8640}
8641
8642/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8643/// operations, split it in the various pieces being extracted.
8644///
8645/// This sort of thing is introduced by SROA.
8646/// This slicing takes care not to insert overlapping loads.
8647/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8648bool DAGCombiner::SliceUpLoad(SDNode *N) {
8649 if (Level < AfterLegalizeDAG)
8650 return false;
8651
8652 LoadSDNode *LD = cast<LoadSDNode>(N);
8653 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8654 !LD->getValueType(0).isInteger())
8655 return false;
8656
8657 // Keep track of already used bits to detect overlapping values.
8658 // In that case, we will just abort the transformation.
8659 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8660
8661 SmallVector<LoadedSlice, 4> LoadedSlices;
8662
8663 // Check if this load is used as several smaller chunks of bits.
8664 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8665 // of computation for each trunc.
8666 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8667 UI != UIEnd; ++UI) {
8668 // Skip the uses of the chain.
8669 if (UI.getUse().getResNo() != 0)
8670 continue;
8671
8672 SDNode *User = *UI;
8673 unsigned Shift = 0;
8674
8675 // Check if this is a trunc(lshr).
8676 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8677 isa<ConstantSDNode>(User->getOperand(1))) {
8678 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8679 User = *User->use_begin();
8680 }
8681
8682 // At this point, User is a Truncate, iff we encountered, trunc or
8683 // trunc(lshr).
8684 if (User->getOpcode() != ISD::TRUNCATE)
8685 return false;
8686
8687 // The width of the type must be a power of 2 and greater than 8-bits.
8688 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008689 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008690 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008691 unsigned Width = User->getValueSizeInBits(0);
8692 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8693 return 0;
8694
8695 // Build the slice for this chain of computations.
8696 LoadedSlice LS(User, LD, Shift, &DAG);
8697 APInt CurrentUsedBits = LS.getUsedBits();
8698
8699 // Check if this slice overlaps with another.
8700 if ((CurrentUsedBits & UsedBits) != 0)
8701 return false;
8702 // Update the bits used globally.
8703 UsedBits |= CurrentUsedBits;
8704
8705 // Check if the new slice would be legal.
8706 if (!LS.isLegal())
8707 return false;
8708
8709 // Record the slice.
8710 LoadedSlices.push_back(LS);
8711 }
8712
8713 // Abort slicing if it does not seem to be profitable.
8714 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8715 return false;
8716
8717 ++SlicedLoads;
8718
8719 // Rewrite each chain to use an independent load.
8720 // By construction, each chain can be represented by a unique load.
8721
8722 // Prepare the argument for the new token factor for all the slices.
8723 SmallVector<SDValue, 8> ArgChains;
8724 for (SmallVectorImpl<LoadedSlice>::const_iterator
8725 LSIt = LoadedSlices.begin(),
8726 LSItEnd = LoadedSlices.end();
8727 LSIt != LSItEnd; ++LSIt) {
8728 SDValue SliceInst = LSIt->loadSlice();
8729 CombineTo(LSIt->Inst, SliceInst, true);
8730 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8731 SliceInst = SliceInst.getOperand(0);
8732 assert(SliceInst->getOpcode() == ISD::LOAD &&
8733 "It takes more than a zext to get to the loaded slice!!");
8734 ArgChains.push_back(SliceInst.getValue(1));
8735 }
8736
8737 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008738 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008739 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8740 return true;
8741}
8742
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008743/// Check to see if V is (and load (ptr), imm), where the load is having
8744/// specific bytes cleared out. If so, return the byte size being masked out
8745/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00008746static std::pair<unsigned, unsigned>
8747CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8748 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008749
Chris Lattner4041ab62010-04-15 04:48:01 +00008750 // Check for the structure we're looking for.
8751 if (V->getOpcode() != ISD::AND ||
8752 !isa<ConstantSDNode>(V->getOperand(1)) ||
8753 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8754 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008755
Chris Lattner3245afd2010-04-15 06:10:49 +00008756 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008757 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008758 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008759
Chris Lattner3245afd2010-04-15 06:10:49 +00008760 // The store should be chained directly to the load or be an operand of a
8761 // tokenfactor.
8762 if (LD == Chain.getNode())
8763 ; // ok.
8764 else if (Chain->getOpcode() != ISD::TokenFactor)
8765 return Result; // Fail.
8766 else {
8767 bool isOk = false;
8768 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8769 if (Chain->getOperand(i).getNode() == LD) {
8770 isOk = true;
8771 break;
8772 }
8773 if (!isOk) return Result;
8774 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008775
Chris Lattner4041ab62010-04-15 04:48:01 +00008776 // This only handles simple types.
8777 if (V.getValueType() != MVT::i16 &&
8778 V.getValueType() != MVT::i32 &&
8779 V.getValueType() != MVT::i64)
8780 return Result;
8781
8782 // Check the constant mask. Invert it so that the bits being masked out are
8783 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8784 // follow the sign bit for uniformity.
8785 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008786 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008787 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008788 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008789 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8790 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008791
Chris Lattner4041ab62010-04-15 04:48:01 +00008792 // See if we have a continuous run of bits. If so, we have 0*1+0*
8793 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8794 return Result;
8795
8796 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8797 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8798 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008799
Chris Lattner4041ab62010-04-15 04:48:01 +00008800 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8801 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008802 case 1:
8803 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008804 case 4: break;
8805 default: return Result; // All one mask, or 5-byte mask.
8806 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008807
Chris Lattner4041ab62010-04-15 04:48:01 +00008808 // Verify that the first bit starts at a multiple of mask so that the access
8809 // is aligned the same as the access width.
8810 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008811
Chris Lattner4041ab62010-04-15 04:48:01 +00008812 Result.first = MaskedBytes;
8813 Result.second = NotMaskTZ/8;
8814 return Result;
8815}
8816
8817
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008818/// Check to see if IVal is something that provides a value as specified by
8819/// MaskInfo. If so, replace the specified store with a narrower store of
8820/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00008821static SDNode *
8822ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8823 SDValue IVal, StoreSDNode *St,
8824 DAGCombiner *DC) {
8825 unsigned NumBytes = MaskInfo.first;
8826 unsigned ByteShift = MaskInfo.second;
8827 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008828
Chris Lattner4041ab62010-04-15 04:48:01 +00008829 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8830 // that uses this. If not, this is not a replacement.
8831 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8832 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008833 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008834
Chris Lattner4041ab62010-04-15 04:48:01 +00008835 // Check that it is legal on the target to do this. It is legal if the new
8836 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8837 // legalization.
8838 MVT VT = MVT::getIntegerVT(NumBytes*8);
8839 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008840 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008841
Chris Lattner4041ab62010-04-15 04:48:01 +00008842 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8843 // shifted by ByteShift and truncated down to NumBytes.
8844 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008845 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008846 DAG.getConstant(ByteShift*8,
8847 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008848
8849 // Figure out the offset for the store and the alignment of the access.
8850 unsigned StOffset;
8851 unsigned NewAlign = St->getAlignment();
8852
8853 if (DAG.getTargetLoweringInfo().isLittleEndian())
8854 StOffset = ByteShift;
8855 else
8856 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008857
Chris Lattner4041ab62010-04-15 04:48:01 +00008858 SDValue Ptr = St->getBasePtr();
8859 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008860 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008861 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8862 NewAlign = MinAlign(NewAlign, StOffset);
8863 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008864
Chris Lattner4041ab62010-04-15 04:48:01 +00008865 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008866 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008867
Chris Lattner4041ab62010-04-15 04:48:01 +00008868 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008869 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008870 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008871 false, false, NewAlign).getNode();
8872}
8873
Evan Chenga9cda8a2009-05-28 00:35:15 +00008874
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008875/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8876/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8877/// narrowing the load and store if it would end up being a win for performance
8878/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00008879SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8880 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008881 if (ST->isVolatile())
8882 return SDValue();
8883
Evan Chenga9cda8a2009-05-28 00:35:15 +00008884 SDValue Chain = ST->getChain();
8885 SDValue Value = ST->getValue();
8886 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008887 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008888
8889 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008890 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008891
8892 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008893
Chris Lattner4041ab62010-04-15 04:48:01 +00008894 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8895 // is a byte mask indicating a consecutive number of bytes, check to see if
8896 // Y is known to provide just those bytes. If so, we try to replace the
8897 // load + replace + store sequence with a single (narrower) store, which makes
8898 // the load dead.
8899 if (Opc == ISD::OR) {
8900 std::pair<unsigned, unsigned> MaskedLoad;
8901 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8902 if (MaskedLoad.first)
8903 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8904 Value.getOperand(1), ST,this))
8905 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008906
Chris Lattner4041ab62010-04-15 04:48:01 +00008907 // Or is commutative, so try swapping X and Y.
8908 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8909 if (MaskedLoad.first)
8910 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8911 Value.getOperand(0), ST,this))
8912 return SDValue(NewST, 0);
8913 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008914
Evan Chenga9cda8a2009-05-28 00:35:15 +00008915 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8916 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008917 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008918
8919 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008920 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8921 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008922 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008923 if (LD->getBasePtr() != Ptr ||
8924 LD->getPointerInfo().getAddrSpace() !=
8925 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008926 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008927
8928 // Find the type to narrow it the load / op / store to.
8929 SDValue N1 = Value.getOperand(1);
8930 unsigned BitWidth = N1.getValueSizeInBits();
8931 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8932 if (Opc == ISD::AND)
8933 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008934 if (Imm == 0 || Imm.isAllOnesValue())
8935 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008936 unsigned ShAmt = Imm.countTrailingZeros();
8937 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8938 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008939 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008940 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008941 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008942 TLI.isNarrowingProfitable(VT, NewVT))) {
8943 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008944 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008945 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008946 if (NewBW >= BitWidth)
8947 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008948
8949 // If the lsb changed does not start at the type bitwidth boundary,
8950 // start at the previous one.
8951 if (ShAmt % NewBW)
8952 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008953 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8954 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008955 if ((Imm & Mask) == Imm) {
8956 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8957 if (Opc == ISD::AND)
8958 NewImm ^= APInt::getAllOnesValue(NewBW);
8959 uint64_t PtrOff = ShAmt / 8;
8960 // For big endian targets, we need to adjust the offset to the pointer to
8961 // load the correct bytes.
8962 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008963 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008964
8965 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008966 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008967 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008968 return SDValue();
8969
Andrew Trickef9de2a2013-05-25 02:42:55 +00008970 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008971 Ptr.getValueType(), Ptr,
8972 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008973 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008974 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008975 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008976 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008977 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00008978 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008979 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008980 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008981 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008982 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008983 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008984 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008985
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008986 AddToWorklist(NewPtr.getNode());
8987 AddToWorklist(NewLD.getNode());
8988 AddToWorklist(NewVal.getNode());
8989 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008990 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008991 ++OpsNarrowed;
8992 return NewST;
8993 }
8994 }
8995
Evan Cheng6673ff02009-05-28 18:41:02 +00008996 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008997}
8998
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008999/// For a given floating point load / store pair, if the load value isn't used
9000/// by any other operations, then consider transforming the pair to integer
9001/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00009002SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9003 StoreSDNode *ST = cast<StoreSDNode>(N);
9004 SDValue Chain = ST->getChain();
9005 SDValue Value = ST->getValue();
9006 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9007 Value.hasOneUse() &&
9008 Chain == SDValue(Value.getNode(), 1)) {
9009 LoadSDNode *LD = cast<LoadSDNode>(Value);
9010 EVT VT = LD->getMemoryVT();
9011 if (!VT.isFloatingPoint() ||
9012 VT != ST->getMemoryVT() ||
9013 LD->isNonTemporal() ||
9014 ST->isNonTemporal() ||
9015 LD->getPointerInfo().getAddrSpace() != 0 ||
9016 ST->getPointerInfo().getAddrSpace() != 0)
9017 return SDValue();
9018
9019 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9020 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9021 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9022 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9023 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9024 return SDValue();
9025
9026 unsigned LDAlign = LD->getAlignment();
9027 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009028 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009029 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009030 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9031 return SDValue();
9032
Andrew Trickef9de2a2013-05-25 02:42:55 +00009033 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009034 LD->getChain(), LD->getBasePtr(),
9035 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009036 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009037
Andrew Trickef9de2a2013-05-25 02:42:55 +00009038 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009039 NewLD, ST->getBasePtr(),
9040 ST->getPointerInfo(),
9041 false, false, STAlign);
9042
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009043 AddToWorklist(NewLD.getNode());
9044 AddToWorklist(NewST.getNode());
9045 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009046 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009047 ++LdStFP2Int;
9048 return NewST;
9049 }
9050
9051 return SDValue();
9052}
9053
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009054/// Helper struct to parse and store a memory address as base + index + offset.
9055/// We ignore sign extensions when it is safe to do so.
9056/// The following two expressions are not equivalent. To differentiate we need
9057/// to store whether there was a sign extension involved in the index
9058/// computation.
9059/// (load (i64 add (i64 copyfromreg %c)
9060/// (i64 signextend (add (i8 load %index)
9061/// (i8 1))))
9062/// vs
9063///
9064/// (load (i64 add (i64 copyfromreg %c)
9065/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9066/// (i32 1)))))
9067struct BaseIndexOffset {
9068 SDValue Base;
9069 SDValue Index;
9070 int64_t Offset;
9071 bool IsIndexSignExt;
9072
9073 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9074
9075 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9076 bool IsIndexSignExt) :
9077 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9078
9079 bool equalBaseIndex(const BaseIndexOffset &Other) {
9080 return Other.Base == Base && Other.Index == Index &&
9081 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009082 }
9083
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009084 /// Parses tree in Ptr for base, index, offset addresses.
9085 static BaseIndexOffset match(SDValue Ptr) {
9086 bool IsIndexSignExt = false;
9087
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009088 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9089 // instruction, then it could be just the BASE or everything else we don't
9090 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009091 if (Ptr->getOpcode() != ISD::ADD)
9092 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9093
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009094 // We know that we have at least an ADD instruction. Try to pattern match
9095 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009096 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9097 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9098 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9099 IsIndexSignExt);
9100 }
9101
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009102 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009103 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009104 // (i64 add (i64 %array_ptr)
9105 // (i64 mul (i64 %induction_var)
9106 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009107 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009108 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009109
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009110 // Look at Base + Index + Offset cases.
9111 SDValue Base = Ptr->getOperand(0);
9112 SDValue IndexOffset = Ptr->getOperand(1);
9113
9114 // Skip signextends.
9115 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9116 IndexOffset = IndexOffset->getOperand(0);
9117 IsIndexSignExt = true;
9118 }
9119
9120 // Either the case of Base + Index (no offset) or something else.
9121 if (IndexOffset->getOpcode() != ISD::ADD)
9122 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9123
9124 // Now we have the case of Base + Index + offset.
9125 SDValue Index = IndexOffset->getOperand(0);
9126 SDValue Offset = IndexOffset->getOperand(1);
9127
9128 if (!isa<ConstantSDNode>(Offset))
9129 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9130
9131 // Ignore signextends.
9132 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9133 Index = Index->getOperand(0);
9134 IsIndexSignExt = true;
9135 } else IsIndexSignExt = false;
9136
9137 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9138 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9139 }
9140};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009141
9142/// Holds a pointer to an LSBaseSDNode as well as information on where it
9143/// is located in a sequence of memory operations connected by a chain.
9144struct MemOpLink {
9145 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9146 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9147 // Ptr to the mem node.
9148 LSBaseSDNode *MemNode;
9149 // Offset from the base ptr.
9150 int64_t OffsetFromBase;
9151 // What is the sequence number of this mem node.
9152 // Lowest mem operand in the DAG starts at zero.
9153 unsigned SequenceNum;
9154};
9155
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009156bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9157 EVT MemVT = St->getMemoryVT();
9158 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009159 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9160 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009161
9162 // Don't merge vectors into wider inputs.
9163 if (MemVT.isVector() || !MemVT.isSimple())
9164 return false;
9165
9166 // Perform an early exit check. Do not bother looking at stored values that
9167 // are not constants or loads.
9168 SDValue StoredVal = St->getValue();
9169 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9170 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9171 !IsLoadSrc)
9172 return false;
9173
9174 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +00009175 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009176 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9177 return false;
9178
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009179 // This holds the base pointer, index, and the offset in bytes from the base
9180 // pointer.
9181 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009182
9183 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009184 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009185 return false;
9186
9187 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009188 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009189 return false;
9190
Nadav Rotem307d7672012-11-29 00:00:08 +00009191 // Save the LoadSDNodes that we find in the chain.
9192 // We need to make sure that these nodes do not interfere with
9193 // any of the store nodes.
9194 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9195
9196 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009197 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009198
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009199 // Walk up the chain and look for nodes with offsets from the same
9200 // base pointer. Stop when reaching an instruction with a different kind
9201 // or instruction which has a different base pointer.
9202 unsigned Seq = 0;
9203 StoreSDNode *Index = St;
9204 while (Index) {
9205 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +00009206 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009207 break;
9208
9209 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009210 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009211
9212 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009213 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009214 break;
9215
9216 // Check that the alignment is the same.
9217 if (Index->getAlignment() != St->getAlignment())
9218 break;
9219
9220 // The memory operands must not be volatile.
9221 if (Index->isVolatile() || Index->isIndexed())
9222 break;
9223
9224 // No truncation.
9225 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9226 if (St->isTruncatingStore())
9227 break;
9228
9229 // The stored memory type must be the same.
9230 if (Index->getMemoryVT() != MemVT)
9231 break;
9232
9233 // We do not allow unaligned stores because we want to prevent overriding
9234 // stores.
9235 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9236 break;
9237
9238 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009239 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009240
Nadav Rotem307d7672012-11-29 00:00:08 +00009241 // Find the next memory operand in the chain. If the next operand in the
9242 // chain is a store then move up and continue the scan with the next
9243 // memory operand. If the next operand is a load save it and use alias
9244 // information to check if it interferes with anything.
9245 SDNode *NextInChain = Index->getChain().getNode();
9246 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009247 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009248 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009249 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009250 break;
9251 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009252 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009253 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009254 break;
9255 }
9256
Nadav Rotem307d7672012-11-29 00:00:08 +00009257 // Save the load node for later. Continue the scan.
9258 AliasLoadNodes.push_back(Ldn);
9259 NextInChain = Ldn->getChain().getNode();
9260 continue;
9261 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009262 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009263 break;
9264 }
9265 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009266 }
9267
9268 // Check if there is anything to merge.
9269 if (StoreNodes.size() < 2)
9270 return false;
9271
9272 // Sort the memory operands according to their distance from the base pointer.
9273 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009274 [](MemOpLink LHS, MemOpLink RHS) {
9275 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9276 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9277 LHS.SequenceNum > RHS.SequenceNum);
9278 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009279
9280 // Scan the memory operations on the chain and find the first non-consecutive
9281 // store memory address.
9282 unsigned LastConsecutiveStore = 0;
9283 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009284 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9285
9286 // Check that the addresses are consecutive starting from the second
9287 // element in the list of stores.
9288 if (i > 0) {
9289 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9290 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9291 break;
9292 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009293
Nadav Rotem307d7672012-11-29 00:00:08 +00009294 bool Alias = false;
9295 // Check if this store interferes with any of the loads that we found.
9296 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9297 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9298 Alias = true;
9299 break;
9300 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009301 // We found a load that alias with this store. Stop the sequence.
9302 if (Alias)
9303 break;
9304
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009305 // Mark this node as useful.
9306 LastConsecutiveStore = i;
9307 }
9308
9309 // The node with the lowest store address.
9310 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9311
9312 // Store the constants into memory as one consecutive store.
9313 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009314 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009315 unsigned LastLegalVectorType = 0;
9316 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009317 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9318 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9319 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009320
9321 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009322 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009323 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009324 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009325 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009326 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009327 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009328 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009329
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009330 // Find a legal type for the constant store.
9331 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9332 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9333 if (TLI.isTypeLegal(StoreTy))
9334 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009335 // Or check whether a truncstore is legal.
9336 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9337 TargetLowering::TypePromoteInteger) {
9338 EVT LegalizedStoredValueTy =
9339 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9340 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9341 LastLegalType = i+1;
9342 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009343
9344 // Find a legal type for the vector store.
9345 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9346 if (TLI.isTypeLegal(Ty))
9347 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009348 }
9349
Bob Wilson3365b802012-12-20 01:36:20 +00009350 // We only use vectors if the constant is known to be zero and the
9351 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009352 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009353 LastLegalVectorType = 0;
9354
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009355 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009356 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009357 return false;
9358
Nadav Rotem495b1a42013-02-14 18:28:52 +00009359 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009360 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9361
9362 // Make sure we have something to merge.
9363 if (NumElem < 2)
9364 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009365
9366 unsigned EarliestNodeUsed = 0;
9367 for (unsigned i=0; i < NumElem; ++i) {
9368 // Find a chain for the new wide-store operand. Notice that some
9369 // of the store nodes that we found may not be selected for inclusion
9370 // in the wide store. The chain we use needs to be the chain of the
9371 // earliest store node which is *used* and replaced by the wide store.
9372 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9373 EarliestNodeUsed = i;
9374 }
9375
9376 // The earliest Node in the DAG.
9377 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009378 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009379
Nadav Rotemb27777f2012-10-04 22:35:15 +00009380 SDValue StoredVal;
9381 if (UseVector) {
9382 // Find a legal type for the vector store.
9383 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9384 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9385 StoredVal = DAG.getConstant(0, Ty);
9386 } else {
9387 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9388 APInt StoreInt(StoreBW, 0);
9389
9390 // Construct a single integer constant which is made of the smaller
9391 // constant inputs.
9392 bool IsLE = TLI.isLittleEndian();
9393 for (unsigned i = 0; i < NumElem ; ++i) {
9394 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9395 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9396 SDValue Val = St->getValue();
9397 StoreInt<<=ElementSizeBytes*8;
9398 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9399 StoreInt|=C->getAPIntValue().zext(StoreBW);
9400 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9401 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9402 } else {
9403 assert(false && "Invalid constant element type");
9404 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009405 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009406
9407 // Create the new Load and Store operations.
9408 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9409 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009410 }
9411
Nadav Rotemb27777f2012-10-04 22:35:15 +00009412 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009413 FirstInChain->getBasePtr(),
9414 FirstInChain->getPointerInfo(),
9415 false, false,
9416 FirstInChain->getAlignment());
9417
9418 // Replace the first store with the new store
9419 CombineTo(EarliestOp, NewStore);
9420 // Erase all other stores.
9421 for (unsigned i = 0; i < NumElem ; ++i) {
9422 if (StoreNodes[i].MemNode == EarliestOp)
9423 continue;
9424 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009425 // ReplaceAllUsesWith will replace all uses that existed when it was
9426 // called, but graph optimizations may cause new ones to appear. For
9427 // example, the case in pr14333 looks like
9428 //
9429 // St's chain -> St -> another store -> X
9430 //
9431 // And the only difference from St to the other store is the chain.
9432 // When we change it's chain to be St's chain they become identical,
9433 // get CSEed and the net result is that X is now a use of St.
9434 // Since we know that St is redundant, just iterate.
9435 while (!St->use_empty())
9436 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009437 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009438 }
9439
9440 return true;
9441 }
9442
9443 // Below we handle the case of multiple consecutive stores that
9444 // come from multiple consecutive loads. We merge them into a single
9445 // wide load and a single wide store.
9446
9447 // Look for load nodes which are used by the stored values.
9448 SmallVector<MemOpLink, 8> LoadNodes;
9449
9450 // Find acceptable loads. Loads need to have the same chain (token factor),
9451 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009452 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009453 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9454 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9455 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9456 if (!Ld) break;
9457
9458 // Loads must only have one use.
9459 if (!Ld->hasNUsesOfValue(1, 0))
9460 break;
9461
9462 // Check that the alignment is the same as the stores.
9463 if (Ld->getAlignment() != St->getAlignment())
9464 break;
9465
9466 // The memory operands must not be volatile.
9467 if (Ld->isVolatile() || Ld->isIndexed())
9468 break;
9469
9470 // We do not accept ext loads.
9471 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9472 break;
9473
9474 // The stored memory type must be the same.
9475 if (Ld->getMemoryVT() != MemVT)
9476 break;
9477
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009478 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009479 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009480 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009481 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009482 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009483 break;
9484 } else {
9485 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009486 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009487 }
9488
9489 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009490 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009491 }
9492
9493 if (LoadNodes.size() < 2)
9494 return false;
9495
James Molloyce45be02014-08-02 14:51:24 +00009496 // If we have load/store pair instructions and we only have two values,
9497 // don't bother.
9498 unsigned RequiredAlignment;
9499 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9500 St->getAlignment() >= RequiredAlignment)
9501 return false;
9502
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009503 // Scan the memory operations on the chain and find the first non-consecutive
9504 // load memory address. These variables hold the index in the store node
9505 // array.
9506 unsigned LastConsecutiveLoad = 0;
9507 // This variable refers to the size and not index in the array.
9508 unsigned LastLegalVectorType = 0;
9509 unsigned LastLegalIntegerType = 0;
9510 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009511 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9512 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9513 // All loads much share the same chain.
9514 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9515 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009516
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009517 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9518 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9519 break;
9520 LastConsecutiveLoad = i;
9521
9522 // Find a legal type for the vector store.
9523 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9524 if (TLI.isTypeLegal(StoreTy))
9525 LastLegalVectorType = i + 1;
9526
9527 // Find a legal type for the integer store.
9528 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9529 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9530 if (TLI.isTypeLegal(StoreTy))
9531 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009532 // Or check whether a truncstore and extload is legal.
9533 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9534 TargetLowering::TypePromoteInteger) {
9535 EVT LegalizedStoredValueTy =
9536 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9537 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9538 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9539 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9540 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9541 LastLegalIntegerType = i+1;
9542 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009543 }
9544
9545 // Only use vector types if the vector type is larger than the integer type.
9546 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009547 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009548 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9549
9550 // We add +1 here because the LastXXX variables refer to location while
9551 // the NumElem refers to array/index size.
9552 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9553 NumElem = std::min(LastLegalType, NumElem);
9554
9555 if (NumElem < 2)
9556 return false;
9557
9558 // The earliest Node in the DAG.
9559 unsigned EarliestNodeUsed = 0;
9560 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9561 for (unsigned i=1; i<NumElem; ++i) {
9562 // Find a chain for the new wide-store operand. Notice that some
9563 // of the store nodes that we found may not be selected for inclusion
9564 // in the wide store. The chain we use needs to be the chain of the
9565 // earliest store node which is *used* and replaced by the wide store.
9566 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9567 EarliestNodeUsed = i;
9568 }
9569
9570 // Find if it is better to use vectors or integers to load and store
9571 // to memory.
9572 EVT JointMemOpVT;
9573 if (UseVectorTy) {
9574 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9575 } else {
9576 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9577 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9578 }
9579
Andrew Trickef9de2a2013-05-25 02:42:55 +00009580 SDLoc LoadDL(LoadNodes[0].MemNode);
9581 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009582
9583 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9584 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9585 FirstLoad->getChain(),
9586 FirstLoad->getBasePtr(),
9587 FirstLoad->getPointerInfo(),
9588 false, false, false,
9589 FirstLoad->getAlignment());
9590
9591 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9592 FirstInChain->getBasePtr(),
9593 FirstInChain->getPointerInfo(), false, false,
9594 FirstInChain->getAlignment());
9595
Nadav Rotemac920662012-10-03 19:30:31 +00009596 // Replace one of the loads with the new load.
9597 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9598 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9599 SDValue(NewLoad.getNode(), 1));
9600
9601 // Remove the rest of the load chains.
9602 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009603 // Replace all chain users of the old load nodes with the chain of the new
9604 // load node.
9605 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009606 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9607 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009608
Nadav Rotemac920662012-10-03 19:30:31 +00009609 // Replace the first store with the new store.
9610 CombineTo(EarliestOp, NewStore);
9611 // Erase all other stores.
9612 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009613 // Remove all Store nodes.
9614 if (StoreNodes[i].MemNode == EarliestOp)
9615 continue;
9616 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9617 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009618 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009619 }
9620
9621 return true;
9622}
9623
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009624SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009625 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009626 SDValue Chain = ST->getChain();
9627 SDValue Value = ST->getValue();
9628 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009629
Evan Chenga4cf58a2007-05-07 21:27:48 +00009630 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009631 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009632 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009633 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009634 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009635 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009636 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009637 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009638 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009639 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009640 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009641 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009642 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009643 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009644 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009645 }
Owen Andersona5192842011-04-14 17:30:49 +00009646
Chris Lattner41c80e82011-04-09 02:32:02 +00009647 // Turn 'store undef, Ptr' -> nothing.
9648 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9649 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009650
Nate Begeman8e20c762006-12-11 02:23:46 +00009651 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009652 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009653 // NOTE: If the original store is volatile, this transform must not increase
9654 // the number of stores. For example, on x86-32 an f64 can be stored in one
9655 // processor operation but an i64 (which is not legal) requires two. So the
9656 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009657 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009658 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009659 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009660 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009661 case MVT::f16: // We don't do this for these yet.
9662 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009663 case MVT::f128:
9664 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009665 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009666 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009667 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009668 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009669 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009670 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009671 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009672 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009673 }
9674 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009675 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009676 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009677 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009678 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009679 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009680 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009681 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009682 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009683 }
Owen Andersona5192842011-04-14 17:30:49 +00009684
Chris Lattner41c80e82011-04-09 02:32:02 +00009685 if (!ST->isVolatile() &&
9686 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009687 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009688 // argument passing. Since this is so common, custom legalize the
9689 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009690 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009691 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9692 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009693 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009694
Dan Gohman2af30632007-07-09 22:18:38 +00009695 unsigned Alignment = ST->getAlignment();
9696 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009697 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +00009698 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009699
Andrew Trickef9de2a2013-05-25 02:42:55 +00009700 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009701 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009702 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009703 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009704 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009705 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009706 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009707 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009708 Ptr, ST->getPointerInfo().getWithOffset(4),
9709 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009710 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009711 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009712 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009713 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009714
Chris Lattnerb7524b62006-12-12 04:16:14 +00009715 break;
Evan Cheng21836982006-12-11 17:25:19 +00009716 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009717 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009718 }
9719
Evan Cheng43cd9e32010-04-01 06:04:33 +00009720 // Try to infer better alignment information than the store already has.
9721 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009722 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9723 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009724 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009725 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009726 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +00009727 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009728 }
9729 }
9730
Evan Chengd42641c2011-02-02 01:06:55 +00009731 // Try transforming a pair floating point load / store ops to integer
9732 // load / store ops.
9733 SDValue NewST = TransformFPLoadStorePair(N);
9734 if (NewST.getNode())
9735 return NewST;
9736
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009737 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9738 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009739#ifndef NDEBUG
9740 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9741 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9742 UseAA = false;
9743#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009744 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009745 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009746 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009747
Jim Laskey708d0db2006-10-04 16:53:27 +00009748 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009749 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009750 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009751
9752 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009753 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009754 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009755 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009756 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009757 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009758 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009759 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009760
Jim Laskeyd07be232006-09-25 16:29:54 +00009761 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009762 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009763 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009764
Nate Begeman879d8f12009-09-15 00:18:30 +00009765 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009766 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +00009767
Jim Laskeydcf983c2006-10-13 23:32:28 +00009768 // Don't add users to work list.
9769 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009770 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009771 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009772
Evan Cheng33157702006-11-05 09:31:14 +00009773 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009774 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009775 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009776
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009777 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009778 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009779 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009780 // See if we can simplify the input to this truncstore with knowledge that
9781 // only the low bits are being used. For example:
9782 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009783 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009784 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009785 APInt::getLowBitsSet(
9786 Value.getValueType().getScalarType().getSizeInBits(),
9787 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009788 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00009789 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009790 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009791 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009792
Chris Lattnerf47e3062007-10-13 06:58:48 +00009793 // Otherwise, see if we can simplify the operation with
9794 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009795 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009796 APInt::getLowBitsSet(
9797 Value.getValueType().getScalarType().getSizeInBits(),
9798 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009799 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009800 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009801
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009802 // If this is a load followed by a store to the same location, then the store
9803 // is dead/noop.
9804 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009805 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009806 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009807 // There can't be any side effects between the load and store, such as
9808 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009809 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009810 // The store is dead, remove it.
9811 return Chain;
9812 }
9813 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009814
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009815 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9816 // truncating store. We can do this even if this is already a truncstore.
9817 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009818 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009819 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009820 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009821 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009822 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009823 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009824
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009825 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009826 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009827 if (!LegalTypes) {
9828 bool EverChanged = false;
9829
9830 do {
9831 // There can be multiple store sequences on the same chain.
9832 // Keep trying to merge store sequences until we are unable to do so
9833 // or until we merge the last store on the chain.
9834 bool Changed = MergeConsecutiveStores(ST);
9835 EverChanged |= Changed;
9836 if (!Changed) break;
9837 } while (ST->getOpcode() != ISD::DELETED_NODE);
9838
9839 if (EverChanged)
9840 return SDValue(N, 0);
9841 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009842
Evan Chenga9cda8a2009-05-28 00:35:15 +00009843 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009844}
9845
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009846SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9847 SDValue InVec = N->getOperand(0);
9848 SDValue InVal = N->getOperand(1);
9849 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009850 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009851
Bob Wilson42603952010-05-19 23:42:58 +00009852 // If the inserted element is an UNDEF, just use the input vector.
9853 if (InVal.getOpcode() == ISD::UNDEF)
9854 return InVec;
9855
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009856 EVT VT = InVec.getValueType();
9857
Owen Andersonb2c80da2011-02-25 21:41:48 +00009858 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009859 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9860 return SDValue();
9861
Eli Friedmanb7910b72011-09-09 21:04:06 +00009862 // Check that we know which element is being inserted
9863 if (!isa<ConstantSDNode>(EltNo))
9864 return SDValue();
9865 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009866
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009867 // Canonicalize insert_vector_elt dag nodes.
9868 // Example:
9869 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9870 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9871 //
9872 // Do this only if the child insert_vector node has one use; also
9873 // do this only if indices are both constants and Idx1 < Idx0.
9874 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9875 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9876 unsigned OtherElt =
9877 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9878 if (Elt < OtherElt) {
9879 // Swap nodes.
9880 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9881 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009882 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009883 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9884 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9885 }
9886 }
9887
Eli Friedmanb7910b72011-09-09 21:04:06 +00009888 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9889 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9890 // vector elements.
9891 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009892 // Do not combine these two vectors if the output vector will not replace
9893 // the input vector.
9894 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009895 Ops.append(InVec.getNode()->op_begin(),
9896 InVec.getNode()->op_end());
9897 } else if (InVec.getOpcode() == ISD::UNDEF) {
9898 unsigned NElts = VT.getVectorNumElements();
9899 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9900 } else {
9901 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009902 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009903
9904 // Insert the element
9905 if (Elt < Ops.size()) {
9906 // All the operands of BUILD_VECTOR must have the same type;
9907 // we enforce that here.
9908 EVT OpVT = Ops[0].getValueType();
9909 if (InVal.getValueType() != OpVT)
9910 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9911 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9912 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9913 Ops[Elt] = InVal;
9914 }
9915
9916 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009917 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009918}
9919
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +00009920SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9921 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9922 EVT ResultVT = EVE->getValueType(0);
9923 EVT VecEltVT = InVecVT.getVectorElementType();
9924 unsigned Align = OriginalLoad->getAlignment();
9925 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9926 VecEltVT.getTypeForEVT(*DAG.getContext()));
9927
9928 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9929 return SDValue();
9930
9931 Align = NewAlign;
9932
9933 SDValue NewPtr = OriginalLoad->getBasePtr();
9934 SDValue Offset;
9935 EVT PtrType = NewPtr.getValueType();
9936 MachinePointerInfo MPI;
9937 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9938 int Elt = ConstEltNo->getZExtValue();
9939 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9940 if (TLI.isBigEndian())
9941 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9942 Offset = DAG.getConstant(PtrOff, PtrType);
9943 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9944 } else {
9945 Offset = DAG.getNode(
9946 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9947 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9948 if (TLI.isBigEndian())
9949 Offset = DAG.getNode(
9950 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9951 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9952 MPI = OriginalLoad->getPointerInfo();
9953 }
9954 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9955
9956 // The replacement we need to do here is a little tricky: we need to
9957 // replace an extractelement of a load with a load.
9958 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9959 // Note that this replacement assumes that the extractvalue is the only
9960 // use of the load; that's okay because we don't want to perform this
9961 // transformation in other cases anyway.
9962 SDValue Load;
9963 SDValue Chain;
9964 if (ResultVT.bitsGT(VecEltVT)) {
9965 // If the result type of vextract is wider than the load, then issue an
9966 // extending load instead.
9967 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9968 ? ISD::ZEXTLOAD
9969 : ISD::EXTLOAD;
9970 Load = DAG.getExtLoad(
9971 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9972 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9973 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9974 Chain = Load.getValue(1);
9975 } else {
9976 Load = DAG.getLoad(
9977 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9978 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9979 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9980 Chain = Load.getValue(1);
9981 if (ResultVT.bitsLT(VecEltVT))
9982 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9983 else
9984 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9985 }
9986 WorklistRemover DeadNodes(*this);
9987 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9988 SDValue To[] = { Load, Chain };
9989 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9990 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9991 // worklist explicitly as well.
9992 AddToWorklist(Load.getNode());
9993 AddUsersToWorklist(Load.getNode()); // Add users too
9994 // Make sure to revisit this node to clean it up; it will usually be dead.
9995 AddToWorklist(EVE);
9996 ++OpsNarrowed;
9997 return SDValue(EVE, 0);
9998}
9999
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010000SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000010001 // (vextract (scalar_to_vector val, 0) -> val
10002 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010003 EVT VT = InVec.getValueType();
10004 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010005
Duncan Sands6be291a2011-05-09 08:03:33 +000010006 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10007 // Check if the result type doesn't match the inserted element type. A
10008 // SCALAR_TO_VECTOR may truncate the inserted element and the
10009 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10010 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010011 if (InOp.getValueType() != NVT) {
10012 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010013 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010014 }
10015 return InOp;
10016 }
Evan Cheng1120279a2008-05-13 08:35:03 +000010017
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010018 SDValue EltNo = N->getOperand(1);
10019 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10020
10021 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10022 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000010023 // we may introduce new vector instructions which are not backed by TD
10024 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000010025 // without using extract_subvector. However, if we can find an underlying
10026 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010027 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000010028 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010029 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10030 int NumElem = VT.getVectorNumElements();
10031 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10032 // Find the new index to extract from.
10033 int OrigElt = SVOp->getMaskElt(Elt);
10034
10035 // Extracting an undef index is undef.
10036 if (OrigElt == -1)
10037 return DAG.getUNDEF(NVT);
10038
10039 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000010040 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010041 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000010042 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010043 } else {
Hal Finkel02807592014-03-31 11:43:19 +000010044 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010045 OrigElt -= NumElem;
10046 }
10047
Hal Finkel02807592014-03-31 11:43:19 +000010048 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10049 SDValue InOp = SVInVec.getOperand(OrigElt);
10050 if (InOp.getValueType() != NVT) {
10051 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10052 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10053 }
10054
10055 return InOp;
10056 }
10057
10058 // FIXME: We should handle recursing on other vector shuffles and
10059 // scalar_to_vector here as well.
10060
10061 if (!LegalOperations) {
10062 EVT IndexTy = TLI.getVectorIdxTy();
10063 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10064 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10065 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010066 }
10067
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010068 bool BCNumEltsChanged = false;
10069 EVT ExtVT = VT.getVectorElementType();
10070 EVT LVT = ExtVT;
10071
10072 // If the result of load has to be truncated, then it's not necessarily
10073 // profitable.
10074 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10075 return SDValue();
10076
10077 if (InVec.getOpcode() == ISD::BITCAST) {
10078 // Don't duplicate a load with other uses.
10079 if (!InVec.hasOneUse())
10080 return SDValue();
10081
10082 EVT BCVT = InVec.getOperand(0).getValueType();
10083 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10084 return SDValue();
10085 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10086 BCNumEltsChanged = true;
10087 InVec = InVec.getOperand(0);
10088 ExtVT = BCVT.getVectorElementType();
10089 }
10090
10091 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10092 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10093 ISD::isNormalLoad(InVec.getNode()) &&
10094 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10095 SDValue Index = N->getOperand(1);
10096 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10097 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10098 OrigLoad);
10099 }
10100
Evan Cheng1120279a2008-05-13 08:35:03 +000010101 // Perform only after legalization to ensure build_vector / vector_shuffle
10102 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010103 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010104
Mon P Wangca6d6de2009-01-17 00:07:25 +000010105 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10106 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10107 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000010108
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010109 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000010110 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010111
Craig Topperc0196b12014-04-14 00:51:57 +000010112 LoadSDNode *LN0 = nullptr;
10113 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000010114 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010115 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010116 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000010117 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000010118 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000010119 // Don't duplicate a load with other uses.
10120 if (!InVec.hasOneUse())
10121 return SDValue();
10122
Evan Cheng1120279a2008-05-13 08:35:03 +000010123 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000010124 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010125 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10126 // =>
10127 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000010128
Eli Friedmane96286c2011-12-26 22:49:32 +000010129 // Don't duplicate a load with other uses.
10130 if (!InVec.hasOneUse())
10131 return SDValue();
10132
Mon P Wangb5eb7202008-12-11 00:26:16 +000010133 // If the bit convert changed the number of elements, it is unsafe
10134 // to examine the mask.
10135 if (BCNumEltsChanged)
10136 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010137
10138 // Select the input vector, guarding against out of range extract vector.
10139 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010140 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010141 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10142
Eli Friedmane96286c2011-12-26 22:49:32 +000010143 if (InVec.getOpcode() == ISD::BITCAST) {
10144 // Don't duplicate a load with other uses.
10145 if (!InVec.hasOneUse())
10146 return SDValue();
10147
Evan Cheng1120279a2008-05-13 08:35:03 +000010148 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010149 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010150 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010151 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010152 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010153 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010154 }
10155 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010156
Eli Friedmane96286c2011-12-26 22:49:32 +000010157 // Make sure we found a non-volatile load and the extractelement is
10158 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010159 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010160 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010161
Eric Christopherc6418b12010-11-03 20:44:42 +000010162 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10163 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010164 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010165
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010166 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010167 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010168
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010169 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010170}
Evan Cheng0de312d2007-10-06 08:19:55 +000010171
Michael Liao6d106b72012-10-23 23:06:52 +000010172// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10173SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10174 // We perform this optimization post type-legalization because
10175 // the type-legalizer often scalarizes integer-promoted vectors.
10176 // Performing this optimization before may create bit-casts which
10177 // will be type-legalized to complex code sequences.
10178 // We perform this optimization only before the operation legalizer because we
10179 // may introduce illegal operations.
10180 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10181 return SDValue();
10182
Dan Gohmana8665142007-06-25 16:23:39 +000010183 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010184 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010185 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010186
Nadav Rotembf6568b2011-10-29 21:23:04 +000010187 // Check to see if this is a BUILD_VECTOR of a bunch of values
10188 // which come from any_extend or zero_extend nodes. If so, we can create
10189 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010190 // optimizations. We do not handle sign-extend because we can't fill the sign
10191 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010192 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010193 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010194
Craig Topper02cb0fb2012-01-17 09:09:48 +000010195 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010196 SDValue In = N->getOperand(i);
10197 // Ignore undef inputs.
10198 if (In.getOpcode() == ISD::UNDEF) continue;
10199
10200 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10201 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10202
Nadav Rotemf3103612011-10-31 20:08:25 +000010203 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010204 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010205 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010206 break;
10207 }
10208
10209 // The input is a ZeroExt or AnyExt. Check the original type.
10210 EVT InTy = In.getOperand(0).getValueType();
10211
10212 // Check that all of the widened source types are the same.
10213 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010214 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010215 SourceType = InTy;
10216 else if (InTy != SourceType) {
10217 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010218 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010219 break;
10220 }
10221
10222 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010223 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010224 }
10225
Nadav Rotemf3103612011-10-31 20:08:25 +000010226 // In order to have valid types, all of the inputs must be extended from the
10227 // same source type and all of the inputs must be any or zero extend.
10228 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010229 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010230 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010231 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10232 isPowerOf2_32(SourceType.getSizeInBits());
10233
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010234 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10235 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010236 if (!ValidTypes)
10237 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010238
Michael Liao6d106b72012-10-23 23:06:52 +000010239 bool isLE = TLI.isLittleEndian();
10240 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10241 assert(ElemRatio > 1 && "Invalid element size ratio");
10242 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10243 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010244
Michael Liao6d106b72012-10-23 23:06:52 +000010245 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10246 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010247
Michael Liao6d106b72012-10-23 23:06:52 +000010248 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010249 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010250 SDValue Cast = N->getOperand(i);
10251 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10252 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10253 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10254 SDValue In;
10255 if (Cast.getOpcode() == ISD::UNDEF)
10256 In = DAG.getUNDEF(SourceType);
10257 else
10258 In = Cast->getOperand(0);
10259 unsigned Index = isLE ? (i * ElemRatio) :
10260 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010261
Michael Liao6d106b72012-10-23 23:06:52 +000010262 assert(Index < Ops.size() && "Invalid index");
10263 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010264 }
Chris Lattner5336a592006-03-19 01:27:56 +000010265
Michael Liao6d106b72012-10-23 23:06:52 +000010266 // The type of the new BUILD_VECTOR node.
10267 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10268 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10269 "Invalid vector size");
10270 // Check if the new vector type is legal.
10271 if (!isTypeLegal(VecVT)) return SDValue();
10272
10273 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010274 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010275
10276 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010277 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010278 // Bitcast to the desired type.
10279 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10280}
10281
Michael Liao59229792012-10-24 04:14:18 +000010282SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10283 EVT VT = N->getValueType(0);
10284
10285 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010286 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010287
10288 EVT SrcVT = MVT::Other;
10289 unsigned Opcode = ISD::DELETED_NODE;
10290 unsigned NumDefs = 0;
10291
10292 for (unsigned i = 0; i != NumInScalars; ++i) {
10293 SDValue In = N->getOperand(i);
10294 unsigned Opc = In.getOpcode();
10295
10296 if (Opc == ISD::UNDEF)
10297 continue;
10298
10299 // If all scalar values are floats and converted from integers.
10300 if (Opcode == ISD::DELETED_NODE &&
10301 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10302 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010303 }
Tom Stellard567f8862013-01-02 22:13:01 +000010304
Michael Liao59229792012-10-24 04:14:18 +000010305 if (Opc != Opcode)
10306 return SDValue();
10307
10308 EVT InVT = In.getOperand(0).getValueType();
10309
10310 // If all scalar values are typed differently, bail out. It's chosen to
10311 // simplify BUILD_VECTOR of integer types.
10312 if (SrcVT == MVT::Other)
10313 SrcVT = InVT;
10314 if (SrcVT != InVT)
10315 return SDValue();
10316 NumDefs++;
10317 }
10318
10319 // If the vector has just one element defined, it's not worth to fold it into
10320 // a vectorized one.
10321 if (NumDefs < 2)
10322 return SDValue();
10323
10324 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10325 && "Should only handle conversion from integer to float.");
10326 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10327
10328 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010329
10330 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10331 return SDValue();
10332
Michael Liao59229792012-10-24 04:14:18 +000010333 SmallVector<SDValue, 8> Opnds;
10334 for (unsigned i = 0; i != NumInScalars; ++i) {
10335 SDValue In = N->getOperand(i);
10336
10337 if (In.getOpcode() == ISD::UNDEF)
10338 Opnds.push_back(DAG.getUNDEF(SrcVT));
10339 else
10340 Opnds.push_back(In.getOperand(0));
10341 }
Craig Topper48d114b2014-04-26 18:35:24 +000010342 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010343 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010344
10345 return DAG.getNode(Opcode, dl, VT, BV);
10346}
10347
Michael Liao6d106b72012-10-23 23:06:52 +000010348SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10349 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010350 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010351 EVT VT = N->getValueType(0);
10352
10353 // A vector built entirely of undefs is undef.
10354 if (ISD::allOperandsUndef(N))
10355 return DAG.getUNDEF(VT);
10356
10357 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10358 if (V.getNode())
10359 return V;
10360
Michael Liao59229792012-10-24 04:14:18 +000010361 V = reduceBuildVecConvertToConvertBuildVec(N);
10362 if (V.getNode())
10363 return V;
10364
Dan Gohmana8665142007-06-25 16:23:39 +000010365 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10366 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10367 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010368
10369 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000010370 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010371 return SDValue();
10372
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010373 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010374 for (unsigned i = 0; i != NumInScalars; ++i) {
10375 // Ignore undef inputs.
10376 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010377
Dan Gohmana8665142007-06-25 16:23:39 +000010378 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010379 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010380 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010381 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010382 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010383 break;
10384 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010385
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010386 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010387 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010388 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10389 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010390
Craig Topperc0196b12014-04-14 00:51:57 +000010391 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010392 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010393 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010394 VecIn2 = ExtractedFromVec;
10395 } else {
10396 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010397 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010398 break;
10399 }
10400 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010401
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010402 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010403 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010404 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010405 for (unsigned i = 0; i != NumInScalars; ++i) {
10406 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010407 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010408 continue;
10409 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010410
Rafael Espindolab93db662009-04-24 12:40:33 +000010411 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010412 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010413 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010414 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010415 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10416 if (ExtIndex > VT.getVectorNumElements())
10417 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010418
Nate Begeman5f829d82009-04-29 05:20:52 +000010419 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010420 continue;
10421 }
10422
10423 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010424 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010425 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010426 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010427
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010428 // We can't generate a shuffle node with mismatched input and output types.
10429 // Attempt to transform a single input vector to the correct type.
10430 if ((VT != VecIn1.getValueType())) {
10431 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010432 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010433 return SDValue();
10434
10435 // We only support widening of vectors which are half the size of the
10436 // output registers. For example XMM->YMM widening on X86 with AVX.
10437 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10438 return SDValue();
10439
James Molloy1e5c6112012-09-10 14:01:21 +000010440 // If the input vector type has a different base type to the output
10441 // vector type, bail out.
10442 if (VecIn1.getValueType().getVectorElementType() !=
10443 VT.getVectorElementType())
10444 return SDValue();
10445
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010446 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010447 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010448 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010449 }
10450
10451 // If VecIn2 is unused then change it to undef.
10452 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10453
Nadav Rotem841c9a82012-09-20 08:53:31 +000010454 // Check that we were able to transform all incoming values to the same
10455 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010456 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10457 VecIn1.getValueType() != VT)
10458 return SDValue();
10459
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010460 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010461 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010462 return SDValue();
10463
Dan Gohmana8665142007-06-25 16:23:39 +000010464 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010465 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010466 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010467 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010468 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010469 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010470
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010471 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010472}
10473
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010474SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010475 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10476 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10477 // inputs come from at most two distinct vectors, turn this into a shuffle
10478 // node.
10479
10480 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010481 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010482 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010483
Nadav Rotem01892102012-07-14 21:30:27 +000010484 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010485 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010486 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010487 return DAG.getUNDEF(VT);
10488
10489 // Optimize concat_vectors where one of the vectors is undef.
10490 if (N->getNumOperands() == 2 &&
10491 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10492 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010493 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010494
10495 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10496 if (In->getOpcode() == ISD::BITCAST &&
10497 !In->getOperand(0)->getValueType(0).isVector()) {
10498 SDValue Scalar = In->getOperand(0);
10499 EVT SclTy = Scalar->getValueType(0);
10500
10501 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10502 return SDValue();
10503
10504 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10505 VT.getSizeInBits() / SclTy.getSizeInBits());
10506 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10507 return SDValue();
10508
10509 SDLoc dl = SDLoc(N);
10510 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10511 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10512 }
10513 }
Nadav Rotem01892102012-07-14 21:30:27 +000010514
Robert Lougher7d9084f2014-02-11 15:42:46 +000010515 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10516 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10517 if (N->getNumOperands() == 2 &&
10518 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10519 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10520 EVT VT = N->getValueType(0);
10521 SDValue N0 = N->getOperand(0);
10522 SDValue N1 = N->getOperand(1);
10523 SmallVector<SDValue, 8> Opnds;
10524 unsigned BuildVecNumElts = N0.getNumOperands();
10525
Hao Liu71224b02014-07-10 03:41:50 +000010526 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10527 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10528 if (SclTy0.isFloatingPoint()) {
10529 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10530 Opnds.push_back(N0.getOperand(i));
10531 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10532 Opnds.push_back(N1.getOperand(i));
10533 } else {
10534 // If BUILD_VECTOR are from built from integer, they may have different
10535 // operand types. Get the smaller type and truncate all operands to it.
10536 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10537 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10538 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10539 N0.getOperand(i)));
10540 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10541 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10542 N1.getOperand(i)));
10543 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010544
Craig Topper48d114b2014-04-26 18:35:24 +000010545 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010546 }
10547
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010548 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10549 // nodes often generate nop CONCAT_VECTOR nodes.
10550 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10551 // place the incoming vectors at the exact same location.
10552 SDValue SingleSource = SDValue();
10553 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10554
10555 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10556 SDValue Op = N->getOperand(i);
10557
10558 if (Op.getOpcode() == ISD::UNDEF)
10559 continue;
10560
10561 // Check if this is the identity extract:
10562 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10563 return SDValue();
10564
10565 // Find the single incoming vector for the extract_subvector.
10566 if (SingleSource.getNode()) {
10567 if (Op.getOperand(0) != SingleSource)
10568 return SDValue();
10569 } else {
10570 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010571
10572 // Check the source type is the same as the type of the result.
10573 // If not, this concat may extend the vector, so we can not
10574 // optimize it away.
10575 if (SingleSource.getValueType() != N->getValueType(0))
10576 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010577 }
10578
10579 unsigned IdentityIndex = i * PartNumElem;
10580 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10581 // The extract index must be constant.
10582 if (!CS)
10583 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010584
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010585 // Check that we are reading from the identity index.
10586 if (CS->getZExtValue() != IdentityIndex)
10587 return SDValue();
10588 }
10589
10590 if (SingleSource.getNode())
10591 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010592
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010593 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010594}
10595
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010596SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10597 EVT NVT = N->getValueType(0);
10598 SDValue V = N->getOperand(0);
10599
Michael Liao7a442c802012-10-17 20:48:33 +000010600 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10601 // Combine:
10602 // (extract_subvec (concat V1, V2, ...), i)
10603 // Into:
10604 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010605 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10606 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010607 if (V->getOperand(0).getValueType() != NVT)
10608 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010609 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10610 unsigned NumElems = NVT.getVectorNumElements();
10611 assert((Idx % NumElems) == 0 &&
10612 "IDX in concat is not a multiple of the result vector length.");
10613 return V->getOperand(Idx / NumElems);
10614 }
10615
Michael Liaobb05a1d2013-03-25 23:47:35 +000010616 // Skip bitcasting
10617 if (V->getOpcode() == ISD::BITCAST)
10618 V = V.getOperand(0);
10619
10620 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010621 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010622 // Handle only simple case where vector being inserted and vector
10623 // being extracted are of same type, and are half size of larger vectors.
10624 EVT BigVT = V->getOperand(0).getValueType();
10625 EVT SmallVT = V->getOperand(1).getValueType();
10626 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10627 return SDValue();
10628
10629 // Only handle cases where both indexes are constants with the same type.
10630 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10631 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10632
10633 if (InsIdx && ExtIdx &&
10634 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10635 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10636 // Combine:
10637 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10638 // Into:
10639 // indices are equal or bit offsets are equal => V1
10640 // otherwise => (extract_subvec V1, ExtIdx)
10641 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10642 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10643 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10644 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10645 DAG.getNode(ISD::BITCAST, dl,
10646 N->getOperand(0).getValueType(),
10647 V->getOperand(0)), N->getOperand(1));
10648 }
10649 }
10650
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010651 return SDValue();
10652}
10653
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010654// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10655static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10656 EVT VT = N->getValueType(0);
10657 unsigned NumElts = VT.getVectorNumElements();
10658
10659 SDValue N0 = N->getOperand(0);
10660 SDValue N1 = N->getOperand(1);
10661 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10662
10663 SmallVector<SDValue, 4> Ops;
10664 EVT ConcatVT = N0.getOperand(0).getValueType();
10665 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10666 unsigned NumConcats = NumElts / NumElemsPerConcat;
10667
10668 // Look at every vector that's inserted. We're looking for exact
10669 // subvector-sized copies from a concatenated vector
10670 for (unsigned I = 0; I != NumConcats; ++I) {
10671 // Make sure we're dealing with a copy.
10672 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010673 bool AllUndef = true, NoUndef = true;
10674 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10675 if (SVN->getMaskElt(J) >= 0)
10676 AllUndef = false;
10677 else
10678 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010679 }
10680
Hao Liubc601962013-05-13 02:07:05 +000010681 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010682 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10683 return SDValue();
10684
10685 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10686 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10687 return SDValue();
10688
10689 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10690 if (FirstElt < N0.getNumOperands())
10691 Ops.push_back(N0.getOperand(FirstElt));
10692 else
10693 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10694
10695 } else if (AllUndef) {
10696 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10697 } else { // Mixed with general masks and undefs, can't do optimization.
10698 return SDValue();
10699 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010700 }
10701
Craig Topper48d114b2014-04-26 18:35:24 +000010702 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010703}
10704
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010705SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010706 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010707 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010708
Mon P Wang25f01062008-11-10 04:46:22 +000010709 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010710 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010711
Craig Topper5894fe42012-04-09 05:16:56 +000010712 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010713
Craig Topper279c77b2012-01-04 08:07:43 +000010714 // Canonicalize shuffle undef, undef -> undef
10715 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10716 return DAG.getUNDEF(VT);
10717
10718 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10719
10720 // Canonicalize shuffle v, v -> v, undef
10721 if (N0 == N1) {
10722 SmallVector<int, 8> NewMask;
10723 for (unsigned i = 0; i != NumElts; ++i) {
10724 int Idx = SVN->getMaskElt(i);
10725 if (Idx >= (int)NumElts) Idx -= NumElts;
10726 NewMask.push_back(Idx);
10727 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010728 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010729 &NewMask[0]);
10730 }
10731
10732 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10733 if (N0.getOpcode() == ISD::UNDEF) {
10734 SmallVector<int, 8> NewMask;
10735 for (unsigned i = 0; i != NumElts; ++i) {
10736 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010737 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010738 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010739 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010740 else
10741 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010742 }
10743 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010744 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010745 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010746 &NewMask[0]);
10747 }
10748
10749 // Remove references to rhs if it is undef
10750 if (N1.getOpcode() == ISD::UNDEF) {
10751 bool Changed = false;
10752 SmallVector<int, 8> NewMask;
10753 for (unsigned i = 0; i != NumElts; ++i) {
10754 int Idx = SVN->getMaskElt(i);
10755 if (Idx >= (int)NumElts) {
10756 Idx = -1;
10757 Changed = true;
10758 }
10759 NewMask.push_back(Idx);
10760 }
10761 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010762 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010763 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010764
Bob Wilsonf63da122010-10-28 17:06:14 +000010765 // If it is a splat, check if the argument vector is another splat or a
10766 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010767 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010768 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010769
Dan Gohmana8665142007-06-25 16:23:39 +000010770 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010771 // not the number of vector elements, look through it. Be careful not to
10772 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010773 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010774 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010775 if (ConvInput.getValueType().isVector() &&
10776 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010777 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010778 }
10779
Dan Gohmana8665142007-06-25 16:23:39 +000010780 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010781 assert(V->getNumOperands() == NumElts &&
10782 "BUILD_VECTOR has wrong number of operands");
10783 SDValue Base;
10784 bool AllSame = true;
10785 for (unsigned i = 0; i != NumElts; ++i) {
10786 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10787 Base = V->getOperand(i);
10788 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010789 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010790 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010791 // Splat of <u, u, u, u>, return <u, u, u, u>
10792 if (!Base.getNode())
10793 return N0;
10794 for (unsigned i = 0; i != NumElts; ++i) {
10795 if (V->getOperand(i) != Base) {
10796 AllSame = false;
10797 break;
10798 }
10799 }
10800 // Splat of <x, x, x, x>, return <x, x, x, x>
10801 if (AllSame)
10802 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010803 }
10804 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010805
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010806 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10807 Level < AfterLegalizeVectorOps &&
10808 (N1.getOpcode() == ISD::UNDEF ||
10809 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10810 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10811 SDValue V = partitionShuffleOfConcats(N, DAG);
10812
10813 if (V.getNode())
10814 return V;
10815 }
10816
Nadav Rotemb0783502012-04-01 19:31:22 +000010817 // If this shuffle node is simply a swizzle of another shuffle node,
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010818 // then try to simplify it.
Nadav Rotemb0783502012-04-01 19:31:22 +000010819 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10820 N1.getOpcode() == ISD::UNDEF) {
10821
Nadav Rotemb0783502012-04-01 19:31:22 +000010822 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10823
Craig Topper5894fe42012-04-09 05:16:56 +000010824 // The incoming shuffle must be of the same type as the result of the
10825 // current shuffle.
10826 assert(OtherSV->getOperand(0).getValueType() == VT &&
10827 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010828
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010829 SmallVector<int, 4> Mask;
10830 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010831 for (unsigned i = 0; i != NumElts; ++i) {
10832 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010833 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010834 // Next, this index comes from the first value, which is the incoming
10835 // shuffle. Adopt the incoming index.
10836 if (Idx >= 0)
10837 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010838 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010839 }
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000010840
10841 // Check if all indices in Mask are Undef. In case, propagate Undef.
10842 bool isUndefMask = true;
10843 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10844 isUndefMask &= Mask[i] < 0;
10845
10846 if (isUndefMask)
10847 return DAG.getUNDEF(VT);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010848
10849 bool CommuteOperands = false;
10850 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10851 // To be valid, the combine shuffle mask should only reference elements
10852 // from one of the two vectors in input to the inner shufflevector.
10853 bool IsValidMask = true;
10854 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10855 // See if the combined mask only reference undefs or elements coming
10856 // from the first shufflevector operand.
10857 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010858
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010859 if (!IsValidMask) {
10860 IsValidMask = true;
10861 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10862 // Check that all the elements come from the second shuffle operand.
10863 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10864 CommuteOperands = IsValidMask;
10865 }
10866
10867 // Early exit if the combined shuffle mask is not valid.
10868 if (!IsValidMask)
10869 return SDValue();
10870 }
10871
10872 // See if this pair of shuffles can be safely folded according to either
10873 // of the following rules:
10874 // shuffle(shuffle(x, y), undef) -> x
10875 // shuffle(shuffle(x, undef), undef) -> x
10876 // shuffle(shuffle(x, y), undef) -> y
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010877 bool IsIdentityMask = true;
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010878 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010879 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10880 // Skip Undefs.
10881 if (Mask[i] < 0)
10882 continue;
10883
10884 // The combined shuffle must map each index to itself.
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010885 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010886 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010887
10888 if (IsIdentityMask) {
10889 if (CommuteOperands)
10890 // optimize shuffle(shuffle(x, y), undef) -> y.
10891 return OtherSV->getOperand(1);
10892
10893 // optimize shuffle(shuffle(x, undef), undef) -> x
10894 // optimize shuffle(shuffle(x, y), undef) -> x
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010895 return OtherSV->getOperand(0);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010896 }
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010897
10898 // It may still be beneficial to combine the two shuffles if the
10899 // resulting shuffle is legal.
Andrea Di Biagioace8e1e2014-08-13 16:09:40 +000010900 if (TLI.isTypeLegal(VT)) {
10901 if (!CommuteOperands) {
10902 if (TLI.isShuffleMaskLegal(Mask, VT))
10903 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10904 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10905 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10906 &Mask[0]);
10907 } else {
10908 // Compute the commuted shuffle mask.
10909 for (unsigned i = 0; i != NumElts; ++i) {
10910 int idx = Mask[i];
10911 if (idx < 0)
10912 continue;
10913 else if (idx < (int)NumElts)
10914 Mask[i] = idx + NumElts;
10915 else
10916 Mask[i] = idx - NumElts;
10917 }
10918
10919 if (TLI.isShuffleMaskLegal(Mask, VT))
10920 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10921 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10922 &Mask[0]);
10923 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010924 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010925 }
10926
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000010927 // Canonicalize shuffles according to rules:
10928 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10929 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10930 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10931 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10932 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10933 TLI.isTypeLegal(VT)) {
10934 // The incoming shuffle must be of the same type as the result of the
10935 // current shuffle.
10936 assert(N1->getOperand(0).getValueType() == VT &&
10937 "Shuffle types don't match");
10938
10939 SDValue SV0 = N1->getOperand(0);
10940 SDValue SV1 = N1->getOperand(1);
10941 bool HasSameOp0 = N0 == SV0;
10942 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10943 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10944 // Commute the operands of this shuffle so that next rule
10945 // will trigger.
10946 return DAG.getCommutedVectorShuffle(*SVN);
10947 }
10948
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010949 // Try to fold according to rules:
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010950 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10951 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10952 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10953 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010954 // Don't try to fold shuffles with illegal type.
10955 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010956 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010957 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10958
10959 // The incoming shuffle must be of the same type as the result of the
10960 // current shuffle.
10961 assert(OtherSV->getOperand(0).getValueType() == VT &&
10962 "Shuffle types don't match");
10963
10964 SDValue SV0 = OtherSV->getOperand(0);
10965 SDValue SV1 = OtherSV->getOperand(1);
10966 bool HasSameOp0 = N1 == SV0;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010967 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10968 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010969 // Early exit.
10970 return SDValue();
10971
10972 SmallVector<int, 4> Mask;
10973 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10974 // operand, and SV1 as the second operand.
10975 for (unsigned i = 0; i != NumElts; ++i) {
10976 int Idx = SVN->getMaskElt(i);
10977 if (Idx < 0) {
10978 // Propagate Undef.
10979 Mask.push_back(Idx);
10980 continue;
10981 }
10982
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010983 if (Idx < (int)NumElts) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010984 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010985 if (IsSV1Undef && Idx >= (int) NumElts)
10986 Idx = -1; // Propagate Undef.
10987 } else
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010988 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10989
10990 Mask.push_back(Idx);
10991 }
10992
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000010993 // Check if all indices in Mask are Undef. In case, propagate Undef.
10994 bool isUndefMask = true;
10995 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10996 isUndefMask &= Mask[i] < 0;
10997
10998 if (isUndefMask)
10999 return DAG.getUNDEF(VT);
11000
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011001 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011002 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11003 if (IsSV1Undef)
11004 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11005 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11006 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011007 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011008 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011009 }
11010
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011011 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011012}
11013
Manman Ren413a6cb2014-01-31 01:10:35 +000011014SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11015 SDValue N0 = N->getOperand(0);
11016 SDValue N2 = N->getOperand(2);
11017
11018 // If the input vector is a concatenation, and the insert replaces
11019 // one of the halves, we can optimize into a single concat_vectors.
11020 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11021 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11022 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11023 EVT VT = N->getValueType(0);
11024
11025 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11026 // (concat_vectors Z, Y)
11027 if (InsIdx == 0)
11028 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11029 N->getOperand(1), N0.getOperand(1));
11030
11031 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11032 // (concat_vectors X, Z)
11033 if (InsIdx == VT.getVectorNumElements()/2)
11034 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11035 N0.getOperand(0), N->getOperand(1));
11036 }
11037
11038 return SDValue();
11039}
11040
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011041/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11042/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000011043/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000011044/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011045SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011046 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011047 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011048 SDValue LHS = N->getOperand(0);
11049 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000011050 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000011051 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000011052 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011053 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011054 SmallVector<int, 8> Indices;
11055 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000011056 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011057 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011058 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011059 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000011060
11061 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011062 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011063 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011064 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000011065 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011066 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011067 }
11068
11069 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011070 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011071 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011072 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011073
Dan Gohmana8665142007-06-25 16:23:39 +000011074 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000011075 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011076 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000011077 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000011078 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000011079 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011080 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000011081 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000011082 }
11083 }
Bill Wendling31b50992009-01-30 23:59:18 +000011084
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011085 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011086}
11087
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011088/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011089SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000011090 assert(N->getValueType(0).isVector() &&
11091 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000011092
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011093 SDValue LHS = N->getOperand(0);
11094 SDValue RHS = N->getOperand(1);
11095 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011096 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000011097
Dan Gohmana8665142007-06-25 16:23:39 +000011098 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000011099 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011100 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000011101 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000011102 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000011103 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11104 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000011105 return SDValue();
11106
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011107 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000011108 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011109 SDValue LHSOp = LHS.getOperand(i);
11110 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000011111
Evan Cheng64d28462006-05-31 06:08:35 +000011112 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000011113 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11114 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000011115 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011116 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000011117 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011118 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000011119 break;
11120 }
Bill Wendling31b50992009-01-30 23:59:18 +000011121
Bob Wilson54081442010-12-17 23:06:49 +000011122 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000011123 EVT RVT = RHSOp.getValueType();
11124 if (RVT != VT) {
11125 // Integer BUILD_VECTOR operands may have types larger than the element
11126 // size (e.g., when the element type is not legal). Prior to type
11127 // legalization, the types may not match between the two BUILD_VECTORS.
11128 // Truncate one of the operands to make them match.
11129 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011130 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011131 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011132 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011133 VT = RVT;
11134 }
11135 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011136 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000011137 LHSOp, RHSOp);
11138 if (FoldOp.getOpcode() != ISD::UNDEF &&
11139 FoldOp.getOpcode() != ISD::Constant &&
11140 FoldOp.getOpcode() != ISD::ConstantFP)
11141 break;
11142 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011143 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000011144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011145
Bob Wilson54081442010-12-17 23:06:49 +000011146 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000011147 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000011148 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011149
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011150 // Type legalization might introduce new shuffles in the DAG.
11151 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11152 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11153 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11154 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11155 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11156 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11157 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11158 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11159
11160 if (SVN0->getMask().equals(SVN1->getMask())) {
11161 EVT VT = N->getValueType(0);
11162 SDValue UndefVector = LHS.getOperand(1);
11163 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11164 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011165 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011166 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11167 &SVN0->getMask()[0]);
11168 }
11169 }
11170
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011171 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011172}
11173
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011174/// Visit a binary vector operation, like FABS/FNEG.
Craig Topper82384612012-09-11 01:45:21 +000011175SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011176 assert(N->getValueType(0).isVector() &&
11177 "SimplifyVUnaryOp only works on vectors!");
11178
11179 SDValue N0 = N->getOperand(0);
11180
11181 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11182 return SDValue();
11183
11184 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11185 SmallVector<SDValue, 8> Ops;
11186 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11187 SDValue Op = N0.getOperand(i);
11188 if (Op.getOpcode() != ISD::UNDEF &&
11189 Op.getOpcode() != ISD::ConstantFP)
11190 break;
11191 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011192 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011193 if (FoldOp.getOpcode() != ISD::UNDEF &&
11194 FoldOp.getOpcode() != ISD::ConstantFP)
11195 break;
11196 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011197 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011198 }
11199
11200 if (Ops.size() != N0.getNumOperands())
11201 return SDValue();
11202
Craig Topper48d114b2014-04-26 18:35:24 +000011203 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011204}
11205
Andrew Trickef9de2a2013-05-25 02:42:55 +000011206SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011207 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011208 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011209
Bill Wendling31b50992009-01-30 23:59:18 +000011210 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011211 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011212
Nate Begeman2042aa52005-10-08 00:29:44 +000011213 // If we got a simplified select_cc node back from SimplifySelectCC, then
11214 // break it down into a new SETCC node, and a new SELECT node, and then return
11215 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011216 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011217 // Check to see if we got a select_cc back (to turn into setcc/select).
11218 // Otherwise, just return whatever node we got back, like fabs.
11219 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011220 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011221 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011222 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011223 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011224 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000011225 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11226 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000011227 }
Bill Wendling31b50992009-01-30 23:59:18 +000011228
Nate Begeman2042aa52005-10-08 00:29:44 +000011229 return SCC;
11230 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011231 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011232}
11233
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011234/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11235/// being selected between, see if we can simplify the select. Callers of this
11236/// should assume that TheSelect is deleted if this returns true. As such, they
11237/// should return the appropriate thing (e.g. the node) back to the top-level of
11238/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011239bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011240 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011241
Nadav Rotema49a02a2011-02-11 19:57:47 +000011242 // Cannot simplify select with vector condition
11243 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11244
Chris Lattner6c14c352005-10-18 06:04:22 +000011245 // If this is a select from two identical things, try to pull the operation
11246 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011247 if (LHS.getOpcode() != RHS.getOpcode() ||
11248 !LHS.hasOneUse() || !RHS.hasOneUse())
11249 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011250
Chris Lattner254c4452010-09-21 15:46:59 +000011251 // If this is a load and the token chain is identical, replace the select
11252 // of two loads with a load through a select of the address to load from.
11253 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11254 // constants have been dropped into the constant pool.
11255 if (LHS.getOpcode() == ISD::LOAD) {
11256 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11257 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011258
Chris Lattner254c4452010-09-21 15:46:59 +000011259 // Token chains must be identical.
11260 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011261 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011262 LLD->isVolatile() || RLD->isVolatile() ||
11263 // If this is an EXTLOAD, the VT's must match.
11264 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011265 // If this is an EXTLOAD, the kind of extension must match.
11266 (LLD->getExtensionType() != RLD->getExtensionType() &&
11267 // The only exception is if one of the extensions is anyext.
11268 LLD->getExtensionType() != ISD::EXTLOAD &&
11269 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011270 // FIXME: this discards src value information. This is
11271 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011272 // both potential memory locations. Since we are discarding
11273 // src value info, don't do the transformation if the memory
11274 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011275 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011276 RLD->getPointerInfo().getAddrSpace() != 0 ||
11277 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11278 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011279 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011280
Chris Lattnere3267522010-09-21 15:58:55 +000011281 // Check that the select condition doesn't reach either load. If so,
11282 // folding this will induce a cycle into the DAG. If not, this is safe to
11283 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011284 SDValue Addr;
11285 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011286 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11287 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11288 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11289 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011290 // The loads must not depend on one another.
11291 if (LLD->isPredecessorOf(RLD) ||
11292 RLD->isPredecessorOf(LLD))
11293 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011294 Addr = DAG.getSelect(SDLoc(TheSelect),
11295 LLD->getBasePtr().getValueType(),
11296 TheSelect->getOperand(0), LLD->getBasePtr(),
11297 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011298 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011299 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11300 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11301
11302 if ((LLD->hasAnyUseOfValue(1) &&
11303 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011304 (RLD->hasAnyUseOfValue(1) &&
11305 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011306 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011307
Andrew Trickef9de2a2013-05-25 02:42:55 +000011308 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011309 LLD->getBasePtr().getValueType(),
11310 TheSelect->getOperand(0),
11311 TheSelect->getOperand(1),
11312 LLD->getBasePtr(), RLD->getBasePtr(),
11313 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011314 }
11315
Chris Lattnere3267522010-09-21 15:58:55 +000011316 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000011317 // It is safe to replace the two loads if they have different alignments,
11318 // but the new load must be the minimum (most restrictive) alignment of the
11319 // inputs.
Louis Gerbarg67474e32014-07-31 21:45:05 +000011320 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000011321 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011322 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11323 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011324 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000011325 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011326 LLD->getChain(), Addr, MachinePointerInfo(),
11327 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011328 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000011329 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011330 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11331 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011332 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011333 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000011334 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011335 LLD->getChain(), Addr, MachinePointerInfo(),
11336 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011337 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000011338 }
Chris Lattnere3267522010-09-21 15:58:55 +000011339
11340 // Users of the select now use the result of the load.
11341 CombineTo(TheSelect, Load);
11342
11343 // Users of the old loads now use the new load's chain. We know the
11344 // old-load value is dead now.
11345 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11346 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11347 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011348 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011349
Chris Lattner6c14c352005-10-18 06:04:22 +000011350 return false;
11351}
11352
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011353/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000011354/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011355SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011356 SDValue N2, SDValue N3,
11357 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011358 // (x ? y : y) -> y.
11359 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011360
Owen Anderson53aa7a92009-08-10 22:56:29 +000011361 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011362 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11363 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11364 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011365
11366 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011367 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011368 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011369 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011370 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011371
11372 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011373 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011374 return N2;
11375 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011376 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011377 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011378
Nate Begeman2042aa52005-10-08 00:29:44 +000011379 // Check to see if we can simplify the select into an fabs node
11380 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11381 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011382 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011383 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11384 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11385 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11386 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011387 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011388
Nate Begeman2042aa52005-10-08 00:29:44 +000011389 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11390 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11391 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11392 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011393 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011394 }
11395 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011396
Chris Lattner43d63772009-03-11 05:08:08 +000011397 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11398 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11399 // in it. This is a win when the constant is not otherwise available because
11400 // it replaces two constant pool loads with one. We only do this if the FP
11401 // type is known to be legal, because if it isn't, then we are before legalize
11402 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011403 // messing with soft float) and if the ConstantFP is not legal, because if
11404 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011405 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11406 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11407 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011408 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011409 TargetLowering::Legal &&
11410 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11411 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011412 // If both constants have multiple uses, then we won't need to do an
11413 // extra load, they are likely around in registers for other users.
11414 (TV->hasOneUse() || FV->hasOneUse())) {
11415 Constant *Elts[] = {
11416 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11417 const_cast<ConstantFP*>(TV->getConstantFPValue())
11418 };
Chris Lattner229907c2011-07-18 04:54:35 +000011419 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011420 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011421
Chris Lattner43d63772009-03-11 05:08:08 +000011422 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011423 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011424 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11425 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011426 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011427
11428 // Get the offsets to the 0 and 1 element of the array so that we can
11429 // select between them.
11430 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011431 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011432 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011433
Chris Lattner43d63772009-03-11 05:08:08 +000011434 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011435 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011436 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011437 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011438 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11439 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011440 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011441 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011442 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011443 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011444 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011445 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011446 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011447
11448 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011450
Nate Begeman2042aa52005-10-08 00:29:44 +000011451 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011452 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011453 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011454 (N1C->isNullValue() || // (a < 0) ? b : 0
11455 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011456 EVT XType = N0.getValueType();
11457 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011458 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011459 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011460 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011461 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11462 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011463 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011464 SDValue ShCt = DAG.getConstant(ShCtV,
11465 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011466 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011467 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011468 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011469
Duncan Sands11dd4242008-06-08 20:54:56 +000011470 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011471 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011472 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011473 }
Bill Wendling31b50992009-01-30 23:59:18 +000011474
11475 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011476 }
Bill Wendling31b50992009-01-30 23:59:18 +000011477
Andrew Trickef9de2a2013-05-25 02:42:55 +000011478 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011479 XType, N0,
11480 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011481 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011482 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011483
Duncan Sands11dd4242008-06-08 20:54:56 +000011484 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011485 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011486 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011487 }
Bill Wendling31b50992009-01-30 23:59:18 +000011488
11489 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011490 }
11491 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011492
Owen Anderson3231d132010-09-22 22:58:22 +000011493 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11494 // where y is has a single bit set.
11495 // A plaintext description would be, we can turn the SELECT_CC into an AND
11496 // when the condition can be materialized as an all-ones register. Any
11497 // single bit-test can be materialized as an all-ones register with
11498 // shift-left and shift-right-arith.
11499 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11500 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011501 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011502 N2C && N2C->isNullValue()) {
11503 SDValue AndLHS = N0->getOperand(0);
11504 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11505 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11506 // Shift the tested bit over the sign bit.
11507 APInt AndMask = ConstAndRHS->getAPIntValue();
11508 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011509 DAG.getConstant(AndMask.countLeadingZeros(),
11510 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011511 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011512
Owen Anderson3231d132010-09-22 22:58:22 +000011513 // Now arithmetic right shift it all the way over, so the result is either
11514 // all-ones, or zero.
11515 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011516 DAG.getConstant(AndMask.getBitWidth()-1,
11517 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011518 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011519
Owen Anderson3231d132010-09-22 22:58:22 +000011520 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11521 }
11522 }
11523
Nate Begeman6828ed92005-10-10 21:26:48 +000011524 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011525 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011526 TLI.getBooleanContents(N0.getValueType()) ==
11527 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011528
Chris Lattnera083ffc2007-04-11 06:50:51 +000011529 // If the caller doesn't want us to simplify this into a zext of a compare,
11530 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011531 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011532 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011533
Nate Begeman6828ed92005-10-10 21:26:48 +000011534 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011535 // NOTE: Don't create a SETCC if it's not legal on this target.
11536 if (!LegalOperations ||
11537 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011538 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011539 SDValue Temp, SCC;
11540 // cast from setcc result type to select result type
11541 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011542 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011543 N0, N1, CC);
11544 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011545 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011546 N2.getValueType());
11547 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011548 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011549 N2.getValueType(), SCC);
11550 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011551 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11552 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011553 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011554 }
11555
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011556 AddToWorklist(SCC.getNode());
11557 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011558
11559 if (N2C->getAPIntValue() == 1)
11560 return Temp;
11561
11562 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011563 return DAG.getNode(
11564 ISD::SHL, DL, N2.getValueType(), Temp,
11565 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11566 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011567 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011568 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011569
Nate Begeman2042aa52005-10-08 00:29:44 +000011570 // Check to see if this is the equivalent of setcc
11571 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11572 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011573 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011574 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011575 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011576 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11577 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011578 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011579 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011580 return Res;
11581 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011582
Bill Wendling31b50992009-01-30 23:59:18 +000011583 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011584 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011585 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011586 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011587 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011588 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011589 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011590 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011591 }
Bill Wendling31b50992009-01-30 23:59:18 +000011592 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011593 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011594 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011595 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011596 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011597 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011598 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011599 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011600 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011601 }
Bill Wendling31b50992009-01-30 23:59:18 +000011602 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011603 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011604 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011605 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011606 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011607 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011608 }
11609 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011610
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011611 // Check to see if this is an integer abs.
11612 // select_cc setg[te] X, 0, X, -X ->
11613 // select_cc setgt X, -1, X, -X ->
11614 // select_cc setl[te] X, 0, -X, X ->
11615 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011616 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011617 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011618 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011619 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11620 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11621 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11622 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11623 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11624 (N1C->isOne() && CC == ISD::SETLT)) &&
11625 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11626 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11627
Owen Anderson53aa7a92009-08-10 22:56:29 +000011628 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011629 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011630 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011631 N0,
11632 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011633 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011634 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011635 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011636 AddToWorklist(Shift.getNode());
11637 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011638 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011639 }
11640 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011641
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011642 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011643}
11644
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011645/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011646SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011647 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011648 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011649 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011650 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011651 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011652}
11653
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011654/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000011655/// a DAG expression to select that will generate the same value by multiplying
11656/// by a magic number. See:
Nate Begemanc6f067a2005-10-20 02:15:44 +000011657/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011658SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011659 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11660 if (!C)
11661 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011662
11663 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011664 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011665 return SDValue();
11666
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011667 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011668 SDValue S =
11669 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011670
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011671 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011672 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011673 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011674}
11675
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011676/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11677/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000011678SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11679 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11680 if (!C)
11681 return SDValue();
11682
11683 // Avoid division by zero.
11684 if (!C->getAPIntValue())
11685 return SDValue();
11686
11687 std::vector<SDNode *> Built;
11688 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11689
11690 for (SDNode *N : Built)
11691 AddToWorklist(N);
11692 return S;
11693}
11694
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011695/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11696/// expression that will generate the same value by multiplying by a magic
11697/// number. See:
Nate Begemanc6f067a2005-10-20 02:15:44 +000011698/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011699SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011700 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11701 if (!C)
11702 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011703
11704 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011705 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011706 return SDValue();
11707
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011708 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011709 SDValue S =
11710 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011711
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011712 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011713 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011714 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011715}
11716
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011717/// Return true if base is a frame index, which is known not to alias with
11718/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000011719static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011720 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011721 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011722 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011723
Jim Laskey0463e082006-10-07 23:37:56 +000011724 // If it's an adding a simple constant then integrate the offset.
11725 if (Base.getOpcode() == ISD::ADD) {
11726 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11727 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011728 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011729 }
11730 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011731
Nate Begeman18150d52009-09-25 06:05:26 +000011732 // Return the underlying GlobalValue, and update the Offset. Return false
11733 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11734 // by multiple nodes with different offsets.
11735 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11736 GV = G->getGlobal();
11737 Offset += G->getOffset();
11738 return false;
11739 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011740
Nate Begeman18150d52009-09-25 06:05:26 +000011741 // Return the underlying Constant value, and update the Offset. Return false
11742 // for ConstantSDNodes since the same constant pool entry may be represented
11743 // by multiple nodes with different offsets.
11744 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011745 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11746 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011747 Offset += C->getOffset();
11748 return false;
11749 }
Jim Laskey0463e082006-10-07 23:37:56 +000011750 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011751 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011752}
11753
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011754/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011755bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011756 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011757 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011758
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011759 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011760 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011761
Jim Laskey0463e082006-10-07 23:37:56 +000011762 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011763 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011764 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011765 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011766 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011767 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11768 Base1, Offset1, GV1, CV1);
11769 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11770 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011771
Nate Begeman18150d52009-09-25 06:05:26 +000011772 // If they have a same base address then check to see if they overlap.
11773 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011774 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11775 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011776
Owen Anderson272ff942010-09-20 20:39:59 +000011777 // It is possible for different frame indices to alias each other, mostly
11778 // when tail call optimization reuses return address slots for arguments.
11779 // To catch this case, look up the actual index of frame indices to compute
11780 // the real alias relationship.
11781 if (isFrameIndex1 && isFrameIndex2) {
11782 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11783 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11784 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011785 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11786 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011787 }
11788
Wesley Peck527da1b2010-11-23 03:31:01 +000011789 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011790 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011791 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11792 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011793
Nate Begeman879d8f12009-09-15 00:18:30 +000011794 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11795 // compared to the size and offset of the access, we may be able to prove they
11796 // do not alias. This check is conservative for now to catch cases created by
11797 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011798 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11799 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11800 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11801 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11802 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11803 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11804 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011805
Nate Begeman879d8f12009-09-15 00:18:30 +000011806 // There is no overlap between these relatively aligned accesses of similar
11807 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011808 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11809 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011810 return false;
11811 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011812
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011813 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11814 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011815#ifndef NDEBUG
11816 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11817 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11818 UseAA = false;
11819#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011820 if (UseAA &&
11821 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011822 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011823 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11824 Op1->getSrcValueOffset());
11825 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11826 Op0->getSrcValueOffset() - MinOffset;
11827 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11828 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011829 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011830 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11831 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000011832 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011833 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11834 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000011835 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011836 if (AAResult == AliasAnalysis::NoAlias)
11837 return false;
11838 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011839
11840 // Otherwise we have to assume they alias.
11841 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011842}
11843
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011844/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000011845/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011846void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011847 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011848 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011849 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011850
Jim Laskeyd07be232006-09-25 16:29:54 +000011851 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011852 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011853
Jim Laskey708d0db2006-10-04 16:53:27 +000011854 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011855 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011856 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011857
Jim Laskey6549d222006-10-05 15:07:25 +000011858 // Look at each chain and determine if it is an alias. If so, add it to the
11859 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011860 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011861 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011862 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011863 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011864
11865 // For TokenFactor nodes, look at each operand and only continue up the
11866 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011867 // find more and revert to original chain since the xform is unlikely to be
11868 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011869 //
11870 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011871 // chain we found before we hit a tokenfactor rather than the original
11872 // chain.
11873 if (Depth > 6 || Aliases.size() == 2) {
11874 Aliases.clear();
11875 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011876 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011877 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011878
Nate Begeman879d8f12009-09-15 00:18:30 +000011879 // Don't bother if we've been before.
11880 if (!Visited.insert(Chain.getNode()))
11881 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011882
Jim Laskey6549d222006-10-05 15:07:25 +000011883 switch (Chain.getOpcode()) {
11884 case ISD::EntryToken:
11885 // Entry token is ideal chain operand, but handled in FindBetterChain.
11886 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011887
Jim Laskey6549d222006-10-05 15:07:25 +000011888 case ISD::LOAD:
11889 case ISD::STORE: {
11890 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011891 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11892 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011893
Jim Laskey6549d222006-10-05 15:07:25 +000011894 // If chain is alias then stop here.
11895 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011896 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011897 Aliases.push_back(Chain);
11898 } else {
11899 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011900 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011901 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011902 }
Jim Laskey6549d222006-10-05 15:07:25 +000011903 break;
11904 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011905
Jim Laskey6549d222006-10-05 15:07:25 +000011906 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011907 // We have to check each of the operands of the token factor for "small"
11908 // token factors, so we queue them up. Adding the operands to the queue
11909 // (stack) in reverse order maintains the original order and increases the
11910 // likelihood that getNode will find a matching token factor (CSE.)
11911 if (Chain.getNumOperands() > 16) {
11912 Aliases.push_back(Chain);
11913 break;
11914 }
Jim Laskey6549d222006-10-05 15:07:25 +000011915 for (unsigned n = Chain.getNumOperands(); n;)
11916 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011917 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011918 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011919
Jim Laskey6549d222006-10-05 15:07:25 +000011920 default:
11921 // For all other instructions we will just have to take what we can get.
11922 Aliases.push_back(Chain);
11923 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011924 }
11925 }
Hal Finkel51a98382014-01-24 20:12:02 +000011926
11927 // We need to be careful here to also search for aliases through the
11928 // value operand of a store, etc. Consider the following situation:
11929 // Token1 = ...
11930 // L1 = load Token1, %52
11931 // S1 = store Token1, L1, %51
11932 // L2 = load Token1, %52+8
11933 // S2 = store Token1, L2, %51+8
11934 // Token2 = Token(S1, S2)
11935 // L3 = load Token2, %53
11936 // S3 = store Token2, L3, %52
11937 // L4 = load Token2, %53+8
11938 // S4 = store Token2, L4, %52+8
11939 // If we search for aliases of S3 (which loads address %52), and we look
11940 // only through the chain, then we'll miss the trivial dependence on L1
11941 // (which also loads from %52). We then might change all loads and
11942 // stores to use Token1 as their chain operand, which could result in
11943 // copying %53 into %52 before copying %52 into %51 (which should
11944 // happen first).
11945 //
11946 // The problem is, however, that searching for such data dependencies
11947 // can become expensive, and the cost is not directly related to the
11948 // chain depth. Instead, we'll rule out such configurations here by
11949 // insisting that we've visited all chain users (except for users
11950 // of the original chain, which is not necessary). When doing this,
11951 // we need to look through nodes we don't care about (otherwise, things
11952 // like register copies will interfere with trivial cases).
11953
11954 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000011955 for (const SDNode *N : Visited)
11956 if (N != OriginalChain.getNode())
11957 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000011958
11959 while (!Worklist.empty()) {
11960 const SDNode *M = Worklist.pop_back_val();
11961
11962 // We have already visited M, and want to make sure we've visited any uses
11963 // of M that we care about. For uses that we've not visisted, and don't
11964 // care about, queue them to the worklist.
11965
11966 for (SDNode::use_iterator UI = M->use_begin(),
11967 UIE = M->use_end(); UI != UIE; ++UI)
11968 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11969 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11970 // We've not visited this use, and we care about it (it could have an
11971 // ordering dependency with the original node).
11972 Aliases.clear();
11973 Aliases.push_back(OriginalChain);
11974 return;
11975 }
11976
11977 // We've not visited this use, but we don't care about it. Mark it as
11978 // visited and enqueue it to the worklist.
11979 Worklist.push_back(*UI);
11980 }
11981 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011982}
11983
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011984/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11985/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011986SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11987 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011988
Jim Laskey708d0db2006-10-04 16:53:27 +000011989 // Accumulate all the aliases to this node.
11990 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011991
Dan Gohman4298df62011-05-17 22:20:36 +000011992 // If no operands then chain to entry token.
11993 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011994 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011995
11996 // If a single operand then chain to it. We don't need to revisit it.
11997 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011998 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011999
Jim Laskey708d0db2006-10-04 16:53:27 +000012000 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000012001 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000012002}
12003
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012004/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000012005void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000012006 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012007 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000012008 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000012009}