blob: 7dc79a4bfeec8fa46e03f7170026629b15dd2b22 [file] [log] [blame]
Nate Begeman2504fe22005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman21158fc2005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman21158fc2005-09-01 00:19:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012//
Dan Gohman45399872009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman21158fc2005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
Nate Begeman21158fc2005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000020#include "llvm/ADT/SetVector.h"
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000021#include "llvm/ADT/SmallBitVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000032#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000034#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043#define DEBUG_TYPE "dagcombine"
44
Chris Lattneraee775a2006-12-19 22:41:21 +000045STATISTIC(NodesCombined , "Number of dag nodes combined");
46STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000048STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000049STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000050STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000051
Nate Begeman21158fc2005-09-01 00:19:25 +000052namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000053 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000054 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000055 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000056
Jim Laskey55e4dca2006-10-18 19:08:31 +000057 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000059 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000060
Hal Finkeldbebb522014-01-25 19:24:54 +000061 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000062 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000063 cl::desc("Enable DAG combiner's use of TBAA"));
64
Hal Finkel9b2617a2014-01-25 17:32:39 +000065#ifndef NDEBUG
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
69 " function"));
70#endif
71
Quentin Colombetde0e0622013-10-11 18:29:42 +000072 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
74 static cl::opt<bool>
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
77 "slicing"),
78 cl::init(false));
79
Hal Finkel51e6fa22014-09-02 06:24:04 +000080 static cl::opt<bool>
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
83
Jim Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
Chandler Carruth9a0051c2014-07-23 07:08:53 +000095 /// \brief Worklist of all of the nodes that need to be simplified.
96 ///
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
99 ///
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
103
104 /// \brief Mapping from an SDNode to its position on the worklist.
105 ///
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000110
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000111 /// \brief Set of nodes which have been combined (at least once).
112 ///
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
116
Jim Laskeydcb2b832006-10-16 20:52:31 +0000117 // AA - Used for DAG load/store alias analysis.
118 AliasAnalysis &AA;
119
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000123 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000124 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000125 }
126
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000127 /// Call the node-specific routine that folds each particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000128 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000129
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000130 public:
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000131 /// Add to the worklist making sure its instance is at the back (next to be
132 /// processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000133 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
137 return;
138
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000141 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000142
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000143 /// Remove all instances of N from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000144 void removeFromWorklist(SDNode *N) {
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000145 CombinedNodes.erase(N);
146
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
150
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000155
Chandler Carruth18066972014-08-02 10:02:07 +0000156 void deleteAndRecombine(SDNode *N);
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000157 bool recursivelyDeleteUnusedNodes(SDNode *N);
158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000160 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000161
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000163 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000164 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000167 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000168 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000169 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000170 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000171
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000173
174 private:
175
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000179 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000182 return SimplifyDemandedBits(Op, Demanded);
183 }
184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000186
Chris Lattnerffad2162006-11-11 00:39:41 +0000187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
Hal Finkel51e6fa22014-09-02 06:24:04 +0000189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000190 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000191
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193 /// load.
194 ///
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000206 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000207 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000210
Craig Toppere0b71182013-07-13 07:43:40 +0000211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000213 ISD::NodeType ExtType);
214
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000215 /// Call the node-specific routine that knows how to fold each
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000218 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000219
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
222 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000226 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000232 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000234 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
Matthias Braun3ecb5572015-03-06 19:49:06 +0000249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000250 SDValue visitOR(SDNode *N);
Matthias Braun3ecb5572015-03-06 19:49:06 +0000251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000254 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000255 SDValue visitSHL(SDNode *N);
256 SDValue visitSRA(SDNode *N);
257 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000258 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000259 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000260 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000262 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000263 SDValue visitCTPOP(SDNode *N);
264 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000265 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000266 SDValue visitSELECT_CC(SDNode *N);
267 SDValue visitSETCC(SDNode *N);
268 SDValue visitSIGN_EXTEND(SDNode *N);
269 SDValue visitZERO_EXTEND(SDNode *N);
270 SDValue visitANY_EXTEND(SDNode *N);
271 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
272 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000273 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000274 SDValue visitBUILD_PAIR(SDNode *N);
275 SDValue visitFADD(SDNode *N);
276 SDValue visitFSUB(SDNode *N);
277 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000278 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000279 SDValue visitFDIV(SDNode *N);
280 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000281 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000282 SDValue visitFCOPYSIGN(SDNode *N);
283 SDValue visitSINT_TO_FP(SDNode *N);
284 SDValue visitUINT_TO_FP(SDNode *N);
285 SDValue visitFP_TO_SINT(SDNode *N);
286 SDValue visitFP_TO_UINT(SDNode *N);
287 SDValue visitFP_ROUND(SDNode *N);
288 SDValue visitFP_ROUND_INREG(SDNode *N);
289 SDValue visitFP_EXTEND(SDNode *N);
290 SDValue visitFNEG(SDNode *N);
291 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000292 SDValue visitFCEIL(SDNode *N);
293 SDValue visitFTRUNC(SDNode *N);
294 SDValue visitFFLOOR(SDNode *N);
Matt Arsenault7c936902014-10-21 23:01:01 +0000295 SDValue visitFMINNUM(SDNode *N);
296 SDValue visitFMAXNUM(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000297 SDValue visitBRCOND(SDNode *N);
298 SDValue visitBR_CC(SDNode *N);
299 SDValue visitLOAD(SDNode *N);
300 SDValue visitSTORE(SDNode *N);
301 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
302 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
303 SDValue visitBUILD_VECTOR(SDNode *N);
304 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000305 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000306 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +0000307 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000308 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +0000309 SDValue visitMLOAD(SDNode *N);
310 SDValue visitMSTORE(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000311
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000312 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000313 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000314
Matt Arsenault985b9de2014-03-17 18:58:01 +0000315 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000317 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
318 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000319 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
320 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000321 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000322 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000323 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000324 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000325
326 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
327 SDValue &CC) const;
328 bool isOneUseSetCC(SDValue N) const;
329
Scott Michelcf0da6c2009-02-17 22:15:04 +0000330 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000331 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000332 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Ahmed Bougachae892d132015-02-05 18:31:02 +0000333 SDValue CombineExtLoad(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000334 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000335 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000336 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000337 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000338 SDValue BuildReciprocalEstimate(SDValue Op);
339 SDValue BuildRsqrtEstimate(SDValue Op);
Sanjay Patel957efc232014-10-24 17:02:16 +0000340 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
341 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000342 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
343 bool DemandHighBits = true);
344 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000345 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
346 SDValue InnerPos, SDValue InnerNeg,
347 unsigned PosOpcode, unsigned NegOpcode,
348 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000349 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000350 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000351 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000352 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000353 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000354 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000355
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000356 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000357
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000358 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000359 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000360 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000361 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000362
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000363 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000364 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000365
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000366 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
367 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000368 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000369
Sanjay Patel37c41c12015-01-22 18:21:26 +0000370 /// Holds a pointer to an LSBaseSDNode as well as information on where it
371 /// is located in a sequence of memory operations connected by a chain.
372 struct MemOpLink {
373 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
374 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
375 // Ptr to the mem node.
376 LSBaseSDNode *MemNode;
377 // Offset from the base ptr.
378 int64_t OffsetFromBase;
379 // What is the sequence number of this mem node.
380 // Lowest mem operand in the DAG starts at zero.
381 unsigned SequenceNum;
382 };
383
384 /// This is a helper function for MergeConsecutiveStores. When the source
385 /// elements of the consecutive stores are all constants or all extracted
386 /// vector elements, try to merge them into one larger store.
387 /// \return True if a merged store was created.
388 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
Quentin Colombet308b1712015-01-27 23:58:01 +0000389 EVT MemVT, unsigned NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +0000390 bool IsConstantSrc, bool UseVector);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +0000391
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000392 /// Merge consecutive store operations into a wide store.
393 /// This optimization uses wide integers or vectors when possible.
394 /// \return True if some memory operations were changed.
395 bool MergeConsecutiveStores(StoreSDNode *N);
396
Adam Nemet67483892014-03-04 23:28:31 +0000397 /// \brief Try to transform a truncation where C is a constant:
398 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
399 ///
400 /// \p N needs to be a truncation and its first operand an AND. Other
401 /// requirements are checked by the function (e.g. that trunc is
402 /// single-use) and if missed an empty SDValue is returned.
403 SDValue distributeTruncateThroughAnd(SDNode *N);
404
Chris Lattner4041ab62010-04-15 04:48:01 +0000405 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000406 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000407 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
408 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000409 auto *F = DAG.getMachineFunction().getFunction();
410 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
411 F->hasFnAttribute(Attribute::MinSize);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000412 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000413
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000414 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000415 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000416
Chris Lattner4041ab62010-04-15 04:48:01 +0000417 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000418
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000419 /// Returns a type large enough to hold any valid shift amount - before type
420 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000421 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000422 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
423 if (LHSTy.isVector())
424 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000425 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
426 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000427 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000428
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000429 /// This method returns true if we are running before type legalization or
430 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000431 bool isTypeLegal(const EVT &VT) {
432 if (!LegalTypes) return true;
433 return TLI.isTypeLegal(VT);
434 }
Matt Arsenault758659232013-05-18 00:21:46 +0000435
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000436 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000437 EVT getSetCCResultType(EVT VT) const {
438 return TLI.getSetCCResultType(*DAG.getContext(), VT);
439 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000440 };
441}
442
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000443
444namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000445/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000446/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000447class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000448 DAGCombiner &DC;
449public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000450 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000451 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000452
Craig Topper7b883b32014-03-08 06:31:39 +0000453 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000454 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000455 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000456};
457}
458
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000459//===----------------------------------------------------------------------===//
460// TargetLowering::DAGCombinerInfo implementation
461//===----------------------------------------------------------------------===//
462
463void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000464 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000465}
466
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000467void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000468 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000469}
470
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000471SDValue TargetLowering::DAGCombinerInfo::
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +0000472CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
Evan Chengfd81c732009-03-28 05:57:29 +0000473 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000474}
475
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000476SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000477CombineTo(SDNode *N, SDValue Res, bool AddTo) {
478 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000479}
480
481
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000482SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000483CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
484 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000485}
486
Dan Gohmane58ab792009-01-29 01:59:02 +0000487void TargetLowering::DAGCombinerInfo::
488CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
489 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
490}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000491
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000492//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000493// Helper Functions
494//===----------------------------------------------------------------------===//
495
Chandler Carruth18066972014-08-02 10:02:07 +0000496void DAGCombiner::deleteAndRecombine(SDNode *N) {
497 removeFromWorklist(N);
498
499 // If the operands of this node are only used by the node, they will now be
500 // dead. Make sure to re-visit them and recursively delete dead nodes.
501 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000502 // For an operand generating multiple values, one of the values may
503 // become dead allowing further simplification (e.g. split index
504 // arithmetic from an indexed load).
505 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000506 AddToWorklist(Op.getNode());
507
508 DAG.DeleteNode(N);
509}
510
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000511/// Return 1 if we can compute the negated form of the specified expression for
512/// the same cost as the expression itself, or 2 if we can compute the negated
513/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000514static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000515 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000516 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000517 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000518 // fneg is removable even if it has multiple uses.
519 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000520
Chris Lattnere49c9742007-05-14 22:04:50 +0000521 // Don't allow anything with multiple uses.
522 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000523
Chris Lattner46980832007-05-25 02:19:06 +0000524 // Don't recurse exponentially.
525 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000526
Chris Lattnere49c9742007-05-14 22:04:50 +0000527 switch (Op.getOpcode()) {
528 default: return false;
529 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000530 // Don't invert constant FP values after legalize. The negated constant
531 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000532 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000533 case ISD::FADD:
534 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000535 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000536
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000537 // After operation legalization, it might not be legal to create new FSUBs.
538 if (LegalOperations &&
539 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
540 return 0;
541
Craig Topper03f39772012-09-09 22:58:45 +0000542 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000543 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
544 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000545 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000546 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000547 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000548 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000549 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000550 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000551 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000552
Bill Wendling6fbf5492009-01-30 23:10:18 +0000553 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000554 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000555
Chris Lattnere49c9742007-05-14 22:04:50 +0000556 case ISD::FMUL:
557 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000558 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000559
Bill Wendling6fbf5492009-01-30 23:10:18 +0000560 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000561 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
562 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000563 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000564
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000565 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000566 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000567
Chris Lattnere49c9742007-05-14 22:04:50 +0000568 case ISD::FP_EXTEND:
569 case ISD::FP_ROUND:
570 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000571 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000572 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000573 }
574}
575
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000576/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000577static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000578 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000579 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000580 // fneg is removable even if it has multiple uses.
581 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000582
Chris Lattnere49c9742007-05-14 22:04:50 +0000583 // Don't allow anything with multiple uses.
584 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000585
Chris Lattner46980832007-05-25 02:19:06 +0000586 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000587 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000588 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000589 case ISD::ConstantFP: {
590 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
591 V.changeSign();
592 return DAG.getConstantFP(V, Op.getValueType());
593 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000594 case ISD::FADD:
595 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000596 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000597
Bill Wendling6fbf5492009-01-30 23:10:18 +0000598 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000599 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000600 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000601 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000602 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000603 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000604 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000605 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000606 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000607 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000608 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000609 Op.getOperand(0));
610 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000611 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000612 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000613
Bill Wendling6fbf5492009-01-30 23:10:18 +0000614 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000615 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000616 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000617 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000618
Bill Wendling6fbf5492009-01-30 23:10:18 +0000619 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000620 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000621 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000622
Chris Lattnere49c9742007-05-14 22:04:50 +0000623 case ISD::FMUL:
624 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000625 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000626
Bill Wendling6fbf5492009-01-30 23:10:18 +0000627 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000628 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000629 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000630 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000631 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000632 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000633 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000634
Bill Wendling6fbf5492009-01-30 23:10:18 +0000635 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000636 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000637 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000638 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000639 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000640
Chris Lattnere49c9742007-05-14 22:04:50 +0000641 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000642 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000643 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000644 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000645 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000646 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000647 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000648 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000649 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000650 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000651 }
652}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000653
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000654// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000655// that selects between the target values used for true and false, making it
656// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
657// the appropriate nodes based on the type of node we are checking. This
658// simplifies life a bit for the callers.
659bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
660 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000661 if (N.getOpcode() == ISD::SETCC) {
662 LHS = N.getOperand(0);
663 RHS = N.getOperand(1);
664 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000665 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000666 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000667
668 if (N.getOpcode() != ISD::SELECT_CC ||
669 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
670 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
671 return false;
672
Oliver Stannardd29db9b2014-11-17 10:49:31 +0000673 if (TLI.getBooleanContents(N.getValueType()) ==
674 TargetLowering::UndefinedBooleanContent)
675 return false;
676
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000677 LHS = N.getOperand(0);
678 RHS = N.getOperand(1);
679 CC = N.getOperand(4);
680 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000681}
682
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000683/// Return true if this is a SetCC-equivalent operation with only one use.
684/// If this is true, it allows the users to invert the operation for free when
685/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000686bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000687 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000688 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000689 return true;
690 return false;
691}
692
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000693/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000694/// elements are all the same constant or undefined.
695static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
696 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
697 if (!C)
698 return false;
699
700 APInt SplatUndef;
701 unsigned SplatBitSize;
702 bool HasAnyUndefs;
703 EVT EltVT = N->getValueType(0).getVectorElementType();
704 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
705 HasAnyUndefs) &&
706 EltVT.getSizeInBits() >= SplatBitSize);
707}
708
709// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000710static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
711 if (isa<ConstantSDNode>(N))
712 return N.getNode();
713 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000714 if (BV && BV->isConstant())
Juergen Ributzka68402822014-01-13 21:49:25 +0000715 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000716 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000717}
718
Matt Arsenault985b9de2014-03-17 18:58:01 +0000719// \brief Returns the SDNode if it is a constant splat BuildVector or constant
720// int.
721static ConstantSDNode *isConstOrConstSplat(SDValue N) {
722 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
723 return CN;
724
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000725 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000726 BitVector UndefElements;
727 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000728
729 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000730 // FIXME: We blindly ignore splats which include undef which is overly
731 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000732 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000733 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000734 return CN;
735 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000736
737 return nullptr;
738}
739
Matt Arsenault6cc00422014-08-16 10:14:19 +0000740// \brief Returns the SDNode if it is a constant splat BuildVector or constant
741// float.
742static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
743 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
744 return CN;
745
746 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
747 BitVector UndefElements;
748 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
749
Matt Arsenault965de302014-09-02 18:33:51 +0000750 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000751 return CN;
752 }
753
754 return nullptr;
755}
756
Andrew Trickef9de2a2013-05-25 02:42:55 +0000757SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000758 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000759 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000760 if (N0.getOpcode() == Opc) {
761 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
762 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
763 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000764 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
765 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
766 return SDValue();
Juergen Ributzka73844052014-01-13 20:51:35 +0000767 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000768 if (N0.hasOneUse()) {
769 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
770 // use
771 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
772 if (!OpNode.getNode())
773 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000774 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000775 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000776 }
777 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000778 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000779
Juergen Ributzka68402822014-01-13 21:49:25 +0000780 if (N1.getOpcode() == Opc) {
781 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
782 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
783 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000784 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
785 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
786 return SDValue();
Juergen Ributzka68402822014-01-13 21:49:25 +0000787 }
788 if (N1.hasOneUse()) {
789 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
790 // use
791 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
792 if (!OpNode.getNode())
793 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000794 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000795 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
796 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000797 }
798 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000799
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000800 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000801}
802
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000803SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
804 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000805 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
806 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000807 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000808 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000809 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000810 To[0].getNode()->dump(&DAG);
Mehdi Aminid3892082014-12-23 18:59:02 +0000811 dbgs() << " and " << NumTo-1 << " other values\n");
812 for (unsigned i = 0, e = NumTo; i != e; ++i)
813 assert((!To[i].getNode() ||
814 N->getValueType(i) == To[i].getValueType()) &&
815 "Cannot combine value to value of different type!");
816
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000817 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000818 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000819 if (AddTo) {
820 // Push the new nodes and any users onto the worklist
821 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000822 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000823 AddToWorklist(To[i].getNode());
824 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000825 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000826 }
827 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000828
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000829 // Finally, if the node is now dead, remove it from the graph. The node
830 // may not be dead if the replacement process recursively simplified to
831 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000832 if (N->use_empty())
833 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000834 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000835}
836
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000837void DAGCombiner::
838CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000839 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000840 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000841 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000842 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000843
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000844 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000845 AddToWorklist(TLO.New.getNode());
846 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000847
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000848 // Finally, if the node is now dead, remove it from the graph. The node
849 // may not be dead if the replacement process recursively simplified to
850 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000851 if (TLO.Old.getNode()->use_empty())
852 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000853}
854
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000855/// Check the specified integer node value to see if it can be simplified or if
856/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000857bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000858 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000859 APInt KnownZero, KnownOne;
860 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
861 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000862
Dan Gohmane58ab792009-01-29 01:59:02 +0000863 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000864 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000865
Dan Gohmane58ab792009-01-29 01:59:02 +0000866 // Replace the old value with the new one.
867 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000868 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000869 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000870 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000871 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000872 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000873
Dan Gohmane58ab792009-01-29 01:59:02 +0000874 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000875 return true;
876}
877
Evan Cheng0abb54d2010-04-24 04:43:44 +0000878void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000879 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000880 EVT VT = Load->getValueType(0);
881 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000882
Evan Cheng0abb54d2010-04-24 04:43:44 +0000883 DEBUG(dbgs() << "\nReplacing.9 ";
884 Load->dump(&DAG);
885 dbgs() << "\nWith: ";
886 Trunc.getNode()->dump(&DAG);
887 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000888 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000889 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
890 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000891 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000892 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000893}
894
895SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
896 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000897 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000898 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000899 EVT MemVT = LD->getMemoryVT();
900 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000901 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
902 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000903 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000904 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000905 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000906 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000907 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000908 }
909
Evan Chenge19aa5c2010-04-19 19:29:22 +0000910 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000911 switch (Opc) {
912 default: break;
913 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000914 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000915 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000916 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000917 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000918 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000919 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000920 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000921 case ISD::Constant: {
922 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000923 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000924 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000925 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000926 }
927
928 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000929 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000930 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000931}
932
Evan Cheng0abb54d2010-04-24 04:43:44 +0000933SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000934 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
935 return SDValue();
936 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000937 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000938 bool Replace = false;
939 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000940 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000941 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000942 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000943
944 if (Replace)
945 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
946 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000947 DAG.getValueType(OldVT));
948}
949
Evan Cheng0abb54d2010-04-24 04:43:44 +0000950SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000951 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000952 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000953 bool Replace = false;
954 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000955 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000956 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000957 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000958
959 if (Replace)
960 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000962}
963
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000964/// Promote the specified integer binary operation if the target indicates it is
965/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
966/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000967SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
968 if (!LegalOperations)
969 return SDValue();
970
971 EVT VT = Op.getValueType();
972 if (VT.isVector() || !VT.isInteger())
973 return SDValue();
974
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000975 // If operation type is 'undesirable', e.g. i16 on x86, consider
976 // promoting it.
977 unsigned Opc = Op.getOpcode();
978 if (TLI.isTypeDesirableForOp(Opc, VT))
979 return SDValue();
980
Evan Chengaf56fac2010-04-16 06:14:10 +0000981 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000982 // Consult target whether it is a good idea to promote this operation and
983 // what's the right type to promote it to.
984 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000985 assert(PVT != VT && "Don't know what type to promote to!");
986
Evan Cheng0abb54d2010-04-24 04:43:44 +0000987 bool Replace0 = false;
988 SDValue N0 = Op.getOperand(0);
989 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000990 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000991 return SDValue();
992
Evan Cheng0abb54d2010-04-24 04:43:44 +0000993 bool Replace1 = false;
994 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000995 SDValue NN1;
996 if (N0 == N1)
997 NN1 = NN0;
998 else {
999 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +00001000 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +00001001 return SDValue();
1002 }
Evan Chengf1223bd2010-04-22 20:19:46 +00001003
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001004 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +00001005 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001006 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001007
1008 if (Replace0)
1009 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1010 if (Replace1)
1011 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +00001012
Evan Chenge8136902010-04-27 19:48:13 +00001013 DEBUG(dbgs() << "\nPromoting ";
1014 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001015 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +00001016 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +00001017 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +00001018 }
1019 return SDValue();
1020}
1021
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001022/// Promote the specified integer shift operation if the target indicates it is
1023/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1024/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +00001025SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1026 if (!LegalOperations)
1027 return SDValue();
1028
1029 EVT VT = Op.getValueType();
1030 if (VT.isVector() || !VT.isInteger())
1031 return SDValue();
1032
1033 // If operation type is 'undesirable', e.g. i16 on x86, consider
1034 // promoting it.
1035 unsigned Opc = Op.getOpcode();
1036 if (TLI.isTypeDesirableForOp(Opc, VT))
1037 return SDValue();
1038
1039 EVT PVT = VT;
1040 // Consult target whether it is a good idea to promote this operation and
1041 // what's the right type to promote it to.
1042 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1043 assert(PVT != VT && "Don't know what type to promote to!");
1044
Evan Cheng0abb54d2010-04-24 04:43:44 +00001045 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001046 SDValue N0 = Op.getOperand(0);
1047 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001048 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001049 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001050 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001051 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001052 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001053 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001054 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001055
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001056 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001057 if (Replace)
1058 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001059
Evan Chenge8136902010-04-27 19:48:13 +00001060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001062 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001063 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001064 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001065 }
1066 return SDValue();
1067}
1068
Evan Chenge19aa5c2010-04-19 19:29:22 +00001069SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1070 if (!LegalOperations)
1071 return SDValue();
1072
1073 EVT VT = Op.getValueType();
1074 if (VT.isVector() || !VT.isInteger())
1075 return SDValue();
1076
1077 // If operation type is 'undesirable', e.g. i16 on x86, consider
1078 // promoting it.
1079 unsigned Opc = Op.getOpcode();
1080 if (TLI.isTypeDesirableForOp(Opc, VT))
1081 return SDValue();
1082
1083 EVT PVT = VT;
1084 // Consult target whether it is a good idea to promote this operation and
1085 // what's the right type to promote it to.
1086 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1087 assert(PVT != VT && "Don't know what type to promote to!");
1088 // fold (aext (aext x)) -> (aext x)
1089 // fold (aext (zext x)) -> (zext x)
1090 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001091 DEBUG(dbgs() << "\nPromoting ";
1092 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001093 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001094 }
1095 return SDValue();
1096}
1097
1098bool DAGCombiner::PromoteLoad(SDValue Op) {
1099 if (!LegalOperations)
1100 return false;
1101
1102 EVT VT = Op.getValueType();
1103 if (VT.isVector() || !VT.isInteger())
1104 return false;
1105
1106 // If operation type is 'undesirable', e.g. i16 on x86, consider
1107 // promoting it.
1108 unsigned Opc = Op.getOpcode();
1109 if (TLI.isTypeDesirableForOp(Opc, VT))
1110 return false;
1111
1112 EVT PVT = VT;
1113 // Consult target whether it is a good idea to promote this operation and
1114 // what's the right type to promote it to.
1115 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1116 assert(PVT != VT && "Don't know what type to promote to!");
1117
Andrew Trickef9de2a2013-05-25 02:42:55 +00001118 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001119 SDNode *N = Op.getNode();
1120 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001121 EVT MemVT = LD->getMemoryVT();
1122 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00001123 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1124 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001125 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001126 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001127 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001128 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001129 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1130
Evan Cheng0abb54d2010-04-24 04:43:44 +00001131 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001132 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001133 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001134 Result.getNode()->dump(&DAG);
1135 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001136 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001137 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1138 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001139 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001140 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001141 return true;
1142 }
1143 return false;
1144}
1145
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001146/// \brief Recursively delete a node which has no uses and any operands for
1147/// which it is the only use.
1148///
1149/// Note that this both deletes the nodes and removes them from the worklist.
1150/// It also adds any nodes who have had a user deleted to the worklist as they
1151/// may now have only one use and subject to other combines.
1152bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1153 if (!N->use_empty())
1154 return false;
1155
1156 SmallSetVector<SDNode *, 16> Nodes;
1157 Nodes.insert(N);
1158 do {
1159 N = Nodes.pop_back_val();
1160 if (!N)
1161 continue;
1162
1163 if (N->use_empty()) {
1164 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1165 Nodes.insert(N->getOperand(i).getNode());
1166
1167 removeFromWorklist(N);
1168 DAG.DeleteNode(N);
1169 } else {
1170 AddToWorklist(N);
1171 }
1172 } while (!Nodes.empty());
1173 return true;
1174}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001175
Chris Lattnere49c9742007-05-14 22:04:50 +00001176//===----------------------------------------------------------------------===//
1177// Main DAG Combiner implementation
1178//===----------------------------------------------------------------------===//
1179
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001180void DAGCombiner::Run(CombineLevel AtLevel) {
1181 // set the instance variables, so that the various visit routines may use it.
1182 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001183 LegalOperations = Level >= AfterLegalizeVectorOps;
1184 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001185
Paul Robinsonad06e432014-11-03 18:19:26 +00001186 // Early exit if this basic block is in an optnone function.
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +00001187 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
1188 Attribute::OptimizeNone))
Paul Robinsonad06e432014-11-03 18:19:26 +00001189 return;
1190
Evan Cheng5e7658c2008-08-29 22:21:44 +00001191 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001192 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1193 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001194 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001195
Evan Cheng5e7658c2008-08-29 22:21:44 +00001196 // Create a dummy node (which is not added to allnodes), that adds a reference
1197 // to the root node, preventing it from being deleted, and tracking any
1198 // changes of the root.
1199 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001200
James Molloy67b6b112012-02-16 09:17:04 +00001201 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001202 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001203 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001204 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001205 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001206 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001207 N = Worklist.pop_back_val();
1208 } while (!N);
1209
1210 bool GoodWorklistEntry = WorklistMap.erase(N);
1211 (void)GoodWorklistEntry;
1212 assert(GoodWorklistEntry &&
1213 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001214
Evan Cheng5e7658c2008-08-29 22:21:44 +00001215 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1216 // N is deleted from the DAG, since they too may now be dead or may have a
1217 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001218 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001219 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001220
1221 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001222
Chandler Carruth411fb402014-07-26 05:49:40 +00001223 // If this combine is running after legalizing the DAG, re-legalize any
1224 // nodes pulled off the worklist.
1225 if (Level == AfterLegalizeDAG) {
1226 SmallSetVector<SDNode *, 16> UpdatedNodes;
1227 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1228
1229 for (SDNode *LN : UpdatedNodes) {
1230 AddToWorklist(LN);
1231 AddUsersToWorklist(LN);
1232 }
1233 if (!NIsValid)
1234 continue;
1235 }
1236
Chandler Carruthb1432742014-07-28 17:55:07 +00001237 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1238
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001239 // Add any operands of the new node which have not yet been combined to the
1240 // worklist as well. Because the worklist uniques things already, this
1241 // won't repeatedly process the same operand.
1242 CombinedNodes.insert(N);
1243 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1244 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1245 AddToWorklist(N->getOperand(i).getNode());
1246
Evan Cheng5e7658c2008-08-29 22:21:44 +00001247 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001248
Craig Topperc0196b12014-04-14 00:51:57 +00001249 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001250 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001251
Evan Cheng5e7658c2008-08-29 22:21:44 +00001252 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001253
Evan Cheng5e7658c2008-08-29 22:21:44 +00001254 // If we get back the same node we passed in, rather than a new node or
1255 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001256 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001257 // mechanics for us, we have no work to do in this case.
1258 if (RV.getNode() == N)
1259 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001260
Evan Cheng5e7658c2008-08-29 22:21:44 +00001261 assert(N->getOpcode() != ISD::DELETED_NODE &&
1262 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1263 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001264
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001265 DEBUG(dbgs() << " ... into: ";
1266 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001267
Devang Patelefec7712011-05-23 22:04:42 +00001268 // Transfer debug value.
1269 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001270 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001271 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001272 else {
1273 assert(N->getValueType(0) == RV.getValueType() &&
1274 N->getNumValues() == 1 && "Type mismatch");
1275 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001276 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001277 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001278
Evan Cheng5e7658c2008-08-29 22:21:44 +00001279 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001280 AddToWorklist(RV.getNode());
1281 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001282
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001283 // Finally, if the node is now dead, remove it from the graph. The node
1284 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001285 // something else needing this node. This will also take care of adding any
1286 // operands which have lost a user to the worklist.
1287 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001288 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001289
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001290 // If the root changed (e.g. it was a dead load, update the root).
1291 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001292 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001293}
1294
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001295SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001296 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001297 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001298 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001299 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001300 case ISD::ADD: return visitADD(N);
1301 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001302 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001303 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001304 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001305 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001306 case ISD::MUL: return visitMUL(N);
1307 case ISD::SDIV: return visitSDIV(N);
1308 case ISD::UDIV: return visitUDIV(N);
1309 case ISD::SREM: return visitSREM(N);
1310 case ISD::UREM: return visitUREM(N);
1311 case ISD::MULHU: return visitMULHU(N);
1312 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001313 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1314 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001315 case ISD::SMULO: return visitSMULO(N);
1316 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001317 case ISD::SDIVREM: return visitSDIVREM(N);
1318 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001319 case ISD::AND: return visitAND(N);
1320 case ISD::OR: return visitOR(N);
1321 case ISD::XOR: return visitXOR(N);
1322 case ISD::SHL: return visitSHL(N);
1323 case ISD::SRA: return visitSRA(N);
1324 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001325 case ISD::ROTR:
1326 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001327 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001328 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001329 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001330 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001331 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001332 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001333 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001334 case ISD::SELECT_CC: return visitSELECT_CC(N);
1335 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001336 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1337 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001338 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001339 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1340 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001341 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001342 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001343 case ISD::FADD: return visitFADD(N);
1344 case ISD::FSUB: return visitFSUB(N);
1345 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001346 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001347 case ISD::FDIV: return visitFDIV(N);
1348 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001349 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001350 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001351 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1352 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1353 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1354 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1355 case ISD::FP_ROUND: return visitFP_ROUND(N);
1356 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1357 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1358 case ISD::FNEG: return visitFNEG(N);
1359 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001360 case ISD::FFLOOR: return visitFFLOOR(N);
Matt Arsenault7c936902014-10-21 23:01:01 +00001361 case ISD::FMINNUM: return visitFMINNUM(N);
1362 case ISD::FMAXNUM: return visitFMAXNUM(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001363 case ISD::FCEIL: return visitFCEIL(N);
1364 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001365 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001366 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001367 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001368 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001369 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001370 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001371 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1372 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001373 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001374 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +00001375 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001376 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001377 case ISD::MLOAD: return visitMLOAD(N);
1378 case ISD::MSTORE: return visitMSTORE(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001379 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001380 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001381}
1382
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001383SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001384 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001385
1386 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001387 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001388 assert(N->getOpcode() != ISD::DELETED_NODE &&
1389 "Node was deleted but visit returned NULL!");
1390
1391 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1392 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1393
1394 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001395 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001396 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001397
1398 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1399 }
1400 }
1401
Evan Chengf1005572010-04-28 07:10:39 +00001402 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001403 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001404 switch (N->getOpcode()) {
1405 default: break;
1406 case ISD::ADD:
1407 case ISD::SUB:
1408 case ISD::MUL:
1409 case ISD::AND:
1410 case ISD::OR:
1411 case ISD::XOR:
1412 RV = PromoteIntBinOp(SDValue(N, 0));
1413 break;
1414 case ISD::SHL:
1415 case ISD::SRA:
1416 case ISD::SRL:
1417 RV = PromoteIntShiftOp(SDValue(N, 0));
1418 break;
1419 case ISD::SIGN_EXTEND:
1420 case ISD::ZERO_EXTEND:
1421 case ISD::ANY_EXTEND:
1422 RV = PromoteExtend(SDValue(N, 0));
1423 break;
1424 case ISD::LOAD:
1425 if (PromoteLoad(SDValue(N, 0)))
1426 RV = SDValue(N, 0);
1427 break;
1428 }
1429 }
1430
Scott Michelcf0da6c2009-02-17 22:15:04 +00001431 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001432 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001433 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001434 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001435 SDValue N0 = N->getOperand(0);
1436 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001437
Evan Cheng31604a62008-03-22 01:55:50 +00001438 // Constant operands are canonicalized to RHS.
1439 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001440 SDValue Ops[] = {N1, N0};
1441 SDNode *CSENode;
1442 if (const BinaryWithFlagsSDNode *BinNode =
1443 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1444 CSENode = DAG.getNodeIfExists(
1445 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1446 BinNode->hasNoSignedWrap(), BinNode->isExact());
1447 } else {
1448 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1449 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001450 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001451 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001452 }
1453 }
1454
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001455 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001456}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001457
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001458/// Given a node, return its input chain if it has one, otherwise return a null
1459/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001460static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001461 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001462 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001463 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001464 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001465 return N->getOperand(NumOps-1);
1466 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001467 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001468 return N->getOperand(i);
1469 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001470 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001471}
1472
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001473SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001474 // If N has two operands, where one has an input chain equal to the other,
1475 // the 'other' chain is redundant.
1476 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001477 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001478 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001479 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001480 return N->getOperand(1);
1481 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001482
Chris Lattner48fb92f2007-05-16 06:37:59 +00001483 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001484 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001485 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001486 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001487
Jim Laskey708d0db2006-10-04 16:53:27 +00001488 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001489 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001490
Jim Laskey0463e082006-10-07 23:37:56 +00001491 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001492 // encountered.
1493 for (unsigned i = 0; i < TFs.size(); ++i) {
1494 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001495
Jim Laskey708d0db2006-10-04 16:53:27 +00001496 // Check each of the operands.
1497 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001498 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001499
Jim Laskey708d0db2006-10-04 16:53:27 +00001500 switch (Op.getOpcode()) {
1501 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001502 // Entry tokens don't need to be added to the list. They are
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001503 // redundant.
Jim Laskey6549d222006-10-05 15:07:25 +00001504 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001505 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001506
Jim Laskey708d0db2006-10-04 16:53:27 +00001507 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001508 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001509 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001510 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001511 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001512 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001513 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001514 Changed = true;
1515 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001516 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001517 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001518
Jim Laskey708d0db2006-10-04 16:53:27 +00001519 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001520 // Only add if it isn't already in the list.
David Blaikie70573dc2014-11-19 07:49:26 +00001521 if (SeenOps.insert(Op.getNode()).second)
Jim Laskey6549d222006-10-05 15:07:25 +00001522 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001523 else
1524 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001525 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001526 }
1527 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001528 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001529
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001530 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001531
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001532 // If we've changed things around then replace token factor.
Jim Laskey708d0db2006-10-04 16:53:27 +00001533 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001534 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001535 // The entry token is the only possible outcome.
1536 Result = DAG.getEntryNode();
1537 } else {
1538 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001539 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001540 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001541
Jonas Paulssonbf8d0cc2015-02-11 16:10:31 +00001542 // Add users to worklist if AA is enabled, since it may introduce
1543 // a lot of new chained token factors while removing memory deps.
1544 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1545 : DAG.getSubtarget().useAA();
1546 return CombineTo(N, Result, UseAA /*add to worklist*/);
Nate Begeman02b23c62005-10-13 03:11:28 +00001547 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001548
Jim Laskey708d0db2006-10-04 16:53:27 +00001549 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001550}
1551
Chris Lattneree322b42008-02-13 07:25:05 +00001552/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001553SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001554 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001555 // Replacing results may cause a different MERGE_VALUES to suddenly
1556 // be CSE'd with N, and carry its uses with it. Iterate until no
1557 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001558 // First add the users of this node to the work list so that they
1559 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001560 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001561 do {
1562 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001563 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001564 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001565 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001566 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001567}
1568
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001569SDValue DAGCombiner::visitADD(SDNode *N) {
1570 SDValue N0 = N->getOperand(0);
1571 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001572 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001573
1574 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001575 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001576 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001577 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001578
1579 // fold (add x, 0) -> x, vector edition
1580 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1581 return N0;
1582 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1583 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001584 }
Bill Wendling0864a752008-12-10 22:36:00 +00001585
Dan Gohman06563a82007-07-03 14:03:57 +00001586 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001587 if (N0.getOpcode() == ISD::UNDEF)
1588 return N0;
1589 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001590 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001591 // fold (add c1, c2) -> c1+c2
Matthias Braun00a40762015-02-24 18:52:01 +00001592 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1593 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001594 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001595 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001596 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001597 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001598 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001599 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001600 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001601 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001602 // fold (add Sym, c) -> Sym+c
1603 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001604 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001605 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001606 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001607 GA->getOffset() +
1608 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001609 // fold ((c1-A)+c2) -> (c1+c2)-A
1610 if (N1C && N0.getOpcode() == ISD::SUB)
1611 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001612 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001613 DAG.getConstant(N1C->getAPIntValue()+
1614 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001615 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001616 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001617 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001618 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001619 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001620 // fold ((0-A) + B) -> B-A
1621 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1622 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001623 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001624 // fold (A + (0-B)) -> A-B
1625 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1626 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001627 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001628 // fold (A+(B-A)) -> B
1629 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001630 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001631 // fold ((B-A)+A) -> B
1632 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1633 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001634 // fold (A+(B-(A+C))) to (B-C)
1635 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001636 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001637 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001638 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001639 // fold (A+(B-(C+A))) to (B-C)
1640 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001641 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001642 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001643 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001644 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001645 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1646 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001647 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001648 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001649 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001650
Dale Johannesen8c766702008-12-02 01:30:54 +00001651 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1652 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1653 SDValue N00 = N0.getOperand(0);
1654 SDValue N01 = N0.getOperand(1);
1655 SDValue N10 = N1.getOperand(0);
1656 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001657
1658 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001659 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1660 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1661 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001662 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001664 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1665 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001666
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001667 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001668 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001669 APInt LHSZero, LHSOne;
1670 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001671 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001672
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001673 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001674 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001675
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001676 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1677 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001678 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1679 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1680 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1681 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001682 }
1683 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001684
Dan Gohman954f4902010-01-19 23:30:49 +00001685 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1686 if (N1.getOpcode() == ISD::SHL &&
1687 N1.getOperand(0).getOpcode() == ISD::SUB)
1688 if (ConstantSDNode *C =
1689 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1690 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001691 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1692 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001693 N1.getOperand(0).getOperand(1),
1694 N1.getOperand(1)));
1695 if (N0.getOpcode() == ISD::SHL &&
1696 N0.getOperand(0).getOpcode() == ISD::SUB)
1697 if (ConstantSDNode *C =
1698 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1699 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001700 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1701 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001702 N0.getOperand(0).getOperand(1),
1703 N0.getOperand(1)));
1704
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001705 if (N1.getOpcode() == ISD::AND) {
1706 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001707 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001708 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1709 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001710
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001711 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1712 // and similar xforms where the inner op is either ~0 or 0.
1713 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001714 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001715 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1716 }
1717 }
1718
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001719 // add (sext i1), X -> sub X, (zext i1)
1720 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1721 N0.getOperand(0).getValueType() == MVT::i1 &&
1722 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001723 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001724 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1725 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1726 }
1727
Jan Veselyaf62cf42014-10-17 14:45:25 +00001728 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1729 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1730 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1731 if (TN->getVT() == MVT::i1) {
1732 SDLoc DL(N);
1733 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1734 DAG.getConstant(1, VT));
1735 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1736 }
1737 }
1738
Evan Chengf1005572010-04-28 07:10:39 +00001739 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001740}
1741
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001742SDValue DAGCombiner::visitADDC(SDNode *N) {
1743 SDValue N0 = N->getOperand(0);
1744 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001745 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001746
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001747 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001748 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001749 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001750 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001751 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001752
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001753 // canonicalize constant to RHS.
Matthias Braun00a40762015-02-24 18:52:01 +00001754 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1755 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001756 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001757 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001758
Chris Lattner47206662007-03-04 20:40:38 +00001759 // fold (addc x, 0) -> x + no carry out
1760 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001761 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001762 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001763
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001764 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001765 APInt LHSZero, LHSOne;
1766 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001767 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001768
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001769 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001770 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001771
Chris Lattner47206662007-03-04 20:40:38 +00001772 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1773 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001774 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001775 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001776 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001777 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001778 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001779
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001780 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001781}
1782
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001783SDValue DAGCombiner::visitADDE(SDNode *N) {
1784 SDValue N0 = N->getOperand(0);
1785 SDValue N1 = N->getOperand(1);
1786 SDValue CarryIn = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001787
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001788 // canonicalize constant to RHS
Matthias Braun00a40762015-02-24 18:52:01 +00001789 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1790 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001791 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001792 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001793 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001794
Chris Lattner47206662007-03-04 20:40:38 +00001795 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001796 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001797 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001798
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001799 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001800}
1801
Eric Christophere5ca1e02011-02-16 04:50:12 +00001802// Since it may not be valid to emit a fold to zero for vector initializers
1803// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001804static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001805 SelectionDAG &DAG,
1806 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001807 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001808 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001809 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1810 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001811 return SDValue();
1812}
1813
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001814SDValue DAGCombiner::visitSUB(SDNode *N) {
1815 SDValue N0 = N->getOperand(0);
1816 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001817 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001818
Dan Gohmana8665142007-06-25 16:23:39 +00001819 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001820 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001821 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001822 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001823
1824 // fold (sub x, 0) -> x, vector edition
1825 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1826 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001827 }
Bill Wendling0864a752008-12-10 22:36:00 +00001828
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001829 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001830 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001831 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001832 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001833 // fold (sub c1, c2) -> c1-c2
Matthias Braun00a40762015-02-24 18:52:01 +00001834 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001836 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001837 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001838 // fold (sub x, c) -> (add x, -c)
1839 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001840 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001841 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001842 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1843 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001844 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001845 // fold A-(A-B) -> B
1846 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1847 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001848 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001849 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001850 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001851 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001852 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001853 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001854 // fold C2-(A+C1) -> (C2-C1)-A
Matthias Braun00a40762015-02-24 18:52:01 +00001855 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1856 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001857 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001858 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1859 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001860 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001861 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001862 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001863 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001864 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001865 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1866 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001867 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001868 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001869 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001870 // fold ((A+(C+B))-B) -> A+C
1871 if (N0.getOpcode() == ISD::ADD &&
1872 N0.getOperand(1).getOpcode() == ISD::ADD &&
1873 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001874 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001875 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001876 // fold ((A-(B-C))-C) -> A-B
1877 if (N0.getOpcode() == ISD::SUB &&
1878 N0.getOperand(1).getOpcode() == ISD::SUB &&
1879 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001880 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001881 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001882
Dan Gohman06563a82007-07-03 14:03:57 +00001883 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001884 if (N0.getOpcode() == ISD::UNDEF)
1885 return N0;
1886 if (N1.getOpcode() == ISD::UNDEF)
1887 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001888
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001889 // If the relocation model supports it, consider symbol offsets.
1890 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001891 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001892 // fold (sub Sym, c) -> Sym-c
1893 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001894 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001895 GA->getOffset() -
1896 (uint64_t)N1C->getSExtValue());
1897 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1898 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1899 if (GA->getGlobal() == GB->getGlobal())
1900 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1901 VT);
1902 }
1903
Jan Veselyaf62cf42014-10-17 14:45:25 +00001904 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1905 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1906 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1907 if (TN->getVT() == MVT::i1) {
1908 SDLoc DL(N);
1909 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1910 DAG.getConstant(1, VT));
1911 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1912 }
1913 }
1914
Evan Chengf1005572010-04-28 07:10:39 +00001915 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001916}
1917
Craig Topper43a1bd62012-01-07 09:06:39 +00001918SDValue DAGCombiner::visitSUBC(SDNode *N) {
1919 SDValue N0 = N->getOperand(0);
1920 SDValue N1 = N->getOperand(1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001921 EVT VT = N0.getValueType();
1922
1923 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001924 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001925 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1926 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001927 MVT::Glue));
1928
1929 // fold (subc x, x) -> 0 + no borrow
1930 if (N0 == N1)
1931 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001932 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001933 MVT::Glue));
1934
1935 // fold (subc x, 0) -> x + no borrow
Matthias Braun00a40762015-02-24 18:52:01 +00001936 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1937 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001938 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001939 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001940 MVT::Glue));
1941
1942 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1943 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001944 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1945 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001946 MVT::Glue));
1947
1948 return SDValue();
1949}
1950
1951SDValue DAGCombiner::visitSUBE(SDNode *N) {
1952 SDValue N0 = N->getOperand(0);
1953 SDValue N1 = N->getOperand(1);
1954 SDValue CarryIn = N->getOperand(2);
1955
1956 // fold (sube x, y, false) -> (subc x, y)
1957 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001958 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001959
1960 return SDValue();
1961}
1962
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001963SDValue DAGCombiner::visitMUL(SDNode *N) {
1964 SDValue N0 = N->getOperand(0);
1965 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001966 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001967
Dan Gohman06563a82007-07-03 14:03:57 +00001968 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001969 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001970 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001971
1972 bool N0IsConst = false;
1973 bool N1IsConst = false;
1974 APInt ConstValue0, ConstValue1;
1975 // fold vector ops
1976 if (VT.isVector()) {
1977 SDValue FoldedVOp = SimplifyVBinOp(N);
1978 if (FoldedVOp.getNode()) return FoldedVOp;
1979
1980 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1981 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1982 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001983 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001984 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1985 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001986 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001987 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1988 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001989 }
1990
Nate Begeman21158fc2005-09-01 00:19:25 +00001991 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001992 if (N0IsConst && N1IsConst)
1993 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1994
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001995 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001996 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001997 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001998 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001999 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00002000 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002001 // We require a splat of the entire scalar bit width for non-contiguous
2002 // bit patterns.
2003 bool IsFullSplat =
2004 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002005 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002006 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002007 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00002008 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002009 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002010 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002011 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002012 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002013 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002014 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002015 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002016 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00002017 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002018 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002019 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002020 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00002021 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002022 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002023 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002024 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002025 DAG.getConstant(Log2Val,
2026 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00002027 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002028
2029 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00002030 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00002031 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002032 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2033 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002034 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002035 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002036 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002037 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002038 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002039 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002040
Chris Lattner324871e2006-03-01 03:44:24 +00002041 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2042 // use.
2043 {
Craig Topperc0196b12014-04-14 00:51:57 +00002044 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002045 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002046 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002047 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2048 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002049 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002050 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002051 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002052 isa<ConstantSDNode>(N1.getOperand(1)) &&
2053 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002054 Sh = N1; Y = N0;
2055 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002056
Gabor Greiff304a7a2008-08-28 21:40:38 +00002057 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002058 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002059 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002060 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002061 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002062 }
2063 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002064
Chris Lattnerf29f5202006-03-04 23:33:26 +00002065 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002066 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2067 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2068 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002069 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2070 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002071 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002072 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002073 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002074
Nate Begeman22e251a2006-02-03 06:46:56 +00002075 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002076 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002077 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002078 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002079
Evan Chengf1005572010-04-28 07:10:39 +00002080 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002081}
2082
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002083SDValue DAGCombiner::visitSDIV(SDNode *N) {
2084 SDValue N0 = N->getOperand(0);
2085 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002086 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002087
Dan Gohmana8665142007-06-25 16:23:39 +00002088 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002089 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002090 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002091 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002092 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002093
Nate Begeman21158fc2005-09-01 00:19:25 +00002094 // fold (sdiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002095 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2096 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002097 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002098 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002099 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002100 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002101 return N0;
2102 // fold (sdiv X, -1) -> 0-X
2103 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002104 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002105 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002106 // If we know the sign bits of both operands are zero, strength reduce to a
2107 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002108 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002109 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002110 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002111 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002112 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002113
Nate Begeman57b35672006-02-17 07:26:20 +00002114 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002115 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2116 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002117 // If dividing by powers of two is cheap, then don't perform the following
2118 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002119 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002120 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002121
Chad Rosier17020f92014-07-23 14:57:52 +00002122 // Target-specific implementation of sdiv x, pow2.
2123 SDValue Res = BuildSDIVPow2(N);
2124 if (Res.getNode())
2125 return Res;
2126
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002127 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002128
Chris Lattner471627c2006-02-16 08:02:36 +00002129 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002130 SDValue SGN =
2131 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2132 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2133 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002134 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002135
Chris Lattner471627c2006-02-16 08:02:36 +00002136 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002137 SDValue SRL =
2138 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2139 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2140 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002141 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002142 AddToWorklist(SRL.getNode());
2143 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002144 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002145 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002146
Nate Begeman4dd38312005-10-21 00:02:42 +00002147 // If we're dividing by a positive value, we're done. Otherwise, we must
2148 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002149 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002150 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002151
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002152 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002153 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002154 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002155
Nate Begemanc6f067a2005-10-20 02:15:44 +00002156 // if integer divide is expensive and we satisfy the requirements, emit an
2157 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002158 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002159 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002160 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002161 }
Dan Gohmana8665142007-06-25 16:23:39 +00002162
Dan Gohman06563a82007-07-03 14:03:57 +00002163 // undef / X -> 0
2164 if (N0.getOpcode() == ISD::UNDEF)
2165 return DAG.getConstant(0, VT);
2166 // X / undef -> undef
2167 if (N1.getOpcode() == ISD::UNDEF)
2168 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002169
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002170 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002171}
2172
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002173SDValue DAGCombiner::visitUDIV(SDNode *N) {
2174 SDValue N0 = N->getOperand(0);
2175 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002176 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002177
Dan Gohmana8665142007-06-25 16:23:39 +00002178 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002179 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002180 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002181 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002182 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002183
Nate Begeman21158fc2005-09-01 00:19:25 +00002184 // fold (udiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002185 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2186 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002187 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002188 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002189 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002190 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002191 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002192 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002193 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002194 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002195 if (N1.getOpcode() == ISD::SHL) {
2196 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002197 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002198 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002199 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002200 N1.getOperand(1),
2201 DAG.getConstant(SHC->getAPIntValue()
2202 .logBase2(),
2203 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002204 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002205 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002206 }
2207 }
2208 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002209 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002210 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002211 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002212 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002213 }
Dan Gohmana8665142007-06-25 16:23:39 +00002214
Dan Gohman06563a82007-07-03 14:03:57 +00002215 // undef / X -> 0
2216 if (N0.getOpcode() == ISD::UNDEF)
2217 return DAG.getConstant(0, VT);
2218 // X / undef -> undef
2219 if (N1.getOpcode() == ISD::UNDEF)
2220 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002221
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002222 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002223}
2224
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002225SDValue DAGCombiner::visitSREM(SDNode *N) {
2226 SDValue N0 = N->getOperand(0);
2227 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002228 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002229
Nate Begeman21158fc2005-09-01 00:19:25 +00002230 // fold (srem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002231 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2232 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002233 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002234 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002235 // If we know the sign bits of both operands are zero, strength reduce to a
2236 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002237 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002238 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002239 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002241
Dan Gohman9a693412007-11-26 23:46:11 +00002242 // If X/C can be simplified by the division-by-constant logic, lower
2243 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002244 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002245 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002246 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002247 SDValue OptimizedDiv = combine(Div.getNode());
2248 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002249 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002250 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002251 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002252 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002253 return Sub;
2254 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002255 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002256
Dan Gohman06563a82007-07-03 14:03:57 +00002257 // undef % X -> 0
2258 if (N0.getOpcode() == ISD::UNDEF)
2259 return DAG.getConstant(0, VT);
2260 // X % undef -> undef
2261 if (N1.getOpcode() == ISD::UNDEF)
2262 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002263
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002264 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002265}
2266
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002267SDValue DAGCombiner::visitUREM(SDNode *N) {
2268 SDValue N0 = N->getOperand(0);
2269 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002270 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002271
Nate Begeman21158fc2005-09-01 00:19:25 +00002272 // fold (urem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002273 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2274 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002275 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002276 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002277 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002278 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002279 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002280 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002281 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2282 if (N1.getOpcode() == ISD::SHL) {
2283 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002284 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002285 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002286 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002287 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002288 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002289 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002290 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002291 }
2292 }
2293 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002294
Dan Gohman9a693412007-11-26 23:46:11 +00002295 // If X/C can be simplified by the division-by-constant logic, lower
2296 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002297 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002298 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002299 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002300 SDValue OptimizedDiv = combine(Div.getNode());
2301 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002302 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002303 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002304 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002305 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002306 return Sub;
2307 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002308 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002309
Dan Gohman06563a82007-07-03 14:03:57 +00002310 // undef % X -> 0
2311 if (N0.getOpcode() == ISD::UNDEF)
2312 return DAG.getConstant(0, VT);
2313 // X % undef -> undef
2314 if (N1.getOpcode() == ISD::UNDEF)
2315 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002317 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002318}
2319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002320SDValue DAGCombiner::visitMULHS(SDNode *N) {
2321 SDValue N0 = N->getOperand(0);
2322 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002323 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002324 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002325 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002326
Nate Begeman21158fc2005-09-01 00:19:25 +00002327 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002328 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002329 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002330 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002331 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002332 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002333 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002334 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002335 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002336 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002337 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002338
Chris Lattner10bd29f2010-12-13 08:39:01 +00002339 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2340 // plus a shift.
2341 if (VT.isSimple() && !VT.isVector()) {
2342 MVT Simple = VT.getSimpleVT();
2343 unsigned SimpleSize = Simple.getSizeInBits();
2344 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2345 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2346 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2347 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2348 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002349 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002350 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002351 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2352 }
2353 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002354
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002355 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002356}
2357
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002358SDValue DAGCombiner::visitMULHU(SDNode *N) {
2359 SDValue N0 = N->getOperand(0);
2360 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002361 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002362 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002363 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002364
Nate Begeman21158fc2005-09-01 00:19:25 +00002365 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002366 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002367 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002368 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002369 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002370 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002371 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002372 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002373 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002374
Chris Lattner10bd29f2010-12-13 08:39:01 +00002375 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2376 // plus a shift.
2377 if (VT.isSimple() && !VT.isVector()) {
2378 MVT Simple = VT.getSimpleVT();
2379 unsigned SimpleSize = Simple.getSizeInBits();
2380 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2381 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2382 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2383 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2384 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2385 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002386 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002387 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2388 }
2389 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002390
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002391 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002392}
2393
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002394/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2395/// give the opcodes for the two computations that are being performed. Return
2396/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002397SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002398 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002399 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002400 bool HiExists = N->hasAnyUseOfValue(1);
2401 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002402 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002403 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002404 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002405 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002406 }
2407
2408 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002409 bool LoExists = N->hasAnyUseOfValue(0);
2410 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002411 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002412 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002413 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002414 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002415 }
2416
Evan Chengece4c682007-11-08 09:25:29 +00002417 // If both halves are used, return as it is.
2418 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002419 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002420
2421 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002422 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002423 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002424 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002425 SDValue LoOpt = combine(Lo.getNode());
2426 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002427 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002428 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002429 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002430 }
2431
Evan Chengece4c682007-11-08 09:25:29 +00002432 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002433 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002434 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002435 SDValue HiOpt = combine(Hi.getNode());
2436 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002437 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002438 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002439 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002440 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002441
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002442 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002443}
2444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002445SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2446 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002447 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002448
Chris Lattner15090e12010-12-15 06:04:19 +00002449 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002450 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002451
2452 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2453 // plus a shift.
2454 if (VT.isSimple() && !VT.isVector()) {
2455 MVT Simple = VT.getSimpleVT();
2456 unsigned SimpleSize = Simple.getSizeInBits();
2457 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2458 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2459 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2460 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2461 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2462 // Compute the high part as N1.
2463 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002464 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002465 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2466 // Compute the low part as N0.
2467 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2468 return CombineTo(N, Lo, Hi);
2469 }
2470 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002471
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002472 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002473}
2474
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002475SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2476 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002477 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002478
Chris Lattner15090e12010-12-15 06:04:19 +00002479 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002480 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002481
Chris Lattner15090e12010-12-15 06:04:19 +00002482 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2483 // plus a shift.
2484 if (VT.isSimple() && !VT.isVector()) {
2485 MVT Simple = VT.getSimpleVT();
2486 unsigned SimpleSize = Simple.getSizeInBits();
2487 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2488 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2489 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2490 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2491 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2492 // Compute the high part as N1.
2493 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002494 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002495 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2496 // Compute the low part as N0.
2497 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2498 return CombineTo(N, Lo, Hi);
2499 }
2500 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002501
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002502 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002503}
2504
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002505SDValue DAGCombiner::visitSMULO(SDNode *N) {
2506 // (smulo x, 2) -> (saddo x, x)
2507 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2508 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002509 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002510 N->getOperand(0), N->getOperand(0));
2511
2512 return SDValue();
2513}
2514
2515SDValue DAGCombiner::visitUMULO(SDNode *N) {
2516 // (umulo x, 2) -> (uaddo x, x)
2517 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2518 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002519 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002520 N->getOperand(0), N->getOperand(0));
2521
2522 return SDValue();
2523}
2524
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002525SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2526 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002527 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002528
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002529 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002530}
2531
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002532SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2533 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002534 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002535
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002536 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002537}
2538
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002539/// If this is a binary operator with two operands of the same opcode, try to
2540/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002541SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2542 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002543 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002544 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002545
Dan Gohmandd5286d2010-01-14 03:08:49 +00002546 // Bail early if none of these transforms apply.
2547 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2548
Chris Lattner002ee912006-05-05 06:31:05 +00002549 // For each of OP in AND/OR/XOR:
2550 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2551 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2552 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002553 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002554 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002555 //
2556 // do not sink logical op inside of a vector extend, since it may combine
2557 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002558 EVT Op0VT = N0.getOperand(0).getValueType();
2559 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002560 N0.getOpcode() == ISD::SIGN_EXTEND ||
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002561 N0.getOpcode() == ISD::BSWAP ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002562 // Avoid infinite looping with PromoteIntBinOp.
2563 (N0.getOpcode() == ISD::ANY_EXTEND &&
2564 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002565 (N0.getOpcode() == ISD::TRUNCATE &&
2566 (!TLI.isZExtFree(VT, Op0VT) ||
2567 !TLI.isTruncateFree(Op0VT, VT)) &&
2568 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002569 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002570 Op0VT == N1.getOperand(0).getValueType() &&
2571 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002572 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002573 N0.getOperand(0).getValueType(),
2574 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002575 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002576 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002577 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002578
Chris Lattner5ac42932006-05-05 06:10:43 +00002579 // For each of OP in SHL/SRL/SRA/AND...
2580 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2581 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2582 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002583 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002584 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002585 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002586 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002587 N0.getOperand(0).getValueType(),
2588 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002589 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002590 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002591 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002592 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002593
Nadav Rotemb0783502012-04-01 19:31:22 +00002594 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2595 // Only perform this optimization after type legalization and before
2596 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2597 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2598 // we don't want to undo this promotion.
2599 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2600 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002601 if ((N0.getOpcode() == ISD::BITCAST ||
2602 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2603 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002604 SDValue In0 = N0.getOperand(0);
2605 SDValue In1 = N1.getOperand(0);
2606 EVT In0Ty = In0.getValueType();
2607 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002608 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002609 // If both incoming values are integers, and the original types are the
2610 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002611 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002612 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2613 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002614 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002615 return BC;
2616 }
2617 }
2618
2619 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2620 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2621 // If both shuffles use the same mask, and both shuffle within a single
2622 // vector, then it is worthwhile to move the swizzle after the operation.
2623 // The type-legalizer generates this pattern when loading illegal
2624 // vector types from memory. In many cases this allows additional shuffle
2625 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002626 // There are other cases where moving the shuffle after the xor/and/or
2627 // is profitable even if shuffles don't perform a swizzle.
2628 // If both shuffles use the same mask, and both shuffles have the same first
2629 // or second operand, then it might still be profitable to move the shuffle
2630 // after the xor/and/or operation.
2631 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002632 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2633 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002634
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002635 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002636 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002637
Nadav Rotemb0783502012-04-01 19:31:22 +00002638 // Check that both shuffles use the same mask. The masks are known to be of
2639 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002640 // Check also that shuffles have only one use to avoid introducing extra
2641 // instructions.
2642 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2643 SVN0->getMask().equals(SVN1->getMask())) {
2644 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002645
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002646 // Don't try to fold this node if it requires introducing a
2647 // build vector of all zeros that might be illegal at this stage.
2648 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2649 if (!LegalTypes)
2650 ShOp = DAG.getConstant(0, VT);
2651 else
2652 ShOp = SDValue();
2653 }
2654
2655 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2656 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2657 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2658 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2659 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2660 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002661 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002662 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2663 &SVN0->getMask()[0]);
2664 }
2665
2666 // Don't try to fold this node if it requires introducing a
2667 // build vector of all zeros that might be illegal at this stage.
2668 ShOp = N0->getOperand(0);
2669 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2670 if (!LegalTypes)
2671 ShOp = DAG.getConstant(0, VT);
2672 else
2673 ShOp = SDValue();
2674 }
2675
2676 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2677 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2678 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2679 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2680 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2681 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002682 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002683 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2684 &SVN0->getMask()[0]);
2685 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002686 }
2687 }
Craig Topper9c3da312012-04-09 07:19:09 +00002688
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002689 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002690}
2691
Matthias Braun3ecb5572015-03-06 19:49:06 +00002692/// This contains all DAGCombine rules which reduce two values combined by
2693/// an And operation to a single value. This makes them reusable in the context
2694/// of visitSELECT(). Rules involving constants are not included as
2695/// visitSELECT() already handles those cases.
2696SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2697 SDNode *LocReference) {
2698 EVT VT = N1.getValueType();
2699
2700 // fold (and x, undef) -> 0
2701 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2702 return DAG.getConstant(0, VT);
2703 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2704 SDValue LL, LR, RL, RR, CC0, CC1;
2705 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2706 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2707 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2708
2709 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2710 LL.getValueType().isInteger()) {
2711 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2712 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2713 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2714 LR.getValueType(), LL, RL);
2715 AddToWorklist(ORNode.getNode());
2716 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2717 }
2718 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2719 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2720 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2721 LR.getValueType(), LL, RL);
2722 AddToWorklist(ANDNode.getNode());
2723 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2724 }
2725 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2727 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2728 LR.getValueType(), LL, RL);
2729 AddToWorklist(ORNode.getNode());
2730 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2731 }
2732 }
2733 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2734 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2735 Op0 == Op1 && LL.getValueType().isInteger() &&
2736 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2737 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2738 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2739 cast<ConstantSDNode>(RR)->isNullValue()))) {
2740 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2741 LL, DAG.getConstant(1, LL.getValueType()));
2742 AddToWorklist(ADDNode.getNode());
2743 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2744 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2745 }
2746 // canonicalize equivalent to ll == rl
2747 if (LL == RR && LR == RL) {
2748 Op1 = ISD::getSetCCSwappedOperands(Op1);
2749 std::swap(RL, RR);
2750 }
2751 if (LL == RL && LR == RR) {
2752 bool isInteger = LL.getValueType().isInteger();
2753 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2754 if (Result != ISD::SETCC_INVALID &&
2755 (!LegalOperations ||
2756 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2757 TLI.isOperationLegal(ISD::SETCC,
2758 getSetCCResultType(N0.getSimpleValueType())))))
2759 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2760 LL, LR, Result);
2761 }
2762 }
2763
2764 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2765 VT.getSizeInBits() <= 64) {
2766 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2767 APInt ADDC = ADDI->getAPIntValue();
2768 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2769 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2770 // immediate for an add, but it is legal if its top c2 bits are set,
2771 // transform the ADD so the immediate doesn't need to be materialized
2772 // in a register.
2773 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2774 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2775 SRLI->getZExtValue());
2776 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2777 ADDC |= Mask;
2778 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2779 SDValue NewAdd =
2780 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2781 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2782 CombineTo(N0.getNode(), NewAdd);
2783 // Return N so it doesn't get rechecked!
2784 return SDValue(LocReference, 0);
2785 }
2786 }
2787 }
2788 }
2789 }
2790 }
2791
2792 return SDValue();
2793}
2794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002795SDValue DAGCombiner::visitAND(SDNode *N) {
2796 SDValue N0 = N->getOperand(0);
2797 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002798 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002799
Dan Gohmana8665142007-06-25 16:23:39 +00002800 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002801 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002802 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002803 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002804
2805 // fold (and x, 0) -> 0, vector edition
2806 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002807 // do not return N0, because undef node may exist in N0
2808 return DAG.getConstant(
2809 APInt::getNullValue(
2810 N0.getValueType().getScalarType().getSizeInBits()),
2811 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002812 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002813 // do not return N1, because undef node may exist in N1
2814 return DAG.getConstant(
2815 APInt::getNullValue(
2816 N1.getValueType().getScalarType().getSizeInBits()),
2817 N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002818
2819 // fold (and x, -1) -> x, vector edition
2820 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2821 return N1;
2822 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2823 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002825
Nate Begeman21158fc2005-09-01 00:19:25 +00002826 // fold (and c1, c2) -> c1&c2
Matthias Braun00a40762015-02-24 18:52:01 +00002827 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002829 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002830 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002831 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002832 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002833 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002834 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002835 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002836 return N0;
2837 // if (and x, c) is known to be zero, return 0
Matthias Braun00a40762015-02-24 18:52:01 +00002838 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002839 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002840 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002841 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002842 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002843 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002844 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002845 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002846 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002847 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002848 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002849 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002850 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002851 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2852 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002853 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002854 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002855 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002856 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002857 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002858 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002859
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002860 // Replace uses of the AND with uses of the Zero extend node.
2861 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002862
Chris Lattner49beaf42006-02-02 07:17:31 +00002863 // We actually want to replace all uses of the any_extend with the
2864 // zero_extend, to avoid duplicating things. This will later cause this
2865 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002866 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002867 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002868 }
2869 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002870 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002871 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2872 // already be zero by virtue of the width of the base type of the load.
2873 //
2874 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2875 // more cases.
2876 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2877 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2878 N0.getOpcode() == ISD::LOAD) {
2879 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2880 N0 : N0.getOperand(0) );
2881
2882 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2883 // This can be a pure constant or a vector splat, in which case we treat the
2884 // vector as a scalar and use the splat value.
2885 APInt Constant = APInt::getNullValue(1);
2886 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2887 Constant = C->getAPIntValue();
2888 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2889 APInt SplatValue, SplatUndef;
2890 unsigned SplatBitSize;
2891 bool HasAnyUndefs;
2892 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2893 SplatBitSize, HasAnyUndefs);
2894 if (IsSplat) {
2895 // Undef bits can contribute to a possible optimisation if set, so
2896 // set them.
2897 SplatValue |= SplatUndef;
2898
2899 // The splat value may be something like "0x00FFFFFF", which means 0 for
2900 // the first vector value and FF for the rest, repeating. We need a mask
2901 // that will apply equally to all members of the vector, so AND all the
2902 // lanes of the constant together.
2903 EVT VT = Vector->getValueType(0);
2904 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002905
2906 // If the splat value has been compressed to a bitlength lower
2907 // than the size of the vector lane, we need to re-expand it to
2908 // the lane size.
2909 if (BitWidth > SplatBitSize)
2910 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2911 SplatBitSize < BitWidth;
2912 SplatBitSize = SplatBitSize * 2)
2913 SplatValue |= SplatValue.shl(SplatBitSize);
2914
Andrea Di Biagioc9d79e82015-03-07 12:24:55 +00002915 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2916 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2917 if (SplatBitSize % BitWidth == 0) {
2918 Constant = APInt::getAllOnesValue(BitWidth);
2919 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2920 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2921 }
James Molloy862fe492012-02-20 12:02:38 +00002922 }
2923 }
2924
2925 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2926 // actually legal and isn't going to get expanded, else this is a false
2927 // optimisation.
2928 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002929 Load->getValueType(0),
James Molloy862fe492012-02-20 12:02:38 +00002930 Load->getMemoryVT());
2931
2932 // Resize the constant to the same size as the original memory access before
2933 // extension. If it is still the AllOnesValue then this AND is completely
2934 // unneeded.
2935 Constant =
2936 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2937
2938 bool B;
2939 switch (Load->getExtensionType()) {
2940 default: B = false; break;
2941 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2942 case ISD::ZEXTLOAD:
2943 case ISD::NON_EXTLOAD: B = true; break;
2944 }
2945
2946 if (B && Constant.isAllOnesValue()) {
2947 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2948 // preserve semantics once we get rid of the AND.
2949 SDValue NewLoad(Load, 0);
2950 if (Load->getExtensionType() == ISD::EXTLOAD) {
2951 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002952 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002953 Load->getChain(), Load->getBasePtr(),
2954 Load->getOffset(), Load->getMemoryVT(),
2955 Load->getMemOperand());
2956 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002957 if (Load->getNumValues() == 3) {
2958 // PRE/POST_INC loads have 3 values.
2959 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2960 NewLoad.getValue(2) };
2961 CombineTo(Load, To, 3, true);
2962 } else {
2963 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2964 }
James Molloy862fe492012-02-20 12:02:38 +00002965 }
2966
2967 // Fold the AND away, taking care not to fold to the old load node if we
2968 // replaced it.
2969 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2970
2971 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2972 }
2973 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002974
Chris Lattnerf0032b32006-02-28 06:49:37 +00002975 // fold (and (load x), 255) -> (zextload x, i8)
2976 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002977 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2978 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2979 (N0.getOpcode() == ISD::ANY_EXTEND &&
2980 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2981 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2982 LoadSDNode *LN0 = HasAnyExt
2983 ? cast<LoadSDNode>(N0.getOperand(0))
2984 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002985 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002986 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002987 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002988 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2989 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2990 EVT LoadedVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002991 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Duncan Sands93b66092008-06-09 11:32:28 +00002992
Evan Cheng166a4e62010-01-06 19:38:29 +00002993 if (ExtVT == LoadedVT &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002994 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2995 ExtVT))) {
Wesley Peck527da1b2010-11-23 03:31:01 +00002996
2997 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002998 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002999 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3000 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003001 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003002 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3003 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3004 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003005
Chris Lattner88de3842010-01-07 21:53:27 +00003006 // Do not change the width of a volatile load.
3007 // Do not generate loads of non-round integer types since these can
3008 // be expensive (and would be wrong if the type is not byte sized).
3009 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003010 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3011 ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00003012 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00003013
Chris Lattner88de3842010-01-07 21:53:27 +00003014 unsigned Alignment = LN0->getAlignment();
3015 SDValue NewPtr = LN0->getBasePtr();
3016
3017 // For big endian targets, we need to add an offset to the pointer
3018 // to load the correct bytes. For little endian systems, we merely
3019 // need to read fewer bytes from the same pointer.
3020 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00003021 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3022 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3023 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003024 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00003025 NewPtr, DAG.getConstant(PtrOff, PtrType));
3026 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00003027 }
Chris Lattner88de3842010-01-07 21:53:27 +00003028
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003029 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00003030
Chris Lattner88de3842010-01-07 21:53:27 +00003031 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003032 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00003033 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00003034 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00003035 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00003036 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003037 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003038 CombineTo(LN0, Load, Load.getValue(1));
3039 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003040 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003041 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003042 }
3043 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003044
Matthias Braun3ecb5572015-03-06 19:49:06 +00003045 if (SDValue Combined = visitANDLike(N0, N1, N))
3046 return Combined;
3047
3048 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3049 if (N0.getOpcode() == N1.getOpcode()) {
3050 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3051 if (Tmp.getNode()) return Tmp;
Evan Chenge6a3b032012-07-17 18:54:11 +00003052 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003053
Matthias Braun3ecb5572015-03-06 19:49:06 +00003054 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3055 // fold (and (sra)) -> (and (srl)) when possible.
3056 if (!VT.isVector() &&
3057 SimplifyDemandedBits(SDValue(N, 0)))
3058 return SDValue(N, 0);
3059
3060 // fold (zext_inreg (extload x)) -> (zextload x)
3061 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3062 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3063 EVT MemVT = LN0->getMemoryVT();
3064 // If we zero all the possible extended bits, then we can turn this into
3065 // a zextload if we are running before legalize or the operation is legal.
3066 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3067 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3068 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3069 ((!LegalOperations && !LN0->isVolatile()) ||
3070 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3071 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3072 LN0->getChain(), LN0->getBasePtr(),
3073 MemVT, LN0->getMemOperand());
3074 AddToWorklist(N);
3075 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3076 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3077 }
3078 }
3079 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3080 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3081 N0.hasOneUse()) {
3082 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3083 EVT MemVT = LN0->getMemoryVT();
3084 // If we zero all the possible extended bits, then we can turn this into
3085 // a zextload if we are running before legalize or the operation is legal.
3086 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3087 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3088 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3089 ((!LegalOperations && !LN0->isVolatile()) ||
3090 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3091 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3092 LN0->getChain(), LN0->getBasePtr(),
3093 MemVT, LN0->getMemOperand());
3094 AddToWorklist(N);
3095 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3096 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3097 }
3098 }
Tim Northover819bfb52013-08-27 13:46:45 +00003099 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3100 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3101 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3102 N0.getOperand(1), false);
3103 if (BSwap.getNode())
3104 return BSwap;
3105 }
3106
Evan Chengf1005572010-04-28 07:10:39 +00003107 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003108}
3109
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003110/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003111SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3112 bool DemandHighBits) {
3113 if (!LegalOperations)
3114 return SDValue();
3115
3116 EVT VT = N->getValueType(0);
3117 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3118 return SDValue();
3119 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3120 return SDValue();
3121
3122 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3123 bool LookPassAnd0 = false;
3124 bool LookPassAnd1 = false;
3125 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3126 std::swap(N0, N1);
3127 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3128 std::swap(N0, N1);
3129 if (N0.getOpcode() == ISD::AND) {
3130 if (!N0.getNode()->hasOneUse())
3131 return SDValue();
3132 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3133 if (!N01C || N01C->getZExtValue() != 0xFF00)
3134 return SDValue();
3135 N0 = N0.getOperand(0);
3136 LookPassAnd0 = true;
3137 }
3138
3139 if (N1.getOpcode() == ISD::AND) {
3140 if (!N1.getNode()->hasOneUse())
3141 return SDValue();
3142 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3143 if (!N11C || N11C->getZExtValue() != 0xFF)
3144 return SDValue();
3145 N1 = N1.getOperand(0);
3146 LookPassAnd1 = true;
3147 }
3148
3149 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3150 std::swap(N0, N1);
3151 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3152 return SDValue();
3153 if (!N0.getNode()->hasOneUse() ||
3154 !N1.getNode()->hasOneUse())
3155 return SDValue();
3156
3157 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3158 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3159 if (!N01C || !N11C)
3160 return SDValue();
3161 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3162 return SDValue();
3163
3164 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3165 SDValue N00 = N0->getOperand(0);
3166 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3167 if (!N00.getNode()->hasOneUse())
3168 return SDValue();
3169 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3170 if (!N001C || N001C->getZExtValue() != 0xFF)
3171 return SDValue();
3172 N00 = N00.getOperand(0);
3173 LookPassAnd0 = true;
3174 }
3175
3176 SDValue N10 = N1->getOperand(0);
3177 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3178 if (!N10.getNode()->hasOneUse())
3179 return SDValue();
3180 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3181 if (!N101C || N101C->getZExtValue() != 0xFF00)
3182 return SDValue();
3183 N10 = N10.getOperand(0);
3184 LookPassAnd1 = true;
3185 }
3186
3187 if (N00 != N10)
3188 return SDValue();
3189
Tim Northover819bfb52013-08-27 13:46:45 +00003190 // Make sure everything beyond the low halfword gets set to zero since the SRL
3191 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003192 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003193 if (DemandHighBits && OpSizeInBits > 16) {
3194 // If the left-shift isn't masked out then the only way this is a bswap is
3195 // if all bits beyond the low 8 are 0. In that case the entire pattern
3196 // reduces to a left shift anyway: leave it for other parts of the combiner.
3197 if (!LookPassAnd0)
3198 return SDValue();
3199
3200 // However, if the right shift isn't masked out then it might be because
3201 // it's not needed. See if we can spot that too.
3202 if (!LookPassAnd1 &&
3203 !DAG.MaskedValueIsZero(
3204 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3205 return SDValue();
3206 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003207
Andrew Trickef9de2a2013-05-25 02:42:55 +00003208 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003209 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003210 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003211 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3212 return Res;
3213}
3214
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003215/// Return true if the specified node is an element that makes up a 32-bit
3216/// packed halfword byteswap.
3217/// ((x & 0x000000ff) << 8) |
3218/// ((x & 0x0000ff00) >> 8) |
3219/// ((x & 0x00ff0000) << 8) |
3220/// ((x & 0xff000000) >> 8)
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003221static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003222 if (!N.getNode()->hasOneUse())
3223 return false;
3224
3225 unsigned Opc = N.getOpcode();
3226 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3227 return false;
3228
3229 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3230 if (!N1C)
3231 return false;
3232
3233 unsigned Num;
3234 switch (N1C->getZExtValue()) {
3235 default:
3236 return false;
3237 case 0xFF: Num = 0; break;
3238 case 0xFF00: Num = 1; break;
3239 case 0xFF0000: Num = 2; break;
3240 case 0xFF000000: Num = 3; break;
3241 }
3242
3243 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3244 SDValue N0 = N.getOperand(0);
3245 if (Opc == ISD::AND) {
3246 if (Num == 0 || Num == 2) {
3247 // (x >> 8) & 0xff
3248 // (x >> 8) & 0xff0000
3249 if (N0.getOpcode() != ISD::SRL)
3250 return false;
3251 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3252 if (!C || C->getZExtValue() != 8)
3253 return false;
3254 } else {
3255 // (x << 8) & 0xff00
3256 // (x << 8) & 0xff000000
3257 if (N0.getOpcode() != ISD::SHL)
3258 return false;
3259 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3260 if (!C || C->getZExtValue() != 8)
3261 return false;
3262 }
3263 } else if (Opc == ISD::SHL) {
3264 // (x & 0xff) << 8
3265 // (x & 0xff0000) << 8
3266 if (Num != 0 && Num != 2)
3267 return false;
3268 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3269 if (!C || C->getZExtValue() != 8)
3270 return false;
3271 } else { // Opc == ISD::SRL
3272 // (x & 0xff00) >> 8
3273 // (x & 0xff000000) >> 8
3274 if (Num != 1 && Num != 3)
3275 return false;
3276 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3277 if (!C || C->getZExtValue() != 8)
3278 return false;
3279 }
3280
3281 if (Parts[Num])
3282 return false;
3283
3284 Parts[Num] = N0.getOperand(0).getNode();
3285 return true;
3286}
3287
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003288/// Match a 32-bit packed halfword bswap. That is
3289/// ((x & 0x000000ff) << 8) |
3290/// ((x & 0x0000ff00) >> 8) |
3291/// ((x & 0x00ff0000) << 8) |
3292/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003293/// => (rotl (bswap x), 16)
3294SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3295 if (!LegalOperations)
3296 return SDValue();
3297
3298 EVT VT = N->getValueType(0);
3299 if (VT != MVT::i32)
3300 return SDValue();
3301 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3302 return SDValue();
3303
Evan Cheng4c0bd962011-06-21 06:01:08 +00003304 // Look for either
3305 // (or (or (and), (and)), (or (and), (and)))
3306 // (or (or (or (and), (and)), (and)), (and))
3307 if (N0.getOpcode() != ISD::OR)
3308 return SDValue();
3309 SDValue N00 = N0.getOperand(0);
3310 SDValue N01 = N0.getOperand(1);
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003311 SDNode *Parts[4] = {};
Evan Cheng4c0bd962011-06-21 06:01:08 +00003312
Evan Chengbf0baa92012-12-13 01:34:32 +00003313 if (N1.getOpcode() == ISD::OR &&
3314 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003315 // (or (or (and), (and)), (or (and), (and)))
3316 SDValue N000 = N00.getOperand(0);
3317 if (!isBSwapHWordElement(N000, Parts))
3318 return SDValue();
3319
3320 SDValue N001 = N00.getOperand(1);
3321 if (!isBSwapHWordElement(N001, Parts))
3322 return SDValue();
3323 SDValue N010 = N01.getOperand(0);
3324 if (!isBSwapHWordElement(N010, Parts))
3325 return SDValue();
3326 SDValue N011 = N01.getOperand(1);
3327 if (!isBSwapHWordElement(N011, Parts))
3328 return SDValue();
3329 } else {
3330 // (or (or (or (and), (and)), (and)), (and))
3331 if (!isBSwapHWordElement(N1, Parts))
3332 return SDValue();
3333 if (!isBSwapHWordElement(N01, Parts))
3334 return SDValue();
3335 if (N00.getOpcode() != ISD::OR)
3336 return SDValue();
3337 SDValue N000 = N00.getOperand(0);
3338 if (!isBSwapHWordElement(N000, Parts))
3339 return SDValue();
3340 SDValue N001 = N00.getOperand(1);
3341 if (!isBSwapHWordElement(N001, Parts))
3342 return SDValue();
3343 }
3344
3345 // Make sure the parts are all coming from the same node.
3346 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3347 return SDValue();
3348
Andrew Trickef9de2a2013-05-25 02:42:55 +00003349 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003350 SDValue(Parts[0],0));
3351
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003352 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003353 // do (x << 16) | (x >> 16).
3354 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3355 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003356 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003357 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003358 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3359 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3360 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3361 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003362}
3363
Matthias Braun3ecb5572015-03-06 19:49:06 +00003364/// This contains all DAGCombine rules which reduce two values combined by
3365/// an Or operation to a single value \see visitANDLike().
3366SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3367 EVT VT = N1.getValueType();
3368 // fold (or x, undef) -> -1
3369 if (!LegalOperations &&
3370 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3371 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3372 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3373 }
3374 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3375 SDValue LL, LR, RL, RR, CC0, CC1;
3376 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3377 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3378 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3379
3380 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3381 LL.getValueType().isInteger()) {
3382 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3383 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3384 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3385 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3386 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3387 LR.getValueType(), LL, RL);
3388 AddToWorklist(ORNode.getNode());
3389 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3390 }
3391 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3392 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3393 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3394 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3395 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3396 LR.getValueType(), LL, RL);
3397 AddToWorklist(ANDNode.getNode());
3398 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3399 }
3400 }
3401 // canonicalize equivalent to ll == rl
3402 if (LL == RR && LR == RL) {
3403 Op1 = ISD::getSetCCSwappedOperands(Op1);
3404 std::swap(RL, RR);
3405 }
3406 if (LL == RL && LR == RR) {
3407 bool isInteger = LL.getValueType().isInteger();
3408 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3409 if (Result != ISD::SETCC_INVALID &&
3410 (!LegalOperations ||
3411 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3412 TLI.isOperationLegal(ISD::SETCC,
3413 getSetCCResultType(N0.getValueType())))))
3414 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3415 LL, LR, Result);
3416 }
3417 }
3418
3419 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3420 if (N0.getOpcode() == ISD::AND &&
3421 N1.getOpcode() == ISD::AND &&
3422 N0.getOperand(1).getOpcode() == ISD::Constant &&
3423 N1.getOperand(1).getOpcode() == ISD::Constant &&
3424 // Don't increase # computations.
3425 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3426 // We can only do this xform if we know that bits from X that are set in C2
3427 // but not in C1 are already zero. Likewise for Y.
3428 const APInt &LHSMask =
3429 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3430 const APInt &RHSMask =
3431 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3432
3433 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3434 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3435 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3436 N0.getOperand(0), N1.getOperand(0));
3437 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, X,
3438 DAG.getConstant(LHSMask | RHSMask, VT));
3439 }
3440 }
3441
3442 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3443 if (N0.getOpcode() == ISD::AND &&
3444 N1.getOpcode() == ISD::AND &&
3445 N0.getOperand(0) == N1.getOperand(0) &&
3446 // Don't increase # computations.
3447 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3448 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3449 N0.getOperand(1), N1.getOperand(1));
3450 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3451 }
3452
3453 return SDValue();
3454}
3455
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003456SDValue DAGCombiner::visitOR(SDNode *N) {
3457 SDValue N0 = N->getOperand(0);
3458 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003459 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003460
Dan Gohmana8665142007-06-25 16:23:39 +00003461 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003462 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003463 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003464 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003465
3466 // fold (or x, 0) -> x, vector edition
3467 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3468 return N1;
3469 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3470 return N0;
3471
3472 // fold (or x, -1) -> -1, vector edition
3473 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003474 // do not return N0, because undef node may exist in N0
3475 return DAG.getConstant(
3476 APInt::getAllOnesValue(
3477 N0.getValueType().getScalarType().getSizeInBits()),
3478 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003479 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003480 // do not return N1, because undef node may exist in N1
3481 return DAG.getConstant(
3482 APInt::getAllOnesValue(
3483 N1.getValueType().getScalarType().getSizeInBits()),
3484 N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003485
3486 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3487 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3488 // Do this only if the resulting shuffle is legal.
3489 if (isa<ShuffleVectorSDNode>(N0) &&
3490 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003491 // Avoid folding a node with illegal type.
3492 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003493 N0->getOperand(1) == N1->getOperand(1) &&
3494 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3495 bool CanFold = true;
3496 unsigned NumElts = VT.getVectorNumElements();
3497 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3498 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3499 // We construct two shuffle masks:
3500 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3501 // and N1 as the second operand.
3502 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3503 // and N0 as the second operand.
3504 // We do this because OR is commutable and therefore there might be
3505 // two ways to fold this node into a shuffle.
3506 SmallVector<int,4> Mask1;
3507 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003508
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003509 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3510 int M0 = SV0->getMaskElt(i);
3511 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003512
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003513 // Both shuffle indexes are undef. Propagate Undef.
3514 if (M0 < 0 && M1 < 0) {
3515 Mask1.push_back(M0);
3516 Mask2.push_back(M0);
3517 continue;
3518 }
3519
3520 if (M0 < 0 || M1 < 0 ||
3521 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3522 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3523 CanFold = false;
3524 break;
3525 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003526
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003527 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3528 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3529 }
3530
3531 if (CanFold) {
3532 // Fold this sequence only if the resulting shuffle is 'legal'.
3533 if (TLI.isShuffleMaskLegal(Mask1, VT))
3534 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3535 N1->getOperand(0), &Mask1[0]);
3536 if (TLI.isShuffleMaskLegal(Mask2, VT))
3537 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3538 N0->getOperand(0), &Mask2[0]);
3539 }
3540 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003541 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003542
Nate Begeman21158fc2005-09-01 00:19:25 +00003543 // fold (or c1, c2) -> c1|c2
Matthias Braun00a40762015-02-24 18:52:01 +00003544 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3545 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003546 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003547 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003548 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003549 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003550 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003551 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003552 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003553 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003554 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003555 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003556 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003557 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003558 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003559 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003560
Matthias Braun3ecb5572015-03-06 19:49:06 +00003561 if (SDValue Combined = visitORLike(N0, N1, N))
3562 return Combined;
3563
Evan Cheng4c0bd962011-06-21 06:01:08 +00003564 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3565 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003566 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003567 return BSwap;
3568 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003569 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003570 return BSwap;
3571
Nate Begeman22e251a2006-02-03 06:46:56 +00003572 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003573 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003574 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003575 return ROR;
3576 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003577 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003578 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003579 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003580 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003581 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
Matthias Braunf50ab432015-01-13 22:17:46 +00003582 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3583 return DAG.getNode(
3584 ISD::AND, SDLoc(N), VT,
3585 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3586 return SDValue();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003587 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003588 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003589 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003590 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003591 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003592 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003593 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003594
Chris Lattner97614c82006-09-14 20:50:57 +00003595 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003596 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003597 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003598
Dan Gohman600f62b2010-06-24 14:30:44 +00003599 // Simplify the operands using demanded-bits information.
3600 if (!VT.isVector() &&
3601 SimplifyDemandedBits(SDValue(N, 0)))
3602 return SDValue(N, 0);
3603
Evan Chengf1005572010-04-28 07:10:39 +00003604 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003605}
3606
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003607/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003608static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003609 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003610 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003611 Mask = Op.getOperand(1);
3612 Op = Op.getOperand(0);
3613 } else {
3614 return false;
3615 }
3616 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003617
Chris Lattner97614c82006-09-14 20:50:57 +00003618 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3619 Shift = Op;
3620 return true;
3621 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003622
Scott Michelcf0da6c2009-02-17 22:15:04 +00003623 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003624}
3625
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003626// Return true if we can prove that, whenever Neg and Pos are both in the
3627// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003628// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3629//
3630// (or (shift1 X, Neg), (shift2 X, Pos))
3631//
Adam Nemetc6553a82014-03-07 23:56:24 +00003632// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3633// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3634// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003635static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003636 // If OpSize is a power of 2 then:
3637 //
3638 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3639 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3640 //
3641 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3642 // for the stronger condition:
3643 //
3644 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3645 //
3646 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3647 // we can just replace Neg with Neg' for the rest of the function.
3648 //
3649 // In other cases we check for the even stronger condition:
3650 //
3651 // Neg == OpSize - Pos [B]
3652 //
3653 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3654 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003655 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003656 // We could actually use [A] whenever OpSize is a power of 2, but the
3657 // only extra cases that it would match are those uninteresting ones
3658 // where Neg and Pos are never in range at the same time. E.g. for
3659 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3660 // as well as (sub 32, Pos), but:
3661 //
3662 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3663 //
3664 // always invokes undefined behavior for 32-bit X.
3665 //
3666 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003667 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003668 if (Neg.getOpcode() == ISD::AND &&
3669 isPowerOf2_64(OpSize) &&
3670 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3671 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3672 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003673 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003674 }
3675
Richard Sandiford0f264db2014-01-09 10:49:40 +00003676 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3677 if (Neg.getOpcode() != ISD::SUB)
3678 return 0;
3679 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3680 if (!NegC)
3681 return 0;
3682 SDValue NegOp1 = Neg.getOperand(1);
3683
Adam Nemet5117f5d2014-03-07 23:56:28 +00003684 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3685 // Pos'. The truncation is redundant for the purpose of the equality.
3686 if (MaskLoBits &&
3687 Pos.getOpcode() == ISD::AND &&
3688 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3689 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3690 Pos = Pos.getOperand(0);
3691
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003692 // The condition we need is now:
3693 //
3694 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3695 //
3696 // If NegOp1 == Pos then we need:
3697 //
3698 // OpSize & Mask == NegC & Mask
3699 //
3700 // (because "x & Mask" is a truncation and distributes through subtraction).
3701 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003702 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003703 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003704 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3705 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003706 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003707 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3708 //
3709 // which, again because "x & Mask" is a truncation, becomes:
3710 //
3711 // NegC & Mask == (OpSize - PosC) & Mask
3712 // OpSize & Mask == (NegC + PosC) & Mask
3713 else if (Pos.getOpcode() == ISD::ADD &&
3714 Pos.getOperand(0) == NegOp1 &&
3715 Pos.getOperand(1).getOpcode() == ISD::Constant)
3716 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3717 NegC->getAPIntValue());
3718 else
3719 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003720
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003721 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003722 if (MaskLoBits)
3723 // Opsize & Mask is 0 since Mask is Opsize - 1.
3724 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003725 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003726}
3727
Richard Sandiford95c864d2014-01-08 15:40:47 +00003728// A subroutine of MatchRotate used once we have found an OR of two opposite
3729// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3730// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3731// former being preferred if supported. InnerPos and InnerNeg are Pos and
3732// Neg with outer conversions stripped away.
3733SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3734 SDValue Neg, SDValue InnerPos,
3735 SDValue InnerNeg, unsigned PosOpcode,
3736 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003737 // fold (or (shl x, (*ext y)),
3738 // (srl x, (*ext (sub 32, y)))) ->
3739 // (rotl x, y) or (rotr x, (sub 32, y))
3740 //
3741 // fold (or (shl x, (*ext (sub 32, y))),
3742 // (srl x, (*ext y))) ->
3743 // (rotr x, y) or (rotl x, (sub 32, y))
3744 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003745 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003746 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3747 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3748 HasPos ? Pos : Neg).getNode();
3749 }
3750
Craig Topperc0196b12014-04-14 00:51:57 +00003751 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003752}
3753
Chris Lattner97614c82006-09-14 20:50:57 +00003754// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3755// idioms for rotate, and if the target supports rotation instructions, generate
3756// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003757SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003758 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003759 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003760 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003761
3762 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003763 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3764 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003765 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003766
Chris Lattner97614c82006-09-14 20:50:57 +00003767 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003768 SDValue LHSShift; // The shift.
3769 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003770 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003771 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003772
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003773 SDValue RHSShift; // The shift.
3774 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003775 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003776 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003777
Chris Lattner97614c82006-09-14 20:50:57 +00003778 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003779 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003780
3781 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003782 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003783
Chris Lattner97614c82006-09-14 20:50:57 +00003784 // Canonicalize shl to left side in a shl/srl pair.
3785 if (RHSShift.getOpcode() == ISD::SHL) {
3786 std::swap(LHS, RHS);
3787 std::swap(LHSShift, RHSShift);
3788 std::swap(LHSMask , RHSMask );
3789 }
3790
Duncan Sands13237ac2008-06-06 12:08:01 +00003791 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003792 SDValue LHSShiftArg = LHSShift.getOperand(0);
3793 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003794 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003795 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003796
3797 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3798 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003799 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3800 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003801 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3802 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003803 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003804 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003805
Craig Topper65161fa2012-09-29 06:54:22 +00003806 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3807 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003808
Chris Lattner97614c82006-09-14 20:50:57 +00003809 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003810 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003811 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003812
Gabor Greiff304a7a2008-08-28 21:40:38 +00003813 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003814 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3815 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003816 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003817 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003818 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3819 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003820 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003821
Bill Wendling35972a92009-01-30 21:14:50 +00003822 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003823 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003824
Gabor Greiff304a7a2008-08-28 21:40:38 +00003825 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003826 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003827
Chris Lattner97614c82006-09-14 20:50:57 +00003828 // If there is a mask here, and we have a variable shift, we can't be sure
3829 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003830 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003831 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003832
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003833 // If the shift amount is sign/zext/any-extended just peel it off.
3834 SDValue LExtOp0 = LHSShiftAmt;
3835 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003836 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3837 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3838 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3839 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3840 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3841 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3842 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3843 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003844 LExtOp0 = LHSShiftAmt.getOperand(0);
3845 RExtOp0 = RHSShiftAmt.getOperand(0);
3846 }
3847
Richard Sandiford95c864d2014-01-08 15:40:47 +00003848 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3849 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3850 if (TryL)
3851 return TryL;
3852
3853 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3854 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3855 if (TryR)
3856 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003857
Craig Topperc0196b12014-04-14 00:51:57 +00003858 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003859}
3860
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003861SDValue DAGCombiner::visitXOR(SDNode *N) {
3862 SDValue N0 = N->getOperand(0);
3863 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003864 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003865
Dan Gohmana8665142007-06-25 16:23:39 +00003866 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003867 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003868 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003869 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003870
3871 // fold (xor x, 0) -> x, vector edition
3872 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3873 return N1;
3874 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3875 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003876 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003877
Evan Chengdf1690d2008-03-25 20:08:07 +00003878 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3879 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3880 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003881 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003882 if (N0.getOpcode() == ISD::UNDEF)
3883 return N0;
3884 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003885 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003886 // fold (xor c1, c2) -> c1^c2
Matthias Braun00a40762015-02-24 18:52:01 +00003887 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3888 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003889 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003890 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003891 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003892 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003893 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003894 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003895 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003896 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003897 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003898 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003899 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003900 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003901
Nate Begeman21158fc2005-09-01 00:19:25 +00003902 // fold !(x cc y) -> (x !cc y)
Matthias Brauna8558ca2015-02-24 18:51:59 +00003903 SDValue LHS, RHS, CC;
Oliver Stannardd29db9b2014-11-17 10:49:31 +00003904 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003905 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003906 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3907 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003908
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003909 if (!LegalOperations ||
3910 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003911 switch (N0.getOpcode()) {
3912 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003913 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003914 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003915 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003916 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003917 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003918 N0.getOperand(3), NotCC);
3919 }
3920 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003921 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003922
Chris Lattner58c227b2007-09-10 21:39:07 +00003923 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003924 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003925 N0.getNode()->hasOneUse() &&
3926 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003927 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003928 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003929 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003930 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003931 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003932 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003933
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003934 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003935 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003936 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003937 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003938 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3939 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003940 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3941 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003942 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003943 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003944 }
3945 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003946 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003947 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003948 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003949 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003950 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3951 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003952 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3953 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003954 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003955 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003956 }
3957 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003958 // fold (xor (and x, y), y) -> (and (not x), y)
3959 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003960 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003961 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003962 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003963 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003964 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003965 }
Bill Wendling35972a92009-01-30 21:14:50 +00003966 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003967 if (N1C && N0.getOpcode() == ISD::XOR) {
3968 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3969 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3970 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003971 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003972 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003973 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003974 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003975 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003976 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003977 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003978 }
3979 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003980 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003981 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003982
Chris Lattner8d6fc202006-05-05 05:51:50 +00003983 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3984 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003985 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003986 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003987 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003988
Chris Lattner098c01e2006-04-08 04:15:24 +00003989 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003990 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003991 SimplifyDemandedBits(SDValue(N, 0)))
3992 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003993
Evan Chengf1005572010-04-28 07:10:39 +00003994 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003995}
3996
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003997/// Handle transforms common to the three shifts, when the shift amount is a
3998/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003999SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004000 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004001 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004002 return SDValue();
4003
Gabor Greiff304a7a2008-08-28 21:40:38 +00004004 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004005 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004006
Chris Lattner7c709a52007-12-06 07:33:36 +00004007 // We want to pull some binops through shifts, so that we have (and (shift))
4008 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4009 // thing happens with address calculations, so it's important to canonicalize
4010 // it.
4011 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00004012
Chris Lattner7c709a52007-12-06 07:33:36 +00004013 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004014 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004015 case ISD::OR:
4016 case ISD::XOR:
4017 HighBitSet = false; // We can only transform sra if the high bit is clear.
4018 break;
4019 case ISD::AND:
4020 HighBitSet = true; // We can only transform sra if the high bit is set.
4021 break;
4022 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00004023 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004024 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00004025 HighBitSet = false; // We can only transform sra if the high bit is clear.
4026 break;
4027 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004028
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004029 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00004030 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004031 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004032
4033 // FIXME: disable this unless the input to the binop is a shift by a constant.
4034 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00004035 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004036 // void foo(int *X, int i) { X[i & 1235] = 1; }
4037 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00004038 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004039 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00004040 BinOpLHSVal->getOpcode() != ISD::SRA &&
4041 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4042 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004043 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004044
Owen Anderson53aa7a92009-08-10 22:56:29 +00004045 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004046
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004047 // If this is a signed shift right, and the high bit is modified by the
4048 // logical operation, do not perform the transformation. The highBitSet
4049 // boolean indicates the value of the high bit of the constant which would
4050 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00004051 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00004052 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4053 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004054 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004055 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004056
Weiming Zhao7f6daf12014-04-30 21:07:24 +00004057 if (!TLI.isDesirableToCommuteWithShift(LHS))
4058 return SDValue();
4059
Chris Lattner7c709a52007-12-06 07:33:36 +00004060 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004061 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004062 N->getValueType(0),
4063 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004064 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00004065
4066 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004067 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004068 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004069 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00004070
4071 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004072 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00004073}
4074
Adam Nemet67483892014-03-04 23:28:31 +00004075SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4076 assert(N->getOpcode() == ISD::TRUNCATE);
4077 assert(N->getOperand(0).getOpcode() == ISD::AND);
4078
4079 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4080 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4081 SDValue N01 = N->getOperand(0).getOperand(1);
4082
Matt Arsenault985b9de2014-03-17 18:58:01 +00004083 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00004084 EVT TruncVT = N->getValueType(0);
4085 SDValue N00 = N->getOperand(0).getOperand(0);
4086 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004087 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00004088
4089 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4090 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4091 DAG.getConstant(TruncC, TruncVT));
4092 }
4093 }
4094
4095 return SDValue();
4096}
Adam Nemet7f928f12014-03-07 23:56:30 +00004097
4098SDValue DAGCombiner::visitRotate(SDNode *N) {
4099 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4100 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4101 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4102 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4103 if (NewOp1.getNode())
4104 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4105 N->getOperand(0), NewOp1);
4106 }
4107 return SDValue();
4108}
4109
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004110SDValue DAGCombiner::visitSHL(SDNode *N) {
4111 SDValue N0 = N->getOperand(0);
4112 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004113 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004114 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004115
Daniel Sandersa1840d22013-11-11 17:23:41 +00004116 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004117 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004118 if (VT.isVector()) {
4119 SDValue FoldedVOp = SimplifyVBinOp(N);
4120 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004121
4122 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4123 // If setcc produces all-one true value then:
4124 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004125 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004126 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004127 SDValue N00 = N0->getOperand(0);
4128 SDValue N01 = N0->getOperand(1);
4129 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004130
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004131 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4132 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4133 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matthias Braunf50ab432015-01-13 22:17:46 +00004134 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004135 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4136 }
4137 } else {
4138 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004139 }
4140 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004141 }
4142
Nate Begeman21158fc2005-09-01 00:19:25 +00004143 // fold (shl c1, c2) -> c1<<c2
Matthias Braun00a40762015-02-24 18:52:01 +00004144 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004145 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004146 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004147 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004148 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004149 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004150 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004151 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004152 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004153 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004154 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004155 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004156 // fold (shl undef, x) -> 0
4157 if (N0.getOpcode() == ISD::UNDEF)
4158 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004159 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004160 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004161 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004162 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004163 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004164 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004165 N1.getOperand(0).getOpcode() == ISD::AND) {
4166 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4167 if (NewOp1.getNode())
4168 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004169 }
4170
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004171 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4172 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004173
4174 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004175 if (N1C && N0.getOpcode() == ISD::SHL) {
4176 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4177 uint64_t c1 = N0C1->getZExtValue();
4178 uint64_t c2 = N1C->getZExtValue();
4179 if (c1 + c2 >= OpSizeInBits)
4180 return DAG.getConstant(0, VT);
4181 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4182 DAG.getConstant(c1 + c2, N1.getValueType()));
4183 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004184 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004185
4186 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4187 // For this to be valid, the second form must not preserve any of the bits
4188 // that are shifted out by the inner shift in the first form. This means
4189 // the outer shift size must be >= the number of bits added by the ext.
4190 // As a corollary, we don't care what kind of ext it is.
4191 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4192 N0.getOpcode() == ISD::ANY_EXTEND ||
4193 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004194 N0.getOperand(0).getOpcode() == ISD::SHL) {
4195 SDValue N0Op0 = N0.getOperand(0);
4196 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4197 uint64_t c1 = N0Op0C1->getZExtValue();
4198 uint64_t c2 = N1C->getZExtValue();
4199 EVT InnerShiftVT = N0Op0.getValueType();
4200 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4201 if (c2 >= OpSizeInBits - InnerShiftSize) {
4202 if (c1 + c2 >= OpSizeInBits)
4203 return DAG.getConstant(0, VT);
4204 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4205 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4206 N0Op0->getOperand(0)),
4207 DAG.getConstant(c1 + c2, N1.getValueType()));
4208 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004209 }
4210 }
4211
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004212 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4213 // Only fold this if the inner zext has no other uses to avoid increasing
4214 // the total number of instructions.
4215 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004216 N0.getOperand(0).getOpcode() == ISD::SRL) {
4217 SDValue N0Op0 = N0.getOperand(0);
4218 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4219 uint64_t c1 = N0Op0C1->getZExtValue();
4220 if (c1 < VT.getScalarSizeInBits()) {
4221 uint64_t c2 = N1C->getZExtValue();
4222 if (c1 == c2) {
4223 SDValue NewOp0 = N0.getOperand(0);
4224 EVT CountVT = NewOp0.getOperand(1).getValueType();
4225 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4226 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004227 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004228 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4229 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004230 }
4231 }
4232 }
4233
Eli Friedman1877ac92011-06-09 22:14:44 +00004234 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4235 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004236 // Only fold this if the inner shift has no other uses -- if it does, folding
4237 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004238 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4239 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4240 uint64_t c1 = N0C1->getZExtValue();
4241 if (c1 < OpSizeInBits) {
4242 uint64_t c2 = N1C->getZExtValue();
4243 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4244 SDValue Shift;
4245 if (c2 > c1) {
4246 Mask = Mask.shl(c2 - c1);
4247 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4248 DAG.getConstant(c2 - c1, N1.getValueType()));
4249 } else {
4250 Mask = Mask.lshr(c1 - c2);
4251 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4252 DAG.getConstant(c1 - c2, N1.getValueType()));
4253 }
4254 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4255 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004256 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004257 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004258 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004259 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004260 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004261 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004262 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004263 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4264 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004265 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004266 HiBitsMask);
4267 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004268
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004269 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4270 // Variant of version done on multiply, except mul by a power of 2 is turned
4271 // into a shift.
4272 APInt Val;
4273 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4274 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4275 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4276 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4277 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4278 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4279 }
4280
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004281 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004282 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004283 if (NewSHL.getNode())
4284 return NewSHL;
4285 }
4286
Evan Chengf1005572010-04-28 07:10:39 +00004287 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004288}
4289
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004290SDValue DAGCombiner::visitSRA(SDNode *N) {
4291 SDValue N0 = N->getOperand(0);
4292 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004293 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004294 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004295
Daniel Sandersa1840d22013-11-11 17:23:41 +00004296 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004297 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004298 if (VT.isVector()) {
4299 SDValue FoldedVOp = SimplifyVBinOp(N);
4300 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004301
4302 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004303 }
4304
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004305 // fold (sra c1, c2) -> (sra c1, c2)
Matthias Braun00a40762015-02-24 18:52:01 +00004306 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004307 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004308 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004309 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004310 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004311 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004312 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004313 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004314 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004315 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004316 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004317 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004318 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004319 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004320 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004321 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4322 // sext_inreg.
4323 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004324 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004325 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4326 if (VT.isVector())
4327 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4328 ExtVT, VT.getVectorNumElements());
4329 if ((!LegalOperations ||
4330 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004331 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004332 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004333 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004334
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004335 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004336 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004337 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004338 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004339 if (Sum >= OpSizeInBits)
4340 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004341 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004342 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004343 }
4344 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004345
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004346 // fold (sra (shl X, m), (sub result_size, n))
4347 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004348 // result_size - n != m.
4349 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004350 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004351 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004352 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004353 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4354 if (N01C) {
4355 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004356 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004357 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4358
4359 if (VT.isVector())
4360 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4361
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004362 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004363 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004364
Scott Michelcf0da6c2009-02-17 22:15:04 +00004365 // If the shift is not a no-op (in which case this should be just a sign
4366 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004367 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004368 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004369 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004370 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4371 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004372 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004373
Owen Andersonb2c80da2011-02-25 21:41:48 +00004374 SDValue Amt = DAG.getConstant(ShiftAmt,
4375 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004376 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004377 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004378 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004379 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004380 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004381 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004382 }
4383 }
4384 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004385
Duncan Sands3ed76882009-02-01 18:06:53 +00004386 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004387 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004388 N1.getOperand(0).getOpcode() == ISD::AND) {
4389 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4390 if (NewOp1.getNode())
4391 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004392 }
4393
Matt Arsenault985b9de2014-03-17 18:58:01 +00004394 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004395 // if c1 is equal to the number of bits the trunc removes
4396 if (N0.getOpcode() == ISD::TRUNCATE &&
4397 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4398 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4399 N0.getOperand(0).hasOneUse() &&
4400 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004401 N1C) {
4402 SDValue N0Op0 = N0.getOperand(0);
4403 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4404 unsigned LargeShiftVal = LargeShift->getZExtValue();
4405 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004406
Matt Arsenault985b9de2014-03-17 18:58:01 +00004407 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4408 SDValue Amt =
4409 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4410 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4411 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4412 N0Op0.getOperand(0), Amt);
4413 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4414 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004415 }
4416 }
4417
Scott Michelcf0da6c2009-02-17 22:15:04 +00004418 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004419 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4420 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004421
4422
Nate Begeman21158fc2005-09-01 00:19:25 +00004423 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004424 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004425 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004426
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004427 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004428 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004429 if (NewSRA.getNode())
4430 return NewSRA;
4431 }
4432
Evan Chengf1005572010-04-28 07:10:39 +00004433 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004434}
4435
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004436SDValue DAGCombiner::visitSRL(SDNode *N) {
4437 SDValue N0 = N->getOperand(0);
4438 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004439 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004440 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004441
Daniel Sandersa1840d22013-11-11 17:23:41 +00004442 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004443 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004444 if (VT.isVector()) {
4445 SDValue FoldedVOp = SimplifyVBinOp(N);
4446 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004447
4448 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004449 }
4450
Nate Begeman21158fc2005-09-01 00:19:25 +00004451 // fold (srl c1, c2) -> c1 >>u c2
Matthias Braun00a40762015-02-24 18:52:01 +00004452 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004453 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004454 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004455 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004456 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004457 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004458 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004459 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004460 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004461 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004462 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004463 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004464 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004465 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004466 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004467 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004468
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004469 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004470 if (N1C && N0.getOpcode() == ISD::SRL) {
4471 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4472 uint64_t c1 = N01C->getZExtValue();
4473 uint64_t c2 = N1C->getZExtValue();
4474 if (c1 + c2 >= OpSizeInBits)
4475 return DAG.getConstant(0, VT);
4476 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4477 DAG.getConstant(c1 + c2, N1.getValueType()));
4478 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004479 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004480
Dale Johannesencd538af2010-12-17 21:45:49 +00004481 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004482 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4483 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004484 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004485 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004486 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4487 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004488 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4489 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004490 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004491 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004492 if (c1 + OpSizeInBits == InnerShiftSize) {
4493 if (c1 + c2 >= InnerShiftSize)
4494 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004495 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4496 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004497 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004498 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004499 }
4500 }
4501
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004502 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004503 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4504 unsigned BitSize = N0.getScalarValueSizeInBits();
4505 if (BitSize <= 64) {
4506 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4507 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4508 DAG.getConstant(~0ULL >> ShAmt, VT));
4509 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004510 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004511
Michael Liao62ebfd82013-06-21 18:45:27 +00004512 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004513 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4514 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004515 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004516 unsigned BitSize = SmallVT.getScalarSizeInBits();
4517 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004518 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004519
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004520 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004521 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004522 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004523 N0.getOperand(0),
4524 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004525 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004526 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004527 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4528 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4529 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004530 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004531 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004532
Chris Lattner2e33fb42006-10-12 20:23:19 +00004533 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4534 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004535 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004536 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004537 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004538 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004539
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004540 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004541 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004542 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004543 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004544 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004545
Chris Lattner49932492006-04-02 06:11:11 +00004546 // If any of the input bits are KnownOne, then the input couldn't be all
4547 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004548 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004549
Chris Lattner49932492006-04-02 06:11:11 +00004550 // If all of the bits input the to ctlz node are known to be zero, then
4551 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004552 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004553 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004554
Chris Lattner49932492006-04-02 06:11:11 +00004555 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004556 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004557 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004558 // could be set on input to the CTLZ node. If this bit is set, the SRL
4559 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4560 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004561 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004562 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004563
Chris Lattner49932492006-04-02 06:11:11 +00004564 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004565 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004566 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004567 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004568 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004569
Andrew Trickef9de2a2013-05-25 02:42:55 +00004570 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004571 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004572 }
4573 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004574
Duncan Sands3ed76882009-02-01 18:06:53 +00004575 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004576 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004577 N1.getOperand(0).getOpcode() == ISD::AND) {
4578 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4579 if (NewOp1.getNode())
4580 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004581 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004582
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004583 // fold operands of srl based on knowledge that the low bits are not
4584 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004585 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4586 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004587
Evan Chengb175de62009-12-18 21:31:31 +00004588 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004589 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004590 if (NewSRL.getNode())
4591 return NewSRL;
4592 }
4593
Dan Gohman600f62b2010-06-24 14:30:44 +00004594 // Attempt to convert a srl of a load into a narrower zero-extending load.
4595 SDValue NarrowLoad = ReduceLoadWidth(N);
4596 if (NarrowLoad.getNode())
4597 return NarrowLoad;
4598
Evan Chengb175de62009-12-18 21:31:31 +00004599 // Here is a common situation. We want to optimize:
4600 //
4601 // %a = ...
4602 // %b = and i32 %a, 2
4603 // %c = srl i32 %b, 1
4604 // brcond i32 %c ...
4605 //
4606 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004607 //
Evan Chengb175de62009-12-18 21:31:31 +00004608 // %a = ...
4609 // %b = and %a, 2
4610 // %c = setcc eq %b, 0
4611 // brcond %c ...
4612 //
4613 // However when after the source operand of SRL is optimized into AND, the SRL
4614 // itself may not be optimized further. Look for it and add the BRCOND into
4615 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004616 if (N->hasOneUse()) {
4617 SDNode *Use = *N->use_begin();
4618 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004619 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004620 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4621 // Also look pass the truncate.
4622 Use = *Use->use_begin();
4623 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004624 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004625 }
4626 }
Evan Chengb175de62009-12-18 21:31:31 +00004627
Evan Chengf1005572010-04-28 07:10:39 +00004628 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004629}
4630
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004631SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4632 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004633 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004634
4635 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004636 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004637 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004638 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004639}
4640
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004641SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4642 SDValue N0 = N->getOperand(0);
4643 EVT VT = N->getValueType(0);
4644
4645 // fold (ctlz_zero_undef c1) -> c2
4646 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004647 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004648 return SDValue();
4649}
4650
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004651SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4652 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004653 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004654
Nate Begeman21158fc2005-09-01 00:19:25 +00004655 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004656 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004657 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004658 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004659}
4660
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004661SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4662 SDValue N0 = N->getOperand(0);
4663 EVT VT = N->getValueType(0);
4664
4665 // fold (cttz_zero_undef c1) -> c2
4666 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004667 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004668 return SDValue();
4669}
4670
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004671SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4672 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004673 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004674
Nate Begeman21158fc2005-09-01 00:19:25 +00004675 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004676 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004677 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004678 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004679}
4680
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004681
4682/// \brief Generate Min/Max node
4683static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4684 SDValue True, SDValue False,
4685 ISD::CondCode CC, const TargetLowering &TLI,
4686 SelectionDAG &DAG) {
4687 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4688 return SDValue();
4689
4690 switch (CC) {
4691 case ISD::SETOLT:
4692 case ISD::SETOLE:
4693 case ISD::SETLT:
4694 case ISD::SETLE:
4695 case ISD::SETULT:
4696 case ISD::SETULE: {
4697 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4698 if (TLI.isOperationLegal(Opcode, VT))
4699 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4700 return SDValue();
4701 }
4702 case ISD::SETOGT:
4703 case ISD::SETOGE:
4704 case ISD::SETGT:
4705 case ISD::SETGE:
4706 case ISD::SETUGT:
4707 case ISD::SETUGE: {
4708 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4709 if (TLI.isOperationLegal(Opcode, VT))
4710 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4711 return SDValue();
4712 }
4713 default:
4714 return SDValue();
4715 }
4716}
4717
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004718SDValue DAGCombiner::visitSELECT(SDNode *N) {
4719 SDValue N0 = N->getOperand(0);
4720 SDValue N1 = N->getOperand(1);
4721 SDValue N2 = N->getOperand(2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004722 EVT VT = N->getValueType(0);
4723 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004724
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004725 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004726 if (N1 == N2)
4727 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004728 // fold (select true, X, Y) -> X
Matthias Braun00a40762015-02-24 18:52:01 +00004729 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004730 if (N0C && !N0C->isNullValue())
4731 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004732 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004733 if (N0C && N0C->isNullValue())
4734 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004735 // fold (select C, 1, X) -> (or C, X)
Matthias Braun00a40762015-02-24 18:52:01 +00004736 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson9f944592009-08-11 20:47:22 +00004737 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004738 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004739 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004740 // We can't do this reliably if integer based booleans have different contents
4741 // to floating point based booleans. This is because we can't tell whether we
4742 // have an integer-based boolean or a floating-point-based boolean unless we
4743 // can find the SETCC that produced it and inspect its operands. This is
4744 // fairly easy if C is the SETCC node, but it can potentially be
4745 // undiscoverable (or not reasonably discoverable). For example, it could be
4746 // in another basic block or it could require searching a complicated
4747 // expression.
Matthias Braun00a40762015-02-24 18:52:01 +00004748 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004749 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004750 (VT0 == MVT::i1 || (VT0.isInteger() &&
4751 TLI.getBooleanContents(false, false) ==
4752 TLI.getBooleanContents(false, true) &&
4753 TLI.getBooleanContents(false, false) ==
4754 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004755 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004756 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004757 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004758 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004759 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004760 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004761 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004762 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004763 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004764 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4765 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004766 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004767 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004768 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004769 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004770 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004771 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004772 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004773 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004774 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004775 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004776 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004777 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004778 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004779 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004780 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004781 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004782 // fold (select X, X, Y) -> (or X, Y)
4783 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004784 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004785 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004786 // fold (select X, Y, X) -> (and X, Y)
4787 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004788 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004789 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004790
Chris Lattner6c14c352005-10-18 06:04:22 +00004791 // If we can fold this based on the true/false value, do so.
4792 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004793 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004794
Nate Begemanc760f802005-09-19 22:34:01 +00004795 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004796 if (N0.getOpcode() == ISD::SETCC) {
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004797 // select x, y (fcmp lt x, y) -> fminnum x, y
4798 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4799 //
4800 // This is OK if we don't care about what happens if either operand is a
4801 // NaN.
4802 //
4803
4804 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4805 // no signed zeros as well as no nans.
4806 const TargetOptions &Options = DAG.getTarget().Options;
4807 if (Options.UnsafeFPMath &&
4808 VT.isFloatingPoint() && N0.hasOneUse() &&
4809 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4810 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4811
4812 SDValue FMinMax =
4813 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4814 N1, N2, CC, TLI, DAG);
4815 if (FMinMax)
4816 return FMinMax;
4817 }
4818
Tom Stellard3787b122014-06-10 16:01:29 +00004819 if ((!LegalOperations &&
4820 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004821 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004822 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004823 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004824 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004825 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004826 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004827
Matthias Braun898d11e2015-03-06 19:49:10 +00004828 if (VT0 == MVT::i1) {
4829 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4830 // select (and Cond0, Cond1), X, Y
4831 // -> select Cond0, (select Cond1, X, Y), Y
4832 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4833 SDValue Cond0 = N0->getOperand(0);
4834 SDValue Cond1 = N0->getOperand(1);
4835 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4836 N1.getValueType(), Cond1, N1, N2);
4837 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4838 InnerSelect, N2);
4839 }
4840 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4841 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4842 SDValue Cond0 = N0->getOperand(0);
4843 SDValue Cond1 = N0->getOperand(1);
4844 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4845 N1.getValueType(), Cond1, N1, N2);
4846 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4847 InnerSelect);
4848 }
4849 }
4850
4851 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4852 if (N1->getOpcode() == ISD::SELECT) {
4853 SDValue N1_0 = N1->getOperand(0);
4854 SDValue N1_1 = N1->getOperand(1);
4855 SDValue N1_2 = N1->getOperand(2);
4856 if (N1_2 == N2) {
4857 // Create the actual and node if we can generate good code for it.
4858 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4859 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4860 N0, N1_0);
4861 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4862 N1_1, N2);
4863 }
4864 // Otherwise see if we can optimize the "and" to a better pattern.
4865 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4866 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4867 N1_1, N2);
4868 }
4869 }
4870 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4871 if (N2->getOpcode() == ISD::SELECT) {
4872 SDValue N2_0 = N2->getOperand(0);
4873 SDValue N2_1 = N2->getOperand(1);
4874 SDValue N2_2 = N2->getOperand(2);
4875 if (N2_1 == N1) {
4876 // Create the actual or node if we can generate good code for it.
4877 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4878 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4879 N0, N2_0);
4880 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4881 N1, N2_2);
4882 }
4883 // Otherwise see if we can optimize to a better pattern.
4884 if (SDValue Combined = visitORLike(N0, N2_0, N))
4885 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4886 N1, N2_2);
4887 }
4888 }
4889 }
4890
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004891 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004892}
4893
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004894static
4895std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4896 SDLoc DL(N);
4897 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004898 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004899
4900 // Split the inputs.
4901 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004902 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4903 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004904
4905 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4906 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4907
4908 return std::make_pair(Lo, Hi);
4909}
4910
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004911// This function assumes all the vselect's arguments are CONCAT_VECTOR
4912// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4913static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4914 SDLoc dl(N);
4915 SDValue Cond = N->getOperand(0);
4916 SDValue LHS = N->getOperand(1);
4917 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004918 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004919 int NumElems = VT.getVectorNumElements();
4920 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4921 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4922 Cond.getOpcode() == ISD::BUILD_VECTOR);
4923
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004924 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4925 // binary ones here.
4926 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4927 return SDValue();
4928
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004929 // We're sure we have an even number of elements due to the
4930 // concat_vectors we have as arguments to vselect.
4931 // Skip BV elements until we find one that's not an UNDEF
4932 // After we find an UNDEF element, keep looping until we get to half the
4933 // length of the BV and see if all the non-undef nodes are the same.
4934 ConstantSDNode *BottomHalf = nullptr;
4935 for (int i = 0; i < NumElems / 2; ++i) {
4936 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4937 continue;
4938
4939 if (BottomHalf == nullptr)
4940 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4941 else if (Cond->getOperand(i).getNode() != BottomHalf)
4942 return SDValue();
4943 }
4944
4945 // Do the same for the second half of the BuildVector
4946 ConstantSDNode *TopHalf = nullptr;
4947 for (int i = NumElems / 2; i < NumElems; ++i) {
4948 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4949 continue;
4950
4951 if (TopHalf == nullptr)
4952 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4953 else if (Cond->getOperand(i).getNode() != TopHalf)
4954 return SDValue();
4955 }
4956
4957 assert(TopHalf && BottomHalf &&
4958 "One half of the selector was all UNDEFs and the other was all the "
4959 "same value. This should have been addressed before this function.");
4960 return DAG.getNode(
4961 ISD::CONCAT_VECTORS, dl, VT,
4962 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4963 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4964}
4965
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004966SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4967
4968 if (Level >= AfterLegalizeTypes)
4969 return SDValue();
4970
4971 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4972 SDValue Mask = MST->getMask();
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00004973 SDValue Data = MST->getValue();
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004974 SDLoc DL(N);
4975
4976 // If the MSTORE data type requires splitting and the mask is provided by a
4977 // SETCC, then split both nodes and its operands before legalization. This
4978 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4979 // and enables future optimizations (e.g. min/max pattern matching on X86).
4980 if (Mask.getOpcode() == ISD::SETCC) {
4981
4982 // Check if any splitting is required.
4983 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4984 TargetLowering::TypeSplitVector)
4985 return SDValue();
4986
4987 SDValue MaskLo, MaskHi, Lo, Hi;
4988 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4989
4990 EVT LoVT, HiVT;
4991 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4992
4993 SDValue Chain = MST->getChain();
4994 SDValue Ptr = MST->getBasePtr();
4995
4996 EVT MemoryVT = MST->getMemoryVT();
4997 unsigned Alignment = MST->getOriginalAlignment();
4998
4999 // if Alignment is equal to the vector size,
5000 // take the half of it for the second part
5001 unsigned SecondHalfAlignment =
5002 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5003 Alignment/2 : Alignment;
5004
5005 EVT LoMemVT, HiMemVT;
5006 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5007
5008 SDValue DataLo, DataHi;
5009 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5010
5011 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005012 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005013 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5014 Alignment, MST->getAAInfo(), MST->getRanges());
5015
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005016 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5017 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005018
5019 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5020 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5021 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5022
5023 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005024 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005025 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5026 SecondHalfAlignment, MST->getAAInfo(),
5027 MST->getRanges());
5028
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005029 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5030 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005031
5032 AddToWorklist(Lo.getNode());
5033 AddToWorklist(Hi.getNode());
5034
5035 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5036 }
5037 return SDValue();
5038}
5039
5040SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5041
5042 if (Level >= AfterLegalizeTypes)
5043 return SDValue();
5044
5045 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5046 SDValue Mask = MLD->getMask();
5047 SDLoc DL(N);
5048
5049 // If the MLOAD result requires splitting and the mask is provided by a
5050 // SETCC, then split both nodes and its operands before legalization. This
5051 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5052 // and enables future optimizations (e.g. min/max pattern matching on X86).
5053
5054 if (Mask.getOpcode() == ISD::SETCC) {
5055 EVT VT = N->getValueType(0);
5056
5057 // Check if any splitting is required.
5058 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5059 TargetLowering::TypeSplitVector)
5060 return SDValue();
5061
5062 SDValue MaskLo, MaskHi, Lo, Hi;
5063 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5064
5065 SDValue Src0 = MLD->getSrc0();
5066 SDValue Src0Lo, Src0Hi;
5067 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5068
5069 EVT LoVT, HiVT;
5070 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5071
5072 SDValue Chain = MLD->getChain();
5073 SDValue Ptr = MLD->getBasePtr();
5074 EVT MemoryVT = MLD->getMemoryVT();
5075 unsigned Alignment = MLD->getOriginalAlignment();
5076
5077 // if Alignment is equal to the vector size,
5078 // take the half of it for the second part
5079 unsigned SecondHalfAlignment =
5080 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5081 Alignment/2 : Alignment;
5082
5083 EVT LoMemVT, HiMemVT;
5084 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5085
5086 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005087 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005088 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5089 Alignment, MLD->getAAInfo(), MLD->getRanges());
5090
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005091 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5092 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005093
5094 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5095 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5096 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5097
5098 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005099 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005100 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5101 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5102
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005103 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5104 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005105
5106 AddToWorklist(Lo.getNode());
5107 AddToWorklist(Hi.getNode());
5108
5109 // Build a factor node to remember that this load is independent of the
5110 // other one.
5111 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5112 Hi.getValue(1));
5113
5114 // Legalized the chain result - switch anything that used the old chain to
5115 // use the new one.
5116 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5117
5118 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5119
5120 SDValue RetOps[] = { LoadRes, Chain };
5121 return DAG.getMergeValues(RetOps, DL);
5122 }
5123 return SDValue();
5124}
5125
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005126SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5127 SDValue N0 = N->getOperand(0);
5128 SDValue N1 = N->getOperand(1);
5129 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005130 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005131
5132 // Canonicalize integer abs.
5133 // vselect (setg[te] X, 0), X, -X ->
5134 // vselect (setgt X, -1), X, -X ->
5135 // vselect (setl[te] X, 0), -X, X ->
5136 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5137 if (N0.getOpcode() == ISD::SETCC) {
5138 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5139 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5140 bool isAbs = false;
5141 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5142
5143 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5144 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5145 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5146 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5147 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5148 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5149 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5150
5151 if (isAbs) {
5152 EVT VT = LHS.getValueType();
5153 SDValue Shift = DAG.getNode(
5154 ISD::SRA, DL, VT, LHS,
5155 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5156 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005157 AddToWorklist(Shift.getNode());
5158 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005159 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5160 }
5161 }
5162
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005163 // If the VSELECT result requires splitting and the mask is provided by a
5164 // SETCC, then split both nodes and its operands before legalization. This
5165 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5166 // and enables future optimizations (e.g. min/max pattern matching on X86).
5167 if (N0.getOpcode() == ISD::SETCC) {
5168 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005169
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005170 // Check if any splitting is required.
5171 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5172 TargetLowering::TypeSplitVector)
5173 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005174
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005175 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005176 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5177 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5178 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005179
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005180 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5181 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005182
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005183 // Add the new VSELECT nodes to the work list in case they need to be split
5184 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005185 AddToWorklist(Lo.getNode());
5186 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005187
5188 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005189 }
5190
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00005191 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5192 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5193 return N1;
5194 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5195 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5196 return N2;
5197
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005198 // The ConvertSelectToConcatVector function is assuming both the above
5199 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5200 // and addressed.
5201 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5202 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5203 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5204 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5205 if (CV.getNode())
5206 return CV;
5207 }
5208
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005209 return SDValue();
5210}
5211
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005212SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5213 SDValue N0 = N->getOperand(0);
5214 SDValue N1 = N->getOperand(1);
5215 SDValue N2 = N->getOperand(2);
5216 SDValue N3 = N->getOperand(3);
5217 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00005218 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005219
Nate Begemanc760f802005-09-19 22:34:01 +00005220 // fold select_cc lhs, rhs, x, x, cc -> x
5221 if (N2 == N3)
5222 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005223
Chris Lattner8b68dec2006-09-20 06:19:26 +00005224 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00005225 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005226 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00005227 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005228 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00005229
Stephen Lin605207f2013-06-15 04:03:33 +00005230 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5231 if (!SCCC->isNullValue())
5232 return N2; // cond always true -> true val
5233 else
5234 return N3; // cond always false -> false val
Mehdi Amini648eff12015-01-14 05:45:24 +00005235 } else if (SCC->getOpcode() == ISD::UNDEF) {
5236 // When the condition is UNDEF, just return the first operand. This is
5237 // coherent the DAG creation, no setcc node is created in this case
5238 return N2;
5239 } else if (SCC.getOpcode() == ISD::SETCC) {
5240 // Fold to a simpler select_cc
Stephen Lin605207f2013-06-15 04:03:33 +00005241 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5242 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5243 SCC.getOperand(2));
Mehdi Amini648eff12015-01-14 05:45:24 +00005244 }
Chris Lattner8b68dec2006-09-20 06:19:26 +00005245 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005246
Chris Lattner6c14c352005-10-18 06:04:22 +00005247 // If we can fold this based on the true/false value, do so.
5248 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005249 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00005250
Nate Begemanc760f802005-09-19 22:34:01 +00005251 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00005252 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00005253}
5254
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005255SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00005256 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00005257 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005258 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00005259}
5260
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005261// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5262// dag node into a ConstantSDNode or a build_vector of constants.
5263// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005264// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005265// Vector extends are not folded if operations are legal; this is to
5266// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005267static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5268 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005269 bool LegalOperations) {
5270 unsigned Opcode = N->getOpcode();
5271 SDValue N0 = N->getOperand(0);
5272 EVT VT = N->getValueType(0);
5273
5274 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5275 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5276
5277 // fold (sext c1) -> c1
5278 // fold (zext c1) -> c1
5279 // fold (aext c1) -> c1
5280 if (isa<ConstantSDNode>(N0))
5281 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5282
5283 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5284 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5285 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005286 EVT SVT = VT.getScalarType();
5287 if (!(VT.isVector() &&
5288 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005289 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00005290 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005291
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005292 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005293 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005294 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5295 unsigned ShAmt = VTBits - EVTBits;
5296 SmallVector<SDValue, 8> Elts;
5297 unsigned NumElts = N0->getNumOperands();
5298 SDLoc DL(N);
5299
5300 for (unsigned i=0; i != NumElts; ++i) {
5301 SDValue Op = N0->getOperand(i);
5302 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005303 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005304 continue;
5305 }
5306
5307 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5308 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5309 if (Opcode == ISD::SIGN_EXTEND)
5310 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005311 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005312 else
5313 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005314 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005315 }
5316
Craig Topper48d114b2014-04-26 18:35:24 +00005317 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005318}
5319
Evan Chenge106e2f2007-10-29 19:58:20 +00005320// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00005321// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00005322// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00005323// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005324static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00005325 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00005326 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00005327 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005328 bool HasCopyToRegUses = false;
5329 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00005330 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5331 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00005332 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00005333 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00005334 if (User == N)
5335 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00005336 if (UI.getUse().getResNo() != N0.getResNo())
5337 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005338 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00005339 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005340 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5341 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5342 // Sign bits will be lost after a zext.
5343 return false;
5344 bool Add = false;
5345 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005346 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00005347 if (UseOp == N0)
5348 continue;
5349 if (!isa<ConstantSDNode>(UseOp))
5350 return false;
5351 Add = true;
5352 }
5353 if (Add)
5354 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005355 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005356 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00005357 // If truncates aren't free and there are users we can't
5358 // extend, it isn't worthwhile.
5359 if (!isTruncFree)
5360 return false;
5361 // Remember if this value is live-out.
5362 if (User->getOpcode() == ISD::CopyToReg)
5363 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00005364 }
5365
5366 if (HasCopyToRegUses) {
5367 bool BothLiveOut = false;
5368 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5369 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005370 SDUse &Use = UI.getUse();
5371 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5372 BothLiveOut = true;
5373 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00005374 }
5375 }
5376 if (BothLiveOut)
5377 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00005378 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00005379 return ExtendNodes.size();
5380 }
5381 return true;
5382}
5383
Craig Toppere0b71182013-07-13 07:43:40 +00005384void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005385 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005386 ISD::NodeType ExtType) {
5387 // Extend SetCC uses if necessary.
5388 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5389 SDNode *SetCC = SetCCs[i];
5390 SmallVector<SDValue, 4> Ops;
5391
5392 for (unsigned j = 0; j != 2; ++j) {
5393 SDValue SOp = SetCC->getOperand(j);
5394 if (SOp == Trunc)
5395 Ops.push_back(ExtLoad);
5396 else
5397 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5398 }
5399
5400 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005401 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005402 }
5403}
5404
Ahmed Bougachae892d132015-02-05 18:31:02 +00005405// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5406SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5407 SDValue N0 = N->getOperand(0);
5408 EVT DstVT = N->getValueType(0);
5409 EVT SrcVT = N0.getValueType();
5410
5411 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5412 N->getOpcode() == ISD::ZERO_EXTEND) &&
5413 "Unexpected node type (not an extend)!");
5414
5415 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5416 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5417 // (v8i32 (sext (v8i16 (load x))))
5418 // into:
5419 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5420 // (v4i32 (sextload (x + 16)))))
5421 // Where uses of the original load, i.e.:
5422 // (v8i16 (load x))
5423 // are replaced with:
5424 // (v8i16 (truncate
5425 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5426 // (v4i32 (sextload (x + 16)))))))
5427 //
5428 // This combine is only applicable to illegal, but splittable, vectors.
5429 // All legal types, and illegal non-vector types, are handled elsewhere.
5430 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5431 //
5432 if (N0->getOpcode() != ISD::LOAD)
5433 return SDValue();
5434
5435 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5436
5437 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5438 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5439 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5440 return SDValue();
5441
5442 SmallVector<SDNode *, 4> SetCCs;
5443 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5444 return SDValue();
5445
5446 ISD::LoadExtType ExtType =
5447 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5448
5449 // Try to split the vector types to get down to legal types.
5450 EVT SplitSrcVT = SrcVT;
5451 EVT SplitDstVT = DstVT;
5452 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5453 SplitSrcVT.getVectorNumElements() > 1) {
5454 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5455 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5456 }
5457
5458 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5459 return SDValue();
5460
5461 SDLoc DL(N);
5462 const unsigned NumSplits =
5463 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5464 const unsigned Stride = SplitSrcVT.getStoreSize();
5465 SmallVector<SDValue, 4> Loads;
5466 SmallVector<SDValue, 4> Chains;
5467
5468 SDValue BasePtr = LN0->getBasePtr();
5469 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5470 const unsigned Offset = Idx * Stride;
5471 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5472
5473 SDValue SplitLoad = DAG.getExtLoad(
5474 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5475 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5476 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5477 Align, LN0->getAAInfo());
5478
5479 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5480 DAG.getConstant(Stride, BasePtr.getValueType()));
5481
5482 Loads.push_back(SplitLoad.getValue(0));
5483 Chains.push_back(SplitLoad.getValue(1));
5484 }
5485
5486 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5487 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5488
5489 CombineTo(N, NewValue);
5490
5491 // Replace uses of the original load (before extension)
5492 // with a truncate of the concatenated sextloaded vectors.
5493 SDValue Trunc =
5494 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5495 CombineTo(N0.getNode(), Trunc, NewChain);
5496 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5497 (ISD::NodeType)N->getOpcode());
5498 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5499}
5500
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005501SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5502 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005503 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005504
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005505 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5506 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005507 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005508
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005509 // fold (sext (sext x)) -> (sext x)
5510 // fold (sext (aext x)) -> (sext x)
5511 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005512 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005513 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005514
Chris Lattnerfce448f2007-02-26 03:13:59 +00005515 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005516 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5517 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005518 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5519 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005520 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5521 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005522 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005523 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005524 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005525 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005526 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005527 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005528
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005529 // See if the value being truncated is already sign extended. If so, just
5530 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005531 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005532 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5533 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5534 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005535 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005536
Chris Lattnerfce448f2007-02-26 03:13:59 +00005537 if (OpBits == DestBits) {
5538 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5539 // bits, it is already ready.
5540 if (NumSignBits > DestBits-MidBits)
5541 return Op;
5542 } else if (OpBits < DestBits) {
5543 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5544 // bits, just sext from i32.
5545 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005546 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005547 } else {
5548 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5549 // bits, just truncate to i32.
5550 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005551 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005552 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005553
Chris Lattnerfce448f2007-02-26 03:13:59 +00005554 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005555 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5556 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005557 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005558 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005559 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005560 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5561 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005562 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005563 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005564 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005565
Evan Chengbce7c472005-12-14 02:19:23 +00005566 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005567 // Only generate vector extloads when 1) they're legal, and 2) they are
5568 // deemed desirable by the target.
5569 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5570 ((!LegalOperations && !VT.isVector() &&
5571 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005572 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005573 bool DoXform = true;
5574 SmallVector<SDNode*, 4> SetCCs;
5575 if (!N0.hasOneUse())
5576 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005577 if (VT.isVector())
5578 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005579 if (DoXform) {
5580 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005581 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005582 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005583 LN0->getBasePtr(), N0.getValueType(),
5584 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005585 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005586 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005587 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005588 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005589 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005590 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005591 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005592 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005593 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005594
Ahmed Bougachae892d132015-02-05 18:31:02 +00005595 // fold (sext (load x)) to multiple smaller sextloads.
5596 // Only on illegal but splittable vectors.
5597 if (SDValue ExtLoad = CombineExtLoad(N))
5598 return ExtLoad;
5599
Chris Lattner7dac1082005-12-14 19:05:06 +00005600 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5601 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005602 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5603 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005604 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005605 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005606 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005607 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005608 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005609 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005610 LN0->getBasePtr(), MemVT,
5611 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005612 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005613 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005614 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005615 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005616 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005617 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005618 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005619 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005620
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005621 // fold (sext (and/or/xor (load x), cst)) ->
5622 // (and/or/xor (sextload x), (sext cst))
5623 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5624 N0.getOpcode() == ISD::XOR) &&
5625 isa<LoadSDNode>(N0.getOperand(0)) &&
5626 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005627 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005628 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5629 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005630 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005631 bool DoXform = true;
5632 SmallVector<SDNode*, 4> SetCCs;
5633 if (!N0.hasOneUse())
5634 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5635 SetCCs, TLI);
5636 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005637 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005638 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005639 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005640 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005641 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5642 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005643 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005644 ExtLoad, DAG.getConstant(Mask, VT));
5645 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005646 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005647 N0.getOperand(0).getValueType(), ExtLoad);
5648 CombineTo(N, And);
5649 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005650 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005651 ISD::SIGN_EXTEND);
5652 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5653 }
5654 }
5655 }
5656
Chris Lattner65786b02007-04-11 05:32:27 +00005657 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005658 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005659 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005660 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005661 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005662 TLI.getBooleanContents(N0VT) ==
5663 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005664 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5665 // of the same size as the compared operands. Only optimize sext(setcc())
5666 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005667 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005668
5669 // We know that the # elements of the results is the same as the
5670 // # elements of the compare (and the # elements of the compare result
5671 // for that matter). Check to see that they are the same size. If so,
5672 // we know that the element size of the sext'd result matches the
5673 // element size of the compare operands.
5674 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005675 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005676 N0.getOperand(1),
5677 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005678
Dan Gohmane82c25e2010-04-30 17:19:19 +00005679 // If the desired elements are smaller or larger than the source
5680 // elements we can use a matching integer vector type and then
5681 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005682 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005683 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005684 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005685 N0.getOperand(0), N0.getOperand(1),
5686 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005687 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005688 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005689 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005690
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005691 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005692 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005693 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005694 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005695 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005696 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005697 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005698 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005699 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005700
5701 if (!VT.isVector()) {
5702 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5703 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5704 SDLoc DL(N);
5705 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Hal Finkel98085952014-10-06 20:19:47 +00005706 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005707 N0.getOperand(0), N0.getOperand(1), CC);
Hal Finkel98085952014-10-06 20:19:47 +00005708 return DAG.getSelect(DL, VT, SetCC,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005709 NegOne, DAG.getConstant(0, VT));
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005710 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005711 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005712 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005713
Dan Gohman3eb10f72008-04-28 16:58:24 +00005714 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005715 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005716 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005717 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005718
Evan Chengf1005572010-04-28 07:10:39 +00005719 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005720}
5721
Rafael Espindola8f62b322012-04-09 16:06:03 +00005722// isTruncateOf - If N is a truncate of some other value, return true, record
5723// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5724// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005725// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005726static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5727 APInt &KnownZero) {
5728 APInt KnownOne;
5729 if (N->getOpcode() == ISD::TRUNCATE) {
5730 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005731 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005732 return true;
5733 }
5734
5735 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5736 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5737 return false;
5738
5739 SDValue Op0 = N->getOperand(0);
5740 SDValue Op1 = N->getOperand(1);
5741 assert(Op0.getValueType() == Op1.getValueType());
5742
5743 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5744 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005745 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005746 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005747 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005748 Op = Op0;
5749 else
5750 return false;
5751
Jay Foada0653a32014-05-14 21:14:37 +00005752 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005753
5754 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5755 return false;
5756
5757 return true;
5758}
5759
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005760SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5761 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005762 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005763
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005764 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5765 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005766 return SDValue(Res, 0);
5767
Nate Begeman21158fc2005-09-01 00:19:25 +00005768 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005769 // fold (zext (aext x)) -> (zext x)
5770 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005771 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005772 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005773
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005774 // fold (zext (truncate x)) -> (zext x) or
5775 // (zext (truncate x)) -> (truncate x)
5776 // This is valid when the truncated bits of x are already zero.
5777 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005778 SDValue Op;
5779 APInt KnownZero;
5780 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5781 APInt TruncatedBits =
5782 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5783 APInt(Op.getValueSizeInBits(), 0) :
5784 APInt::getBitsSet(Op.getValueSizeInBits(),
5785 N0.getValueSizeInBits(),
5786 std::min(Op.getValueSizeInBits(),
5787 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005788 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005789 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005790 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005791 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005792 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005793
5794 return Op;
5795 }
5796 }
5797
Evan Cheng464dc9b2007-03-22 01:54:19 +00005798 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5799 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005800 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005801 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5802 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005803 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5804 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005805 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005806 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005807 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005808 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005809 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005810 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005811 }
5812
Chris Lattnera31f0a62006-09-21 06:00:20 +00005813 // fold (zext (truncate x)) -> (and x, mask)
5814 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005815 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005816
5817 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5818 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5819 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5820 if (NarrowLoad.getNode()) {
5821 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5822 if (NarrowLoad.getNode() != N0.getNode()) {
5823 CombineTo(N0.getNode(), NarrowLoad);
5824 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005825 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005826 }
5827 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5828 }
5829
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005830 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005831 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005832 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005833 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005834 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005835 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005836 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005837 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005838 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005839 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005840 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005841
Dan Gohmanad3e5492009-04-08 00:15:30 +00005842 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5843 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005844 if (N0.getOpcode() == ISD::AND &&
5845 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005846 N0.getOperand(1).getOpcode() == ISD::Constant &&
5847 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5848 N0.getValueType()) ||
5849 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005850 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005851 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005852 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005853 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005854 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005855 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005856 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005857 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005858 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005859 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005860 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005861
Evan Chengbce7c472005-12-14 02:19:23 +00005862 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005863 // Only generate vector extloads when 1) they're legal, and 2) they are
5864 // deemed desirable by the target.
5865 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5866 ((!LegalOperations && !VT.isVector() &&
5867 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005868 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005869 bool DoXform = true;
5870 SmallVector<SDNode*, 4> SetCCs;
5871 if (!N0.hasOneUse())
5872 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005873 if (VT.isVector())
5874 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005875 if (DoXform) {
5876 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005877 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005878 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005879 LN0->getBasePtr(), N0.getValueType(),
5880 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005881 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005882 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005883 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005884 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005885
Andrew Trickef9de2a2013-05-25 02:42:55 +00005886 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005887 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005888 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005889 }
Evan Chengbce7c472005-12-14 02:19:23 +00005890 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005891
Ahmed Bougachae892d132015-02-05 18:31:02 +00005892 // fold (zext (load x)) to multiple smaller zextloads.
5893 // Only on illegal but splittable vectors.
5894 if (SDValue ExtLoad = CombineExtLoad(N))
5895 return ExtLoad;
5896
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005897 // fold (zext (and/or/xor (load x), cst)) ->
5898 // (and/or/xor (zextload x), (zext cst))
5899 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5900 N0.getOpcode() == ISD::XOR) &&
5901 isa<LoadSDNode>(N0.getOperand(0)) &&
5902 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005903 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005904 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5905 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005906 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005907 bool DoXform = true;
5908 SmallVector<SDNode*, 4> SetCCs;
5909 if (!N0.hasOneUse())
5910 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5911 SetCCs, TLI);
5912 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005913 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005914 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005915 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005916 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005917 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5918 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005919 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005920 ExtLoad, DAG.getConstant(Mask, VT));
5921 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005922 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005923 N0.getOperand(0).getValueType(), ExtLoad);
5924 CombineTo(N, And);
5925 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005926 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005927 ISD::ZERO_EXTEND);
5928 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5929 }
5930 }
5931 }
5932
Chris Lattner7dac1082005-12-14 19:05:06 +00005933 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5934 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005935 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5936 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005937 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005938 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005939 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005940 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005941 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005942 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005943 LN0->getBasePtr(), MemVT,
5944 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005945 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005946 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005947 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005948 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005949 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005950 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005951 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005952 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005953
Chris Lattner65786b02007-04-11 05:32:27 +00005954 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005955 if (!LegalOperations && VT.isVector() &&
5956 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005957 EVT N0VT = N0.getOperand(0).getValueType();
5958 if (getSetCCResultType(N0VT) == N0.getValueType())
5959 return SDValue();
5960
Evan Chengabd0ad52010-05-19 01:08:17 +00005961 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5962 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005963 EVT EltVT = VT.getVectorElementType();
5964 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5965 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005966 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005967 // We know that the # elements of the results is the same as the
5968 // # elements of the compare (and the # elements of the compare result
5969 // for that matter). Check to see that they are the same size. If so,
5970 // we know that the element size of the sext'd result matches the
5971 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005972 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5973 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005974 N0.getOperand(1),
5975 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005976 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005977 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005978
5979 // If the desired elements are smaller or larger than the source
5980 // elements we can use a matching integer vector type and then
5981 // truncate/sign extend
5982 EVT MatchingElementType =
5983 EVT::getIntegerVT(*DAG.getContext(),
5984 N0VT.getScalarType().getSizeInBits());
5985 EVT MatchingVectorType =
5986 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5987 N0VT.getVectorNumElements());
5988 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005989 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005990 N0.getOperand(1),
5991 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005992 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5993 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005994 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005995 }
5996
5997 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005998 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005999 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00006000 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006001 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006002 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006003 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006004
Evan Cheng852c4862009-12-15 03:00:32 +00006005 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00006006 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00006007 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00006008 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6009 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006010 SDValue ShAmt = N0.getOperand(1);
6011 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00006012 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006013 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00006014 // If the original shl may be shifting out bits, do not perform this
6015 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00006016 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6017 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6018 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00006019 return SDValue();
6020 }
Chris Lattnere95d1952011-02-13 19:09:16 +00006021
Andrew Trickef9de2a2013-05-25 02:42:55 +00006022 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006023
6024 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00006025 if (VT.getSizeInBits() >= 256)
6026 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006027
Chris Lattnere95d1952011-02-13 19:09:16 +00006028 return DAG.getNode(N0.getOpcode(), DL, VT,
6029 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6030 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00006031 }
6032
Evan Chengf1005572010-04-28 07:10:39 +00006033 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006034}
6035
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006036SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6037 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006038 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006039
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00006040 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6041 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00006042 return SDValue(Res, 0);
6043
Chris Lattner812646a2006-05-05 05:58:59 +00006044 // fold (aext (aext x)) -> (aext x)
6045 // fold (aext (zext x)) -> (zext x)
6046 // fold (aext (sext x)) -> (sext x)
6047 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6048 N0.getOpcode() == ISD::ZERO_EXTEND ||
6049 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006050 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006051
Evan Cheng464dc9b2007-03-22 01:54:19 +00006052 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6053 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6054 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006055 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6056 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006057 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6058 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006059 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006060 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006061 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006062 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00006063 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00006064 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006065 }
6066
Chris Lattner8746e2c2006-09-20 06:29:17 +00006067 // fold (aext (truncate x))
6068 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006069 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006070 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006071 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00006072 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006073 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6074 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006075 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006076
Dan Gohmanad3e5492009-04-08 00:15:30 +00006077 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6078 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00006079 if (N0.getOpcode() == ISD::AND &&
6080 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00006081 N0.getOperand(1).getOpcode() == ISD::Constant &&
6082 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6083 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006084 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006085 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006086 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00006087 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006088 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00006089 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00006090 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00006091 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006092 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00006093 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00006094 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006095
Chris Lattner812646a2006-05-05 05:58:59 +00006096 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00006097 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00006098 // on vectors in one instruction. We only perform this transformation on
6099 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00006100 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00006101 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006102 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00006103 bool DoXform = true;
6104 SmallVector<SDNode*, 4> SetCCs;
6105 if (!N0.hasOneUse())
6106 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6107 if (DoXform) {
6108 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006109 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00006110 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006111 LN0->getBasePtr(), N0.getValueType(),
6112 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00006113 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006114 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00006115 N0.getValueType(), ExtLoad);
6116 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006117 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006118 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00006119 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6120 }
Chris Lattner812646a2006-05-05 05:58:59 +00006121 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006122
Chris Lattner812646a2006-05-05 05:58:59 +00006123 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6124 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6125 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006126 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006127 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00006128 N0.hasOneUse()) {
6129 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006130 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00006131 EVT MemVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006132 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006133 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6134 VT, LN0->getChain(), LN0->getBasePtr(),
6135 MemVT, LN0->getMemOperand());
6136 CombineTo(N, ExtLoad);
6137 CombineTo(N0.getNode(),
6138 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6139 N0.getValueType(), ExtLoad),
6140 ExtLoad.getValue(1));
6141 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6142 }
Chris Lattner812646a2006-05-05 05:58:59 +00006143 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006144
Chris Lattner65786b02007-04-11 05:32:27 +00006145 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00006146 // For vectors:
6147 // aext(setcc) -> vsetcc
6148 // aext(setcc) -> truncate(vsetcc)
6149 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00006150 // Only do this before legalize for now.
6151 if (VT.isVector() && !LegalOperations) {
6152 EVT N0VT = N0.getOperand(0).getValueType();
6153 // We know that the # elements of the results is the same as the
6154 // # elements of the compare (and the # elements of the compare result
6155 // for that matter). Check to see that they are the same size. If so,
6156 // we know that the element size of the sext'd result matches the
6157 // element size of the compare operands.
6158 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006159 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006160 N0.getOperand(1),
6161 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00006162 // If the desired elements are smaller or larger than the source
6163 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00006164 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00006165 else {
Hao Liuc636d152014-04-22 09:57:06 +00006166 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006167 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006168 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006169 N0.getOperand(1),
6170 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00006171 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00006172 }
6173 }
6174
6175 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00006176 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006177 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006178 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00006179 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006180 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00006181 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006182 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006183
Evan Chengf1005572010-04-28 07:10:39 +00006184 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00006185}
6186
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006187/// See if the specified operand can be simplified with the knowledge that only
6188/// the bits specified by Mask are used. If so, return the simpler operand,
6189/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006190SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00006191 switch (V.getOpcode()) {
6192 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00006193 case ISD::Constant: {
6194 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00006195 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00006196 const APInt &CVal = CV->getAPIntValue();
6197 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00006198 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00006199 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00006200 break;
6201 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006202 case ISD::OR:
6203 case ISD::XOR:
6204 // If the LHS or RHS don't contribute bits to the or, drop them.
6205 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6206 return V.getOperand(1);
6207 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6208 return V.getOperand(0);
6209 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00006210 case ISD::SRL:
6211 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006212 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00006213 break;
6214 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6215 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00006216 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006217
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00006218 // Watch out for shift count overflow though.
6219 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00006220 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006221 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006222 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006223 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00006224 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00006225 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006226 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006227 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00006228}
6229
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006230/// If the result of a wider load is shifted to right of N bits and then
6231/// truncated to a narrower type and where N is a multiple of number of bits of
6232/// the narrower type, transform it to a narrower load from address + N / num of
6233/// bits of new type. If the result is to be extended, also fold the extension
6234/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006235SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006236 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00006237
Evan Cheng464dc9b2007-03-22 01:54:19 +00006238 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006239 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006240 EVT VT = N->getValueType(0);
6241 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006242
Dan Gohman550c9af2008-08-14 20:04:46 +00006243 // This transformation isn't valid for vector loads.
6244 if (VT.isVector())
6245 return SDValue();
6246
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006247 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00006248 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00006249 if (Opc == ISD::SIGN_EXTEND_INREG) {
6250 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006251 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00006252 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00006253 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00006254 ExtType = ISD::ZEXTLOAD;
6255 N0 = SDValue(N, 0);
6256 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6257 if (!N01) return SDValue();
6258 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6259 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00006260 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006261 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
Richard Osborne272e0842011-01-31 17:41:44 +00006262 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006263
Owen Anderson53aa7a92009-08-10 22:56:29 +00006264 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006265
Chris Lattner9a499e92010-12-22 08:01:44 +00006266 // Do not generate loads of non-round integer types since these can
6267 // be expensive (and would be wrong if the type is not byte sized).
6268 if (!ExtVT.isRound())
6269 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006270
Evan Cheng464dc9b2007-03-22 01:54:19 +00006271 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00006272 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006273 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00006274 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006275 // Is the shift amount a multiple of size of VT?
6276 if ((ShAmt & (EVTBits-1)) == 0) {
6277 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00006278 // Is the load width a multiple of size of VT?
6279 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006280 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006281 }
Wesley Peck527da1b2010-11-23 03:31:01 +00006282
Chris Lattnercafc1e62010-12-22 08:02:57 +00006283 // At this point, we must have a load or else we can't do the transform.
6284 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006285
Chandler Carruthb27041c2012-12-11 00:36:57 +00006286 // Because a SRL must be assumed to *need* to zero-extend the high bits
6287 // (as opposed to anyext the high bits), we can't combine the zextload
6288 // lowering of SRL and an sextload.
6289 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6290 return SDValue();
6291
Chris Lattnera2050552010-10-01 05:36:09 +00006292 // If the shift amount is larger than the input type then we're not
6293 // accessing any of the loaded bytes. If the load was a zextload/extload
6294 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00006295 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00006296 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006297 }
6298 }
6299
Dan Gohman68fb0042010-11-03 01:47:46 +00006300 // If the load is shifted left (and the result isn't shifted back right),
6301 // we can fold the truncate through the shift.
6302 unsigned ShLeftAmt = 0;
6303 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00006304 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006305 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6306 ShLeftAmt = N01->getZExtValue();
6307 N0 = N0.getOperand(0);
6308 }
6309 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00006310
Chris Lattner222374d2010-12-22 07:36:50 +00006311 // If we haven't found a load, we can't narrow it. Don't transform one with
6312 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00006313 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6314 return SDValue();
6315
6316 // Don't change the width of a volatile load.
6317 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6318 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00006319 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006320
Chris Lattner9a499e92010-12-22 08:01:44 +00006321 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00006322 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00006323 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006324
Bill Schmidtd006c692013-01-14 22:04:38 +00006325 // For the transform to be legal, the load must produce only two values
6326 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00006327 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00006328 // transformation is not equivalent, and the downstream logic to replace
6329 // uses gets things wrong.
6330 if (LN0->getNumValues() > 2)
6331 return SDValue();
6332
Benjamin Kramerc7332b22013-07-06 14:05:09 +00006333 // If the load that we're shrinking is an extload and we're not just
6334 // discarding the extension we can't simply shrink the load. Bail.
6335 // TODO: It would be possible to merge the extensions in some cases.
6336 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6337 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6338 return SDValue();
6339
Matt Arsenault810cb622014-12-12 00:00:24 +00006340 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6341 return SDValue();
6342
Chris Lattner222374d2010-12-22 07:36:50 +00006343 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006344
Evan Cheng4c6f9172012-06-26 01:19:33 +00006345 if (PtrType == MVT::Untyped || PtrType.isExtended())
6346 // It's not possible to generate a constant of extended or untyped type.
6347 return SDValue();
6348
Chris Lattner222374d2010-12-22 07:36:50 +00006349 // For big endian targets, we need to adjust the offset to the pointer to
6350 // load the correct bytes.
6351 if (TLI.isBigEndian()) {
6352 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6353 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6354 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006355 }
6356
Chris Lattner222374d2010-12-22 07:36:50 +00006357 uint64_t PtrOff = ShAmt / 8;
6358 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006359 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00006360 PtrType, LN0->getBasePtr(),
6361 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006362 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00006363
Chris Lattner9a499e92010-12-22 08:01:44 +00006364 SDValue Load;
6365 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006366 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006367 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006368 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00006369 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00006370 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006371 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006372 LN0->getPointerInfo().getWithOffset(PtrOff),
6373 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00006374 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00006375
6376 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006377 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00006378 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00006379
6380 // Shift the result left, if we've swallowed a left shift.
6381 SDValue Result = Load;
6382 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00006383 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00006384 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6385 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00006386 // If the shift amount is as large as the result size (but, presumably,
6387 // no larger than the source) then the useful bits of the result are
6388 // zero; we can't simply return the shortened shift, because the result
6389 // of that operation is undefined.
6390 if (ShLeftAmt >= VT.getSizeInBits())
6391 Result = DAG.getConstant(0, VT);
6392 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006393 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00006394 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00006395 }
6396
6397 // Return the new loaded value.
6398 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006399}
6400
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006401SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6402 SDValue N0 = N->getOperand(0);
6403 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006404 EVT VT = N->getValueType(0);
6405 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00006406 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006407 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006408
Nate Begeman21158fc2005-09-01 00:19:25 +00006409 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00006410 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006411 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006412
Chris Lattner2a4d7b82006-05-06 22:43:44 +00006413 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00006414 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00006415 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006416
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006417 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6418 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006419 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006420 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006421 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00006422
Dan Gohman345d63c2008-07-31 00:50:31 +00006423 // fold (sext_in_reg (sext x)) -> (sext x)
6424 // fold (sext_in_reg (aext x)) -> (sext x)
6425 // if x is small enough.
6426 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6427 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00006428 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6429 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006430 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00006431 }
6432
Chris Lattner9ad59152007-04-17 19:03:21 +00006433 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00006434 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006435 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006436
Chris Lattner9ad59152007-04-17 19:03:21 +00006437 // fold operands of sext_in_reg based on knowledge that the top bits are not
6438 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006439 if (SimplifyDemandedBits(SDValue(N, 0)))
6440 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006441
Evan Cheng464dc9b2007-03-22 01:54:19 +00006442 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6443 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006444 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006445 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00006446 return NarrowLoad;
6447
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006448 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006449 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00006450 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6451 if (N0.getOpcode() == ISD::SRL) {
6452 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00006453 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006454 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00006455 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00006456 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00006457 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006458 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006459 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00006460 }
6461 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006462
Nate Begeman02b23c62005-10-13 03:11:28 +00006463 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00006464 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006465 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006466 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006467 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006468 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006469 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006470 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006471 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006472 LN0->getBasePtr(), EVT,
6473 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006474 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006475 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006476 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006477 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006478 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006479 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00006480 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006481 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006482 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006483 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006484 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006485 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006486 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006487 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006488 LN0->getBasePtr(), EVT,
6489 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006490 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006491 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006492 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006493 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00006494
6495 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6496 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6497 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6498 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006499 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006500 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006501 BSwap, N1);
6502 }
6503
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006504 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6505 // into a build_vector.
6506 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6507 SmallVector<SDValue, 8> Elts;
6508 unsigned NumElts = N0->getNumOperands();
6509 unsigned ShAmt = VTBits - EVTBits;
6510
6511 for (unsigned i = 0; i != NumElts; ++i) {
6512 SDValue Op = N0->getOperand(i);
6513 if (Op->getOpcode() == ISD::UNDEF) {
6514 Elts.push_back(Op);
6515 continue;
6516 }
6517
6518 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006519 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6520 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006521 Op.getValueType()));
6522 }
6523
Craig Topper48d114b2014-04-26 18:35:24 +00006524 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006525 }
6526
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006527 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006528}
6529
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006530SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6531 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006532 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006533 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006534
6535 // noop truncate
6536 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006537 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006538 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006539 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006540 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006541 // fold (truncate (truncate x)) -> (truncate x)
6542 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006543 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006544 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006545 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6546 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006547 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006548 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006549 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006550 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006551 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006552 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006553 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006554 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006555 // if the source and dest are the same type, we can drop both the extend
6556 // and the truncate.
6557 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006558 }
Evan Chengd63baea2007-03-21 20:14:05 +00006559
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006560 // Fold extract-and-trunc into a narrow extract. For example:
6561 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6562 // i32 y = TRUNCATE(i64 x)
6563 // -- becomes --
6564 // v16i8 b = BITCAST (v2i64 val)
6565 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6566 //
6567 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006568 // creates this pattern) and before operation legalization after which
6569 // we need to be more careful about the vector instructions that we generate.
6570 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006571 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006572
6573 EVT VecTy = N0.getOperand(0).getValueType();
6574 EVT ExTy = N0.getValueType();
6575 EVT TrTy = N->getValueType(0);
6576
6577 unsigned NumElem = VecTy.getVectorNumElements();
6578 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6579
6580 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6581 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6582
6583 SDValue EltNo = N0->getOperand(1);
6584 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6585 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006586 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006587 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6588
Andrew Trickef9de2a2013-05-25 02:42:55 +00006589 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006590 NVT, N0.getOperand(0));
6591
6592 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006593 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006594 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006595 }
6596 }
6597
Matt Arsenault3332b702014-07-10 18:21:04 +00006598 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6599 if (N0.getOpcode() == ISD::SELECT) {
6600 EVT SrcVT = N0.getValueType();
6601 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6602 TLI.isTruncateFree(SrcVT, VT)) {
6603 SDLoc SL(N0);
6604 SDValue Cond = N0.getOperand(0);
6605 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6606 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6607 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6608 }
6609 }
6610
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006611 // Fold a series of buildvector, bitcast, and truncate if possible.
6612 // For example fold
6613 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6614 // (2xi32 (buildvector x, y)).
6615 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6616 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6617 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6618 N0.getOperand(0).hasOneUse()) {
6619
6620 SDValue BuildVect = N0.getOperand(0);
6621 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6622 EVT TruncVecEltTy = VT.getVectorElementType();
6623
6624 // Check that the element types match.
6625 if (BuildVectEltTy == TruncVecEltTy) {
6626 // Now we only need to compute the offset of the truncated elements.
6627 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6628 unsigned TruncVecNumElts = VT.getVectorNumElements();
6629 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6630
6631 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6632 "Invalid number of elements");
6633
6634 SmallVector<SDValue, 8> Opnds;
6635 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6636 Opnds.push_back(BuildVect.getOperand(i));
6637
Craig Topper48d114b2014-04-26 18:35:24 +00006638 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006639 }
6640 }
6641
Chris Lattner5e6fe052007-10-13 06:35:54 +00006642 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006643 // only the low bits are being used.
6644 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006645 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006646 // may have different active low bits.
6647 if (!VT.isVector()) {
6648 SDValue Shorter =
6649 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6650 VT.getSizeInBits()));
6651 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006652 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006653 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006654 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006655 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006656 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6657 SDValue Reduced = ReduceLoadWidth(N);
6658 if (Reduced.getNode())
6659 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006660 // Handle the case where the load remains an extending load even
6661 // after truncation.
6662 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6663 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6664 if (!LN0->isVolatile() &&
6665 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6666 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6667 VT, LN0->getChain(), LN0->getBasePtr(),
6668 LN0->getMemoryVT(),
6669 LN0->getMemOperand());
6670 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6671 return NewLoad;
6672 }
6673 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006674 }
Michael Liao3ac82012012-10-17 23:45:54 +00006675 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6676 // where ... are all 'undef'.
6677 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6678 SmallVector<EVT, 8> VTs;
6679 SDValue V;
6680 unsigned Idx = 0;
6681 unsigned NumDefs = 0;
6682
6683 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6684 SDValue X = N0.getOperand(i);
6685 if (X.getOpcode() != ISD::UNDEF) {
6686 V = X;
6687 Idx = i;
6688 NumDefs++;
6689 }
6690 // Stop if more than one members are non-undef.
6691 if (NumDefs > 1)
6692 break;
6693 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6694 VT.getVectorElementType(),
6695 X.getValueType().getVectorNumElements()));
6696 }
6697
6698 if (NumDefs == 0)
6699 return DAG.getUNDEF(VT);
6700
6701 if (NumDefs == 1) {
6702 assert(V.getNode() && "The single defined operand is empty!");
6703 SmallVector<SDValue, 8> Opnds;
6704 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6705 if (i != Idx) {
6706 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6707 continue;
6708 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006709 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006710 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006711 Opnds.push_back(NV);
6712 }
Craig Topper48d114b2014-04-26 18:35:24 +00006713 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006714 }
6715 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006716
6717 // Simplify the operands using demanded-bits information.
6718 if (!VT.isVector() &&
6719 SimplifyDemandedBits(SDValue(N, 0)))
6720 return SDValue(N, 0);
6721
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006722 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006723}
6724
Evan Chengb980f6f2008-05-12 23:04:07 +00006725static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006726 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006727 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006728 return Elt.getNode();
6729 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006730}
6731
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006732/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006733/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006734SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006735 assert(N->getOpcode() == ISD::BUILD_PAIR);
6736
Nate Begeman624690c2009-06-05 21:37:30 +00006737 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6738 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006739 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006740 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006741 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006742 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006743
Evan Chengb980f6f2008-05-12 23:04:07 +00006744 if (ISD::isNON_EXTLoad(LD2) &&
6745 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006746 // If both are volatile this would reduce the number of volatile loads.
6747 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006748 !LD1->isVolatile() &&
6749 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006750 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006751 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006752 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006753 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006754
Duncan Sands8651e9c2008-06-13 19:07:40 +00006755 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006756 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006757 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006758 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006759 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006760 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006761
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006762 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006763}
6764
Wesley Peck527da1b2010-11-23 03:31:01 +00006765SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006766 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006767 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006768
Dan Gohmana8665142007-06-25 16:23:39 +00006769 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6770 // Only do this before legalize, since afterward the target may be depending
6771 // on the bitconvert.
6772 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006773 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006774 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006775 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006776 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006777
Owen Anderson53aa7a92009-08-10 22:56:29 +00006778 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006779 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006780 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006781 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006782 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006783 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006784
Dan Gohman921ddd62008-09-05 01:58:21 +00006785 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006786 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Chandler Carruthb65d61a2015-02-10 02:25:56 +00006787 // If we can't allow illegal operations, we need to check that this is just
6788 // a fp -> int or int -> conversion and that the resulting operation will
6789 // be legal.
6790 if (!LegalOperations ||
6791 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6792 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6793 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6794 TLI.isOperationLegal(ISD::Constant, VT)))
6795 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Chris Lattnera1874602005-12-23 05:30:37 +00006796 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006797
Bill Wendling4e0a6152009-01-30 22:44:24 +00006798 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006799 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006800 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006801 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006802
Chris Lattner54560f62005-12-23 05:44:41 +00006803 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006804 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006805 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006806 // Do not change the width of a volatile load.
6807 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006808 // Do not remove the cast if the types differ in endian layout.
6809 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6810 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006811 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6812 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006813 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006814 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006815 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006816 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006817
Evan Chenga4cf58a2007-05-07 21:27:48 +00006818 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006819 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006820 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006821 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006822 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006823 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006824 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006825 return Load;
6826 }
Chris Lattner54560f62005-12-23 05:44:41 +00006827 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006828
Bill Wendling4e0a6152009-01-30 22:44:24 +00006829 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6830 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006831 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006832 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6833 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006834 N0.getNode()->hasOneUse() && VT.isInteger() &&
6835 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006836 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006837 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006838 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006839
Duncan Sands13237ac2008-06-06 12:08:01 +00006840 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006841 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006842 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006843 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006844 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006845 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006846 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006847 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006848
Bill Wendling4e0a6152009-01-30 22:44:24 +00006849 // fold (bitconvert (fcopysign cst, x)) ->
6850 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6851 // Note that we don't handle (copysign x, cst) because this can always be
6852 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006853 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006854 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006855 VT.isInteger() && !VT.isVector()) {
6856 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006857 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006858 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006859 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006860 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006861 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006862
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006863 // If X has a different width than the result/lhs, sext it or truncate it.
6864 unsigned VTWidth = VT.getSizeInBits();
6865 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006866 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006867 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006868 } else if (OrigXWidth > VTWidth) {
6869 // To get the sign bit in the right place, we have to shift it right
6870 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006871 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006872 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006873 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006874 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006875 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006876 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006877 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006878
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006879 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006880 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006881 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006882 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006883
Andrew Trickef9de2a2013-05-25 02:42:55 +00006884 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006885 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006886 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006887 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006888 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006889
Andrew Trickef9de2a2013-05-25 02:42:55 +00006890 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006891 }
Chris Lattner888560d2008-01-27 17:42:27 +00006892 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006893
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006894 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006895 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006896 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6897 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006898 return CombineLD;
6899 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006900
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006901 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006902}
6903
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006904SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006905 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006906 return CombineConsecutiveLoads(N, VT);
6907}
6908
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006909/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6910/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006911SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006912ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006913 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006914
Chris Lattnere4e64b62006-04-02 02:53:43 +00006915 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006916 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006917
Duncan Sands13237ac2008-06-06 12:08:01 +00006918 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6919 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006920
Chris Lattnere4e64b62006-04-02 02:53:43 +00006921 // If this is a conversion of N elements of one type to N elements of another
6922 // type, convert each element. This handles FP<->INT cases.
6923 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006924 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6925 BV->getValueType(0).getVectorNumElements());
6926
6927 // Due to the FP element handling below calling this routine recursively,
6928 // we can end up with a scalar-to-vector node here.
6929 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006930 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6931 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006932 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006933
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006934 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006935 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006936 SDValue Op = BV->getOperand(i);
6937 // If the vector element type is not legal, the BUILD_VECTOR operands
6938 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006939 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006940 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6941 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006942 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006943 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006944 }
Craig Topper48d114b2014-04-26 18:35:24 +00006945 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006946 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006947
Chris Lattnere4e64b62006-04-02 02:53:43 +00006948 // Otherwise, we're growing or shrinking the elements. To avoid having to
6949 // handle annoying details of growing/shrinking FP values, we convert them to
6950 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006951 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006952 // Convert the input float vector to a int vector where the elements are the
6953 // same sizes.
Owen Anderson117c9e82009-08-12 00:36:31 +00006954 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006955 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006956 SrcEltVT = IntVT;
6957 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006958
Chris Lattnere4e64b62006-04-02 02:53:43 +00006959 // Now we know the input is an integer vector. If the output is a FP type,
6960 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006961 if (DstEltVT.isFloatingPoint()) {
Owen Anderson117c9e82009-08-12 00:36:31 +00006962 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006963 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006964
Chris Lattnere4e64b62006-04-02 02:53:43 +00006965 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006966 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006967 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006968
Chris Lattnere4e64b62006-04-02 02:53:43 +00006969 // Okay, we know the src/dst types are both integers of differing types.
6970 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006971 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006972 if (SrcBitSize < DstBitSize) {
6973 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006974
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006975 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006976 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006977 i += NumInputsPerOutput) {
6978 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006979 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006980 bool EltIsUndef = true;
6981 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6982 // Shift the previously computed bits over.
6983 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006984 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006985 if (Op.getOpcode() == ISD::UNDEF) continue;
6986 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006987
Jay Foad583abbc2010-12-07 08:25:19 +00006988 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006989 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006990 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006991
Chris Lattnere4e64b62006-04-02 02:53:43 +00006992 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006993 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006994 else
6995 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6996 }
6997
Owen Anderson117c9e82009-08-12 00:36:31 +00006998 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006999 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007000 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007001
Chris Lattnere4e64b62006-04-02 02:53:43 +00007002 // Finally, this must be the case where we are shrinking elements: each input
7003 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00007004 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007005 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00007006 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7007 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007008 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007009
Dan Gohmana8665142007-06-25 16:23:39 +00007010 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007011 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00007012 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007013 continue;
7014 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007015
Jay Foad583abbc2010-12-07 08:25:19 +00007016 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7017 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007018
Chris Lattnere4e64b62006-04-02 02:53:43 +00007019 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00007020 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007021 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00007022 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00007023 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007024 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007025 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00007026 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007027 }
7028
7029 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00007030 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00007031 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7032 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007033
Craig Topper48d114b2014-04-26 18:35:24 +00007034 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007035}
7036
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007037// Attempt different variants of (fadd (fmul a, b), c) -> fma or fmad
7038static SDValue performFaddFmulCombines(unsigned FusedOpcode,
7039 bool Aggressive,
7040 SDNode *N,
7041 const TargetLowering &TLI,
7042 SelectionDAG &DAG) {
7043 SDValue N0 = N->getOperand(0);
7044 SDValue N1 = N->getOperand(1);
7045 EVT VT = N->getValueType(0);
7046
7047 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7048 if (N0.getOpcode() == ISD::FMUL &&
7049 (Aggressive || N0->hasOneUse())) {
7050 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7051 N0.getOperand(0), N0.getOperand(1), N1);
7052 }
7053
7054 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7055 // Note: Commutes FADD operands.
7056 if (N1.getOpcode() == ISD::FMUL &&
7057 (Aggressive || N1->hasOneUse())) {
7058 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7059 N1.getOperand(0), N1.getOperand(1), N0);
7060 }
7061
7062 // More folding opportunities when target permits.
7063 if (Aggressive) {
7064 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7065 if (N0.getOpcode() == ISD::FMA &&
7066 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7067 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7068 N0.getOperand(0), N0.getOperand(1),
7069 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7070 N0.getOperand(2).getOperand(0),
7071 N0.getOperand(2).getOperand(1),
7072 N1));
7073 }
7074
7075 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7076 if (N1->getOpcode() == ISD::FMA &&
7077 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7078 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7079 N1.getOperand(0), N1.getOperand(1),
7080 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7081 N1.getOperand(2).getOperand(0),
7082 N1.getOperand(2).getOperand(1),
7083 N0));
7084 }
7085 }
7086
7087 return SDValue();
7088}
7089
7090static SDValue performFsubFmulCombines(unsigned FusedOpcode,
7091 bool Aggressive,
7092 SDNode *N,
7093 const TargetLowering &TLI,
7094 SelectionDAG &DAG) {
7095 SDValue N0 = N->getOperand(0);
7096 SDValue N1 = N->getOperand(1);
7097 EVT VT = N->getValueType(0);
7098
7099 SDLoc SL(N);
7100
7101 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7102 if (N0.getOpcode() == ISD::FMUL &&
7103 (Aggressive || N0->hasOneUse())) {
7104 return DAG.getNode(FusedOpcode, SL, VT,
7105 N0.getOperand(0), N0.getOperand(1),
7106 DAG.getNode(ISD::FNEG, SL, VT, N1));
7107 }
7108
7109 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7110 // Note: Commutes FSUB operands.
7111 if (N1.getOpcode() == ISD::FMUL &&
7112 (Aggressive || N1->hasOneUse()))
7113 return DAG.getNode(FusedOpcode, SL, VT,
7114 DAG.getNode(ISD::FNEG, SL, VT,
7115 N1.getOperand(0)),
7116 N1.getOperand(1), N0);
7117
7118 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7119 if (N0.getOpcode() == ISD::FNEG &&
7120 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7121 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7122 SDValue N00 = N0.getOperand(0).getOperand(0);
7123 SDValue N01 = N0.getOperand(0).getOperand(1);
7124 return DAG.getNode(FusedOpcode, SL, VT,
7125 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7126 DAG.getNode(ISD::FNEG, SL, VT, N1));
7127 }
7128
7129 // More folding opportunities when target permits.
7130 if (Aggressive) {
7131 // fold (fsub (fma x, y, (fmul u, v)), z)
7132 // -> (fma x, y (fma u, v, (fneg z)))
7133 if (N0.getOpcode() == FusedOpcode &&
7134 N0.getOperand(2).getOpcode() == ISD::FMUL) {
7135 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7136 N0.getOperand(0), N0.getOperand(1),
7137 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7138 N0.getOperand(2).getOperand(0),
7139 N0.getOperand(2).getOperand(1),
7140 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7141 N1)));
7142 }
7143
7144 // fold (fsub x, (fma y, z, (fmul u, v)))
7145 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7146 if (N1.getOpcode() == FusedOpcode &&
7147 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7148 SDValue N20 = N1.getOperand(2).getOperand(0);
7149 SDValue N21 = N1.getOperand(2).getOperand(1);
7150 return DAG.getNode(FusedOpcode, SDLoc(N), VT,
7151 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7152 N1.getOperand(0)),
7153 N1.getOperand(1),
7154 DAG.getNode(FusedOpcode, SDLoc(N), VT,
7155 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7156 N20),
7157 N21, N0));
7158 }
7159 }
7160
7161 return SDValue();
7162}
7163
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007164SDValue DAGCombiner::visitFADD(SDNode *N) {
7165 SDValue N0 = N->getOperand(0);
7166 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00007167 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7168 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007169 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007170 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007171
Dan Gohmana8665142007-06-25 16:23:39 +00007172 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007173 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007174 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007175 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007176 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007177
Lang Hamesa33db652012-06-14 20:37:15 +00007178 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007179 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007180 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007181
Nate Begeman418c6e42005-10-18 00:28:13 +00007182 // canonicalize constant to RHS
7183 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007184 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007185
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007186 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007187 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007188 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007189 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007190 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007191
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007192 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007193 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007194 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007195 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007196 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007197
Sanjay Patel8170dea2014-09-08 17:32:19 +00007198 // If 'unsafe math' is enabled, fold lots of things.
7199 if (Options.UnsafeFPMath) {
7200 // No FP constant should be created after legalization as Instruction
7201 // Selection pass has a hard time dealing with FP constants.
7202 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007203
Sanjay Patel8170dea2014-09-08 17:32:19 +00007204 // fold (fadd A, 0) -> A
7205 if (N1CFP && N1CFP->getValueAPF().isZero())
7206 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007207
Sanjay Patel8170dea2014-09-08 17:32:19 +00007208 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7209 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7210 isa<ConstantFPSDNode>(N0.getOperand(1)))
7211 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7212 DAG.getNode(ISD::FADD, SDLoc(N), VT,
7213 N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007214
Sanjay Patel8170dea2014-09-08 17:32:19 +00007215 // If allowed, fold (fadd (fneg x), x) -> 0.0
7216 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7217 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007218
Sanjay Patel8170dea2014-09-08 17:32:19 +00007219 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7220 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7221 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007222
Sanjay Patel8170dea2014-09-08 17:32:19 +00007223 // We can fold chains of FADD's of the same value into multiplications.
7224 // This transform is not safe in general because we are reducing the number
7225 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00007226 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7227 if (N0.getOpcode() == ISD::FMUL) {
7228 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7229 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007230
Sanjay Patel8170dea2014-09-08 17:32:19 +00007231 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7232 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7233 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7234 SDValue(CFP01, 0),
7235 DAG.getConstantFP(1.0, VT));
7236 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7237 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007238
Sanjay Patel8170dea2014-09-08 17:32:19 +00007239 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7240 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7241 N1.getOperand(0) == N1.getOperand(1) &&
7242 N0.getOperand(0) == N1.getOperand(0)) {
7243 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7244 SDValue(CFP01, 0),
7245 DAG.getConstantFP(2.0, VT));
7246 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7247 N0.getOperand(0), NewCFP);
7248 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007249 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007250
Sanjay Patel8170dea2014-09-08 17:32:19 +00007251 if (N1.getOpcode() == ISD::FMUL) {
7252 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7253 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007254
Sanjay Patel8170dea2014-09-08 17:32:19 +00007255 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7256 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7257 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7258 SDValue(CFP11, 0),
7259 DAG.getConstantFP(1.0, VT));
7260 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7261 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007262
Sanjay Patel8170dea2014-09-08 17:32:19 +00007263 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7264 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7265 N0.getOperand(0) == N0.getOperand(1) &&
7266 N1.getOperand(0) == N0.getOperand(0)) {
7267 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7268 SDValue(CFP11, 0),
7269 DAG.getConstantFP(2.0, VT));
7270 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7271 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007272 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007273
Sanjay Patel8170dea2014-09-08 17:32:19 +00007274 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7275 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7276 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7277 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7278 (N0.getOperand(0) == N1))
7279 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7280 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007281 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007282
Sanjay Patel8170dea2014-09-08 17:32:19 +00007283 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7284 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7285 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7286 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7287 N1.getOperand(0) == N0)
7288 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7289 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007290 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007291
Sanjay Patel8170dea2014-09-08 17:32:19 +00007292 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7293 if (AllowNewConst &&
7294 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00007295 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007296 N1.getOperand(0) == N1.getOperand(1) &&
7297 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007298 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00007299 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007300 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00007301 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007302
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007303 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7304 // Assume if there is an fmad instruction that it should be aggressively
7305 // used.
7306 if (SDValue Fused = performFaddFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7307 return Fused;
7308 }
7309
Lang Hames39fb1d02012-06-19 22:51:23 +00007310 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00007311 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00007312 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00007313 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00007314
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007315 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7316 // Don't form FMA if we are preferring FMAD.
7317 if (SDValue Fused
7318 = performFaddFmulCombines(ISD::FMA,
7319 TLI.enableAggressiveFMAFusion(VT),
7320 N, TLI, DAG)) {
7321 return Fused;
7322 }
7323 }
Olivier Sallenave04515322015-01-07 20:54:17 +00007324
Olivier Sallenave32509692015-01-13 15:06:36 +00007325 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7326 // to combine into FMA, arrange such nodes accordingly.
7327 if (TLI.isFPExtFree(VT)) {
7328
7329 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7330 if (N0.getOpcode() == ISD::FP_EXTEND) {
7331 SDValue N00 = N0.getOperand(0);
7332 if (N00.getOpcode() == ISD::FMUL)
7333 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7334 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7335 N00.getOperand(0)),
7336 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7337 N00.getOperand(1)), N1);
7338 }
7339
7340 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7341 // Note: Commutes FADD operands.
7342 if (N1.getOpcode() == ISD::FP_EXTEND) {
7343 SDValue N10 = N1.getOperand(0);
7344 if (N10.getOpcode() == ISD::FMUL)
7345 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7346 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7347 N10.getOperand(0)),
7348 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7349 N10.getOperand(1)), N0);
7350 }
7351 }
Olivier Sallenave04515322015-01-07 20:54:17 +00007352 }
7353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007354 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007355}
7356
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007357SDValue DAGCombiner::visitFSUB(SDNode *N) {
7358 SDValue N0 = N->getOperand(0);
7359 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00007360 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7361 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007362 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007363 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007364 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007365
Dan Gohmana8665142007-06-25 16:23:39 +00007366 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007367 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007368 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007369 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007370 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007371
Nate Begeman418c6e42005-10-18 00:28:13 +00007372 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007373 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007374 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00007375
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007376 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007377 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007378 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007379 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007380
Sanjay Patelae402a32014-08-27 20:57:52 +00007381 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007382 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00007383 // (fsub A, 0) -> A
7384 if (N1CFP && N1CFP->getValueAPF().isZero())
7385 return N0;
7386
7387 // (fsub 0, B) -> -B
7388 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00007389 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00007390 return GetNegatedExpression(N1, DAG, LegalOperations);
7391 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7392 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7393 }
7394
7395 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00007396 if (N0 == N1)
7397 return DAG.getConstantFP(0.0f, VT);
7398
Sanjay Patelae402a32014-08-27 20:57:52 +00007399 // (fsub x, (fadd x, y)) -> (fneg y)
7400 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00007401 if (N1.getOpcode() == ISD::FADD) {
7402 SDValue N10 = N1->getOperand(0);
7403 SDValue N11 = N1->getOperand(1);
7404
Sanjay Patel78614bf2014-08-28 15:53:16 +00007405 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007406 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00007407
Sanjay Patel78614bf2014-08-28 15:53:16 +00007408 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007409 return GetNegatedExpression(N10, DAG, LegalOperations);
7410 }
7411 }
7412
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007413 if (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)) {
7414 // Assume if there is an fmad instruction that it should be aggressively
7415 // used.
7416 if (SDValue Fused = performFsubFmulCombines(ISD::FMAD, true, N, TLI, DAG))
7417 return Fused;
7418 }
7419
Lang Hames39fb1d02012-06-19 22:51:23 +00007420 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00007421 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00007422 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00007423 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00007424
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007425 if (!TLI.isOperationLegal(ISD::FMAD, VT)) {
7426 // Don't form FMA if we are preferring FMAD.
Lang Hames39fb1d02012-06-19 22:51:23 +00007427
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007428 if (SDValue Fused
7429 = performFsubFmulCombines(ISD::FMA,
7430 TLI.enableAggressiveFMAFusion(VT),
7431 N, TLI, DAG)) {
7432 return Fused;
7433 }
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007434 }
Olivier Sallenave04515322015-01-07 20:54:17 +00007435
Olivier Sallenave32509692015-01-13 15:06:36 +00007436 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7437 // to combine into FMA, arrange such nodes accordingly.
7438 if (TLI.isFPExtFree(VT)) {
Olivier Sallenave32509692015-01-13 15:06:36 +00007439 // fold (fsub (fpext (fmul x, y)), z)
7440 // -> (fma (fpext x), (fpext y), (fneg z))
7441 if (N0.getOpcode() == ISD::FP_EXTEND) {
7442 SDValue N00 = N0.getOperand(0);
7443 if (N00.getOpcode() == ISD::FMUL)
7444 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7445 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7446 N00.getOperand(0)),
7447 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7448 N00.getOperand(1)),
7449 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7450 }
7451
7452 // fold (fsub x, (fpext (fmul y, z)))
7453 // -> (fma (fneg (fpext y)), (fpext z), x)
7454 // Note: Commutes FSUB operands.
7455 if (N1.getOpcode() == ISD::FP_EXTEND) {
7456 SDValue N10 = N1.getOperand(0);
7457 if (N10.getOpcode() == ISD::FMUL)
7458 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7459 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7460 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7461 VT, N10.getOperand(0))),
7462 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7463 N10.getOperand(1)),
7464 N0);
7465 }
7466
7467 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7468 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7469 if (N0.getOpcode() == ISD::FP_EXTEND) {
7470 SDValue N00 = N0.getOperand(0);
7471 if (N00.getOpcode() == ISD::FNEG) {
7472 SDValue N000 = N00.getOperand(0);
7473 if (N000.getOpcode() == ISD::FMUL) {
7474 return DAG.getNode(ISD::FMA, dl, VT,
7475 DAG.getNode(ISD::FNEG, dl, VT,
7476 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7477 VT, N000.getOperand(0))),
7478 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7479 N000.getOperand(1)),
7480 DAG.getNode(ISD::FNEG, dl, VT, N1));
7481 }
7482 }
7483 }
7484
7485 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7486 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7487 if (N0.getOpcode() == ISD::FNEG) {
7488 SDValue N00 = N0.getOperand(0);
7489 if (N00.getOpcode() == ISD::FP_EXTEND) {
7490 SDValue N000 = N00.getOperand(0);
7491 if (N000.getOpcode() == ISD::FMUL) {
7492 return DAG.getNode(ISD::FMA, dl, VT,
7493 DAG.getNode(ISD::FNEG, dl, VT,
7494 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7495 VT, N000.getOperand(0))),
7496 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7497 N000.getOperand(1)),
7498 DAG.getNode(ISD::FNEG, dl, VT, N1));
7499 }
7500 }
7501 }
7502 }
Lang Hames39fb1d02012-06-19 22:51:23 +00007503 }
7504
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007505 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007506}
7507
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007508SDValue DAGCombiner::visitFMUL(SDNode *N) {
7509 SDValue N0 = N->getOperand(0);
7510 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00007511 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7512 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007513 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007514 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007515
Dan Gohmana8665142007-06-25 16:23:39 +00007516 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007517 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007518 // This just handles C1 * C2 for vectors. Other vector folds are below.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007519 SDValue FoldedVOp = SimplifyVBinOp(N);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007520 if (FoldedVOp.getNode())
7521 return FoldedVOp;
7522 // Canonicalize vector constant to RHS.
7523 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7524 N1.getOpcode() != ISD::BUILD_VECTOR)
7525 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7526 if (BV0->isConstant())
7527 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
Dan Gohman80f9f072007-07-13 20:03:40 +00007528 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007529
Nate Begemanec48a1b2005-10-17 20:40:11 +00007530 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007531 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007532 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00007533
Nate Begemanec48a1b2005-10-17 20:40:11 +00007534 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00007535 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007536 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007537
Owen Andersonb5f167c2012-05-02 21:32:35 +00007538 // fold (fmul A, 1.0) -> A
7539 if (N1CFP && N1CFP->isExactlyValue(1.0))
7540 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00007541
Sanjay Patel394c3332014-09-08 20:16:42 +00007542 if (Options.UnsafeFPMath) {
7543 // fold (fmul A, 0) -> 0
7544 if (N1CFP && N1CFP->getValueAPF().isZero())
7545 return N1;
7546
7547 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007548 if (N0.getOpcode() == ISD::FMUL) {
7549 // Fold scalars or any vector constants (not just splats).
7550 // This fold is done in general by InstCombine, but extra fmul insts
7551 // may have been generated during lowering.
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007552 SDValue N00 = N0.getOperand(0);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007553 SDValue N01 = N0.getOperand(1);
7554 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007555 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007556 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00007557
7558 // Check 1: Make sure that the first operand of the inner multiply is NOT
7559 // a constant. Otherwise, we may induce infinite looping.
7560 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7561 // Check 2: Make sure that the second operand of the inner multiply and
7562 // the second operand of the outer multiply are constants.
7563 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7564 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7565 SDLoc SL(N);
7566 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7567 return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7568 }
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007569 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007570 }
7571
Sanjay Patel394c3332014-09-08 20:16:42 +00007572 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007573 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7574 // during an early run of DAGCombiner can prevent folding with fmuls
7575 // inserted during lowering.
7576 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7577 SDLoc SL(N);
7578 const SDValue Two = DAG.getConstantFP(2.0, VT);
7579 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7580 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7581 }
7582 }
7583
Nate Begemanec48a1b2005-10-17 20:40:11 +00007584 // fold (fmul X, 2.0) -> (fadd X, X)
7585 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007586 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007587
Dan Gohmanb7170912009-08-10 16:50:32 +00007588 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00007589 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00007590 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007591 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007592
Bill Wendling3dc5d242009-01-30 22:57:07 +00007593 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007594 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7595 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007596 // Both can be negated for free, check to see if at least one is cheaper
7597 // negated.
7598 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007599 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007600 GetNegatedExpression(N0, DAG, LegalOperations),
7601 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007602 }
7603 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007604
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007605 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007606}
7607
Owen Anderson41b06652012-05-02 22:17:40 +00007608SDValue DAGCombiner::visitFMA(SDNode *N) {
7609 SDValue N0 = N->getOperand(0);
7610 SDValue N1 = N->getOperand(1);
7611 SDValue N2 = N->getOperand(2);
7612 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7613 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7614 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007615 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007616 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007617
7618 // Constant fold FMA.
7619 if (isa<ConstantFPSDNode>(N0) &&
7620 isa<ConstantFPSDNode>(N1) &&
7621 isa<ConstantFPSDNode>(N2)) {
7622 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7623 }
7624
Sanjay Patel78614bf2014-08-28 15:53:16 +00007625 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00007626 if (N0CFP && N0CFP->isZero())
7627 return N2;
7628 if (N1CFP && N1CFP->isZero())
7629 return N2;
7630 }
Owen Anderson41b06652012-05-02 22:17:40 +00007631 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007632 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007633 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007634 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007635
Owen Andersonc7aaf522012-05-30 18:50:39 +00007636 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00007637 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007638 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00007639
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007640 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007641 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007642 N2.getOpcode() == ISD::FMUL &&
7643 N0 == N2.getOperand(0) &&
7644 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7645 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7646 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7647 }
7648
7649
7650 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007651 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007652 N0.getOpcode() == ISD::FMUL && N1CFP &&
7653 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7654 return DAG.getNode(ISD::FMA, dl, VT,
7655 N0.getOperand(0),
7656 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7657 N2);
7658 }
7659
7660 // (fma x, 1, y) -> (fadd x, y)
7661 // (fma x, -1, y) -> (fadd (fneg x), y)
7662 if (N1CFP) {
7663 if (N1CFP->isExactlyValue(1.0))
7664 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7665
7666 if (N1CFP->isExactlyValue(-1.0) &&
7667 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7668 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007669 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007670 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7671 }
7672 }
7673
7674 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007675 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00007676 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007677 DAG.getNode(ISD::FADD, dl, VT,
7678 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007679
7680 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007681 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00007682 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7683 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007684 DAG.getNode(ISD::FADD, dl, VT,
7685 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007686
7687
Owen Anderson41b06652012-05-02 22:17:40 +00007688 return SDValue();
7689}
7690
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007691SDValue DAGCombiner::visitFDIV(SDNode *N) {
7692 SDValue N0 = N->getOperand(0);
7693 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007694 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7695 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007696 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007697 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007698 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007699
Dan Gohmana8665142007-06-25 16:23:39 +00007700 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007701 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007702 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007703 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007704 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007705
Nate Begeman569c4392006-01-18 22:35:16 +00007706 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007707 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007708 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007709
Sanjay Patelb67bd262014-09-21 15:19:15 +00007710 if (Options.UnsafeFPMath) {
7711 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7712 if (N1CFP) {
7713 // Compute the reciprocal 1.0 / c2.
7714 APFloat N1APF = N1CFP->getValueAPF();
7715 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7716 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7717 // Only do the transform if the reciprocal is a legal fp immediate that
7718 // isn't too nasty (eg NaN, denormal, ...).
7719 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7720 (!LegalOperations ||
7721 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7722 // backend)... we should handle this gracefully after Legalize.
7723 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7724 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7725 TLI.isFPImmLegal(Recip, VT)))
7726 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7727 DAG.getConstantFP(Recip, VT));
7728 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007729
Sanjay Patelb67bd262014-09-21 15:19:15 +00007730 // If this FDIV is part of a reciprocal square root, it may be folded
7731 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007732 if (N1.getOpcode() == ISD::FSQRT) {
7733 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007734 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7735 }
7736 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7737 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7738 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007739 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7740 AddToWorklist(RV.getNode());
7741 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7742 }
7743 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7744 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7745 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007746 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7747 AddToWorklist(RV.getNode());
7748 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7749 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00007750 } else if (N1.getOpcode() == ISD::FMUL) {
7751 // Look through an FMUL. Even though this won't remove the FDIV directly,
7752 // it's still worthwhile to get rid of the FSQRT if possible.
7753 SDValue SqrtOp;
7754 SDValue OtherOp;
7755 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7756 SqrtOp = N1.getOperand(0);
7757 OtherOp = N1.getOperand(1);
7758 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7759 SqrtOp = N1.getOperand(1);
7760 OtherOp = N1.getOperand(0);
7761 }
7762 if (SqrtOp.getNode()) {
7763 // We found a FSQRT, so try to make this fold:
7764 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7765 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00007766 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7767 AddToWorklist(RV.getNode());
7768 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7769 }
7770 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007771 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007772
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007773 // Fold into a reciprocal estimate and multiply instead of a real divide.
7774 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7775 AddToWorklist(RV.getNode());
7776 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7777 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00007778 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007779
Bill Wendling3dc5d242009-01-30 22:57:07 +00007780 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007781 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7782 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007783 // Both can be negated for free, check to see if at least one is cheaper
7784 // negated.
7785 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007786 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007787 GetNegatedExpression(N0, DAG, LegalOperations),
7788 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007789 }
7790 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007791
Hao Liu44e5d7a2014-11-21 06:39:58 +00007792 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7793 // reciprocal.
7794 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7795 // Notice that this is not always beneficial. One reason is different target
7796 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7797 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7798 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7799 if (Options.UnsafeFPMath) {
7800 // Skip if current node is a reciprocal.
7801 if (N0CFP && N0CFP->isExactlyValue(1.0))
7802 return SDValue();
7803
7804 SmallVector<SDNode *, 4> Users;
7805 // Find all FDIV users of the same divisor.
7806 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7807 UE = N1.getNode()->use_end();
7808 UI != UE; ++UI) {
7809 SDNode *User = UI.getUse().getUser();
7810 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7811 Users.push_back(User);
7812 }
7813
7814 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7815 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7816 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7817
7818 // Dividend / Divisor -> Dividend * Reciprocal
7819 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7820 if ((*I)->getOperand(0) != FPOne) {
7821 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7822 (*I)->getOperand(0), Reciprocal);
7823 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7824 }
7825 }
7826 return SDValue();
7827 }
7828 }
7829
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007830 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007831}
7832
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007833SDValue DAGCombiner::visitFREM(SDNode *N) {
7834 SDValue N0 = N->getOperand(0);
7835 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007836 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7837 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007838 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007839
Nate Begeman569c4392006-01-18 22:35:16 +00007840 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007841 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007842 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007843
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007844 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007845}
7846
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007847SDValue DAGCombiner::visitFSQRT(SDNode *N) {
Matt Arsenaultbf0db912015-01-13 20:53:23 +00007848 if (DAG.getTarget().Options.UnsafeFPMath &&
7849 !TLI.isFsqrtCheap()) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007850 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007851 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007852 EVT VT = RV.getValueType();
7853 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7854 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007855
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007856 // Unfortunately, RV is now NaN if the input was exactly 0.
7857 // Select out this case and force the answer to 0.
7858 SDValue Zero = DAG.getConstantFP(0.0, VT);
7859 SDValue ZeroCmp =
7860 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7861 N->getOperand(0), Zero, ISD::SETEQ);
7862 AddToWorklist(ZeroCmp.getNode());
7863 AddToWorklist(RV.getNode());
7864
7865 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7866 SDLoc(N), VT, ZeroCmp, Zero, RV);
7867 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007868 }
7869 }
7870 return SDValue();
7871}
7872
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007873SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7874 SDValue N0 = N->getOperand(0);
7875 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007876 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7877 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007878 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007879
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007880 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007881 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007882
Chris Lattner3bc40502006-03-05 05:30:57 +00007883 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007884 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007885 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7886 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007887 if (!V.isNegative()) {
7888 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007889 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007890 } else {
7891 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007892 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7893 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007894 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007895 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007896
Chris Lattner3bc40502006-03-05 05:30:57 +00007897 // copysign(fabs(x), y) -> copysign(x, y)
7898 // copysign(fneg(x), y) -> copysign(x, y)
7899 // copysign(copysign(x,z), y) -> copysign(x, y)
7900 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7901 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007902 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007903 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007904
7905 // copysign(x, abs(y)) -> abs(x)
7906 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007907 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007908
Chris Lattner3bc40502006-03-05 05:30:57 +00007909 // copysign(x, copysign(y,z)) -> copysign(x, z)
7910 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007911 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007912 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007913
Chris Lattner3bc40502006-03-05 05:30:57 +00007914 // copysign(x, fp_extend(y)) -> copysign(x, y)
7915 // copysign(x, fp_round(y)) -> copysign(x, y)
7916 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007917 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007918 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007919
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007920 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007921}
7922
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007923SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7924 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007925 EVT VT = N->getValueType(0);
7926 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007927
Nate Begeman21158fc2005-09-01 00:19:25 +00007928 // fold (sint_to_fp c1) -> c1fp
Matthias Braun00a40762015-02-24 18:52:01 +00007929 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007930 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007931 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007932 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007933 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007934 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007935
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007936 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7937 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007938 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7939 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007940 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007941 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007942 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007943 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007944
Alp Tokercb402912014-01-24 17:20:08 +00007945 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007946 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007947 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7948 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7949 !VT.isVector() &&
7950 (!LegalOperations ||
7951 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7952 SDValue Ops[] =
7953 { N0.getOperand(0), N0.getOperand(1),
7954 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7955 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007956 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007957 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007958
Nadav Rotem90560762012-07-23 07:59:50 +00007959 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7960 // (select_cc x, y, 1.0, 0.0,, cc)
7961 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7962 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7963 (!LegalOperations ||
7964 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7965 SDValue Ops[] =
7966 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7967 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7968 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007969 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007970 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007971 }
7972
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007973 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007974}
7975
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007976SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7977 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007978 EVT VT = N->getValueType(0);
7979 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007980
Nate Begeman21158fc2005-09-01 00:19:25 +00007981 // fold (uint_to_fp c1) -> c1fp
Matthias Braun00a40762015-02-24 18:52:01 +00007982 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007983 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007984 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007985 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007986 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007987 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007988
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007989 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7990 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007991 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7992 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007993 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007994 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007995 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007996 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007997
Alp Tokercb402912014-01-24 17:20:08 +00007998 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007999 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008000 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00008001
Nadav Rotem90560762012-07-23 07:59:50 +00008002 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8003 (!LegalOperations ||
8004 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8005 SDValue Ops[] =
8006 { N0.getOperand(0), N0.getOperand(1),
8007 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
8008 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00008009 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008010 }
8011 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008012
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008013 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008014}
8015
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008016// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8017static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8018 SDValue N0 = N->getOperand(0);
8019 EVT VT = N->getValueType(0);
8020
8021 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8022 return SDValue();
8023
8024 SDValue Src = N0.getOperand(0);
8025 EVT SrcVT = Src.getValueType();
8026 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8027 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8028
8029 // We can safely assume the conversion won't overflow the output range,
8030 // because (for example) (uint8_t)18293.f is undefined behavior.
8031
8032 // Since we can assume the conversion won't overflow, our decision as to
8033 // whether the input will fit in the float should depend on the minimum
8034 // of the input range and output range.
8035
8036 // This means this is also safe for a signed input and unsigned output, since
8037 // a negative input would lead to undefined behavior.
8038 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8039 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8040 unsigned ActualSize = std::min(InputSize, OutputSize);
8041 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8042
8043 // We can only fold away the float conversion if the input range can be
8044 // represented exactly in the float range.
8045 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8046 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8047 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8048 : ISD::ZERO_EXTEND;
8049 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8050 }
8051 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8052 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8053 if (SrcVT == VT)
8054 return Src;
8055 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8056 }
8057 return SDValue();
8058}
8059
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008060SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8061 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008062 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008063 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008064
Nate Begeman21158fc2005-09-01 00:19:25 +00008065 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008066 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008067 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008068
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008069 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008070}
8071
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008072SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8073 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008074 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008075 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008076
Nate Begeman21158fc2005-09-01 00:19:25 +00008077 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008078 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008079 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008080
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008081 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008082}
8083
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008084SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8085 SDValue N0 = N->getOperand(0);
8086 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008087 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008088 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008089
Nate Begeman21158fc2005-09-01 00:19:25 +00008090 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008091 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008092 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008093
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008094 // fold (fp_round (fp_extend x)) -> x
8095 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8096 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008097
Chris Lattner0feb1b02008-01-24 06:45:35 +00008098 // fold (fp_round (fp_round x)) -> (fp_round x)
8099 if (N0.getOpcode() == ISD::FP_ROUND) {
Ahmed Bougacha24433a72015-02-12 06:15:29 +00008100 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8101 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8102 // If the first fp_round isn't a value preserving truncation, it might
8103 // introduce a tie in the second fp_round, that wouldn't occur in the
8104 // single-step fp_round we want to fold to.
8105 // In other words, double rounding isn't the same as rounding.
8106 // Also, this is a value preserving truncation iff both fp_round's are.
8107 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
8108 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
8109 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
Chris Lattner0feb1b02008-01-24 06:45:35 +00008110 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008111
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008112 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00008113 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008114 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008115 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008116 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008117 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008118 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008119 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008120
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008121 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008122}
8123
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008124SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8125 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008126 EVT VT = N->getValueType(0);
8127 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008128 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008129
Nate Begeman21158fc2005-09-01 00:19:25 +00008130 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00008131 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00008132 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008133 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00008134 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008135
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008136 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008137}
8138
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008139SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8140 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008141 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008142 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008143
Chris Lattner5919b482007-12-29 06:55:23 +00008144 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008145 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00008146 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008147 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00008148
Nate Begeman21158fc2005-09-01 00:19:25 +00008149 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008150 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008151 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00008152
8153 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8154 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00008155 if (N0.getOpcode() == ISD::FP_ROUND
8156 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008157 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00008158 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00008159 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008160 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008161 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008162 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00008163 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008164
Chris Lattner72733e52008-01-17 07:00:52 +00008165 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00008166 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00008167 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008168 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008169 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008170 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008171 LN0->getBasePtr(), N0.getValueType(),
8172 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00008173 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00008174 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008175 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00008176 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00008177 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008178 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00008179 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00008180
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008181 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008182}
8183
Sanjay Patelccd26762014-08-28 21:51:37 +00008184SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8185 SDValue N0 = N->getOperand(0);
8186 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8187 EVT VT = N->getValueType(0);
8188
8189 // fold (fceil c1) -> fceil(c1)
8190 if (N0CFP)
8191 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8192
8193 return SDValue();
8194}
8195
8196SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8197 SDValue N0 = N->getOperand(0);
8198 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8199 EVT VT = N->getValueType(0);
8200
8201 // fold (ftrunc c1) -> ftrunc(c1)
8202 if (N0CFP)
8203 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8204
8205 return SDValue();
8206}
8207
8208SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8209 SDValue N0 = N->getOperand(0);
8210 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8211 EVT VT = N->getValueType(0);
8212
8213 // fold (ffloor c1) -> ffloor(c1)
8214 if (N0CFP)
8215 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8216
8217 return SDValue();
8218}
8219
8220// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008221SDValue DAGCombiner::visitFNEG(SDNode *N) {
8222 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00008223 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008224
Craig Topper82384612012-09-11 01:45:21 +00008225 if (VT.isVector()) {
8226 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8227 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00008228 }
8229
Sanjay Patelccd26762014-08-28 21:51:37 +00008230 // Constant fold FNEG.
8231 if (isa<ConstantFPSDNode>(N0))
8232 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8233
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00008234 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8235 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008236 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00008237
Sanjay Patel35d31332014-08-14 15:15:28 +00008238 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008239 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00008240 if (!TLI.isFNegFree(VT) &&
8241 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00008242 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008243 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008244 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008245 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00008246 APInt SignMask;
8247 if (N0.getValueType().isVector()) {
8248 // For a vector, get a mask such as 0x80... per scalar element
8249 // and splat it.
8250 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8251 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8252 } else {
8253 // For a scalar, just generate 0x80...
8254 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8255 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008256 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00008257 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008258 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00008259 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008260 }
8261 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008262
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008263 // (fneg (fmul c, x)) -> (fmul -c, x)
8264 if (N0.getOpcode() == ISD::FMUL) {
8265 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00008266 if (CFP1) {
8267 APFloat CVal = CFP1->getValueAPF();
8268 CVal.changeSign();
8269 if (Level >= AfterLegalizeDAG &&
8270 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8271 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8272 return DAG.getNode(
8273 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8274 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8275 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008276 }
8277
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008278 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008279}
8280
Matt Arsenault7c936902014-10-21 23:01:01 +00008281SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8282 SDValue N0 = N->getOperand(0);
8283 SDValue N1 = N->getOperand(1);
8284 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8285 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8286
8287 if (N0CFP && N1CFP) {
8288 const APFloat &C0 = N0CFP->getValueAPF();
8289 const APFloat &C1 = N1CFP->getValueAPF();
8290 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8291 }
8292
8293 if (N0CFP) {
8294 EVT VT = N->getValueType(0);
8295 // Canonicalize to constant on RHS.
8296 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8297 }
8298
8299 return SDValue();
8300}
8301
8302SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8303 SDValue N0 = N->getOperand(0);
8304 SDValue N1 = N->getOperand(1);
8305 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8306 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8307
8308 if (N0CFP && N1CFP) {
8309 const APFloat &C0 = N0CFP->getValueAPF();
8310 const APFloat &C1 = N1CFP->getValueAPF();
8311 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8312 }
8313
8314 if (N0CFP) {
8315 EVT VT = N->getValueType(0);
8316 // Canonicalize to constant on RHS.
8317 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8318 }
8319
8320 return SDValue();
8321}
8322
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008323SDValue DAGCombiner::visitFABS(SDNode *N) {
8324 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008325 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008326
Craig Topper82384612012-09-11 01:45:21 +00008327 if (VT.isVector()) {
8328 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8329 if (FoldedVOp.getNode()) return FoldedVOp;
8330 }
8331
Nate Begeman21158fc2005-09-01 00:19:25 +00008332 // fold (fabs c1) -> fabs(c1)
Sanjay Patelccd26762014-08-28 21:51:37 +00008333 if (isa<ConstantFPSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008334 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008335
Nate Begeman21158fc2005-09-01 00:19:25 +00008336 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008337 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00008338 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008339
Nate Begeman21158fc2005-09-01 00:19:25 +00008340 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008341 // fold (fabs (fcopysign x, y)) -> (fabs x)
8342 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008343 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008344
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008345 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008346 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00008347 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008348 N0.getOpcode() == ISD::BITCAST &&
8349 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008350 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008351 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008352 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008353 APInt SignMask;
8354 if (N0.getValueType().isVector()) {
8355 // For a vector, get a mask such as 0x7f... per scalar element
8356 // and splat it.
8357 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8358 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8359 } else {
8360 // For a scalar, just generate 0x7f...
8361 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8362 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008363 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008364 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008365 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008366 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008367 }
8368 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008369
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008370 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008371}
8372
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008373SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8374 SDValue Chain = N->getOperand(0);
8375 SDValue N1 = N->getOperand(1);
8376 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008377
Dan Gohman82e80012009-11-17 00:47:23 +00008378 // If N is a constant we could fold this into a fallthrough or unconditional
8379 // branch. However that doesn't happen very often in normal code, because
8380 // Instcombine/SimplifyCFG should have handled the available opportunities.
8381 // If we did this folding here, it would be necessary to update the
8382 // MachineBasicBlock CFG, which is awkward.
8383
Nate Begeman7e7f4392006-02-01 07:19:44 +00008384 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8385 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008386 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00008387 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8388 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008389 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008390 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00008391 N1.getOperand(0), N1.getOperand(1), N2);
8392 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008393
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008394 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8395 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8396 (N1.getOperand(0).hasOneUse() &&
8397 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00008398 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008399 if (N1.getOpcode() == ISD::TRUNCATE) {
8400 // Look pass the truncate.
8401 Trunc = N1.getNode();
8402 N1 = N1.getOperand(0);
8403 }
Evan Cheng166a4e62010-01-06 19:38:29 +00008404
Bill Wendlingaa28be62009-03-26 06:14:09 +00008405 // Match this pattern so that we can generate simpler code:
8406 //
8407 // %a = ...
8408 // %b = and i32 %a, 2
8409 // %c = srl i32 %b, 1
8410 // brcond i32 %c ...
8411 //
8412 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00008413 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00008414 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00008415 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00008416 // %c = setcc eq %b, 0
8417 // brcond %c ...
8418 //
8419 // This applies only when the AND constant value has one bit set and the
8420 // SRL constant is equal to the log2 of the AND constant. The back-end is
8421 // smart enough to convert the result into a TEST/JMP sequence.
8422 SDValue Op0 = N1.getOperand(0);
8423 SDValue Op1 = N1.getOperand(1);
8424
8425 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00008426 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00008427 SDValue AndOp1 = Op0.getOperand(1);
8428
8429 if (AndOp1.getOpcode() == ISD::Constant) {
8430 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8431
8432 if (AndConst.isPowerOf2() &&
8433 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8434 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008435 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00008436 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00008437 Op0, DAG.getConstant(0, Op0.getValueType()),
8438 ISD::SETNE);
8439
Andrew Trickef9de2a2013-05-25 02:42:55 +00008440 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00008441 MVT::Other, Chain, SetCC, N2);
8442 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8443 // will convert it back to (X & C1) >> C2.
8444 CombineTo(N, NewBRCond, false);
8445 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00008446 if (Trunc)
8447 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008448 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008449 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008450 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008451 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00008452 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00008453 }
8454 }
8455 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008456
8457 if (Trunc)
8458 // Restore N1 if the above transformation doesn't match.
8459 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008460 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008461
Evan Cheng228c31f2010-02-27 07:36:59 +00008462 // Transform br(xor(x, y)) -> br(x != y)
8463 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8464 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8465 SDNode *TheXor = N1.getNode();
8466 SDValue Op0 = TheXor->getOperand(0);
8467 SDValue Op1 = TheXor->getOperand(1);
8468 if (Op0.getOpcode() == Op1.getOpcode()) {
8469 // Avoid missing important xor optimizations.
8470 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008471 if (Tmp.getNode()) {
8472 if (Tmp.getNode() != TheXor) {
8473 DEBUG(dbgs() << "\nReplacing.8 ";
8474 TheXor->dump(&DAG);
8475 dbgs() << "\nWith: ";
8476 Tmp.getNode()->dump(&DAG);
8477 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008478 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008479 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00008480 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008481 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00008482 MVT::Other, Chain, Tmp, N2);
8483 }
8484
Benjamin Kramer93354432013-03-30 21:28:18 +00008485 // visitXOR has changed XOR's operands or replaced the XOR completely,
8486 // bail out.
8487 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00008488 }
8489 }
8490
8491 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8492 bool Equal = false;
8493 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8494 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8495 Op0.getOpcode() == ISD::XOR) {
8496 TheXor = Op0.getNode();
8497 Equal = true;
8498 }
8499
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008500 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00008501 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00008502 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008503 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00008504 SetCCVT,
8505 Op0, Op1,
8506 Equal ? ISD::SETEQ : ISD::SETNE);
8507 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008508 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008509 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008510 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008511 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00008512 MVT::Other, Chain, SetCC, N2);
8513 }
8514 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00008515
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008516 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008517}
8518
Chris Lattnera49e16f2005-10-05 06:47:48 +00008519// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8520//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008521SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00008522 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008523 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008524
Dan Gohman82e80012009-11-17 00:47:23 +00008525 // If N is a constant we could fold this into a fallthrough or unconditional
8526 // branch. However that doesn't happen very often in normal code, because
8527 // Instcombine/SimplifyCFG should have handled the available opportunities.
8528 // If we did this folding here, it would be necessary to update the
8529 // MachineBasicBlock CFG, which is awkward.
8530
Duncan Sands93b66092008-06-09 11:32:28 +00008531 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00008532 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008533 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00008534 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008535 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00008536
Nate Begemanbd7df032005-10-05 21:43:42 +00008537 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00008538 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008539 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008540 N->getOperand(0), Simp.getOperand(2),
8541 Simp.getOperand(0), Simp.getOperand(1),
8542 N->getOperand(4));
8543
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008544 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008545}
8546
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008547/// Return true if 'Use' is a load or a store that uses N as its base pointer
8548/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00008549static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8550 SelectionDAG &DAG,
8551 const TargetLowering &TLI) {
8552 EVT VT;
8553 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8554 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8555 return false;
8556 VT = Use->getValueType(0);
8557 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8558 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8559 return false;
8560 VT = ST->getValue().getValueType();
8561 } else
8562 return false;
8563
Chandler Carruth95f83e02013-01-07 15:14:13 +00008564 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00008565 if (N->getOpcode() == ISD::ADD) {
8566 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8567 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008568 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008569 AM.BaseOffs = Offset->getSExtValue();
8570 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008571 // [reg +/- reg]
8572 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008573 } else if (N->getOpcode() == ISD::SUB) {
8574 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8575 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008576 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008577 AM.BaseOffs = -Offset->getSExtValue();
8578 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008579 // [reg +/- reg]
8580 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008581 } else
8582 return false;
8583
8584 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8585}
8586
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008587/// Try turning a load/store into a pre-indexed load/store when the base
8588/// pointer is an add or subtract and it has other uses besides the load/store.
8589/// After the transformation, the new indexed load/store has effectively folded
8590/// the add/subtract in and all of its other uses are redirected to the
8591/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008592bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008593 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008594 return false;
8595
8596 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008597 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008598 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008599 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008600 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008601 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008602 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00008603 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00008604 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8605 return false;
8606 Ptr = LD->getBasePtr();
8607 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008608 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008609 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008610 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008611 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8612 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8613 return false;
8614 Ptr = ST->getBasePtr();
8615 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008616 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008617 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008618 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008619
Chris Lattnereabc15c2006-11-11 00:56:29 +00008620 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8621 // out. There is no reason to make this a preinc/predec.
8622 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00008623 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008624 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008625
Chris Lattnereabc15c2006-11-11 00:56:29 +00008626 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008627 SDValue BasePtr;
8628 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008629 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8630 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8631 return false;
Hal Finkel25819052013-02-08 21:35:47 +00008632
8633 // Backends without true r+i pre-indexed forms may need to pass a
8634 // constant base with a variable offset so that constant coercion
8635 // will work with the patterns in canonical form.
8636 bool Swapped = false;
8637 if (isa<ConstantSDNode>(BasePtr)) {
8638 std::swap(BasePtr, Offset);
8639 Swapped = true;
8640 }
8641
Evan Cheng044a0a82007-05-03 23:52:19 +00008642 // Don't create a indexed load / store with zero offset.
8643 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008644 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008645 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008646
Chris Lattnera0a80032006-11-11 01:00:15 +00008647 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00008648 // 1) The new base ptr is a frame index.
8649 // 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 +00008650 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00008651 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00008652 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00008653 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00008654
Chris Lattnera0a80032006-11-11 01:00:15 +00008655 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8656 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00008657 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00008658 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008659
Chris Lattnera0a80032006-11-11 01:00:15 +00008660 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008661 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008662 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00008663 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008664 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008665 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008666
Hal Finkel25819052013-02-08 21:35:47 +00008667 // If the offset is a constant, there may be other adds of constants that
8668 // can be folded with this one. We should do this to avoid having to keep
8669 // a copy of the original base pointer.
8670 SmallVector<SDNode *, 16> OtherUses;
8671 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00008672 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00008673 if (Use == Ptr.getNode())
8674 continue;
8675
8676 if (Use->isPredecessorOf(N))
8677 continue;
8678
8679 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8680 OtherUses.clear();
8681 break;
8682 }
8683
8684 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8685 if (Op1.getNode() == BasePtr.getNode())
8686 std::swap(Op0, Op1);
8687 assert(Op0.getNode() == BasePtr.getNode() &&
8688 "Use of ADD/SUB but not an operand");
8689
8690 if (!isa<ConstantSDNode>(Op1)) {
8691 OtherUses.clear();
8692 break;
8693 }
8694
8695 // FIXME: In some cases, we can be smarter about this.
8696 if (Op1.getValueType() != Offset.getValueType()) {
8697 OtherUses.clear();
8698 break;
8699 }
8700
8701 OtherUses.push_back(Use);
8702 }
8703
8704 if (Swapped)
8705 std::swap(BasePtr, Offset);
8706
Evan Chenga4d187b2007-05-24 02:35:39 +00008707 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008708 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00008709
8710 // Caches for hasPredecessorHelper
8711 SmallPtrSet<const SDNode *, 32> Visited;
8712 SmallVector<const SDNode *, 16> Worklist;
8713
Jim Grosbache8160032014-04-11 01:13:13 +00008714 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008715 if (Use == N)
8716 continue;
Lang Hames5a004992011-07-07 04:31:51 +00008717 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008718 return false;
8719
Evan Chengfa832632012-01-13 01:37:24 +00008720 // If Ptr may be folded in addressing mode of other use, then it's
8721 // not profitable to do this transformation.
8722 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008723 RealUse = true;
8724 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008725
Chris Lattnereabc15c2006-11-11 00:56:29 +00008726 if (!RealUse)
8727 return false;
8728
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008729 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008730 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008731 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008732 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008733 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00008734 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008735 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008736 ++PreIndexedNodes;
8737 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008738 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008739 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008740 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008741 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008742 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008743 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008744 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008745 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8746 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008747 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008748 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008749 }
8750
Chris Lattnereabc15c2006-11-11 00:56:29 +00008751 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008752 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008753
Hal Finkel25819052013-02-08 21:35:47 +00008754 if (Swapped)
8755 std::swap(BasePtr, Offset);
8756
8757 // Replace other uses of BasePtr that can be updated to use Ptr
8758 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8759 unsigned OffsetIdx = 1;
8760 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8761 OffsetIdx = 0;
8762 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8763 BasePtr.getNode() && "Expected BasePtr operand");
8764
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008765 // We need to replace ptr0 in the following expression:
8766 // x0 * offset0 + y0 * ptr0 = t0
8767 // knowing that
8768 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00008769 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008770 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8771 // indexed load/store and the expresion that needs to be re-written.
8772 //
8773 // Therefore, we have:
8774 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00008775
8776 ConstantSDNode *CN =
8777 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008778 int X0, X1, Y0, Y1;
8779 APInt Offset0 = CN->getAPIntValue();
8780 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00008781
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008782 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8783 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8784 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8785 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00008786
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008787 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8788
8789 APInt CNV = Offset0;
8790 if (X0 < 0) CNV = -CNV;
8791 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8792 else CNV = CNV - Offset1;
8793
8794 // We can now generate the new expression.
8795 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8796 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8797
8798 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00008799 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00008800 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8801 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00008802 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00008803 }
8804
Chris Lattnereabc15c2006-11-11 00:56:29 +00008805 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008806 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008807 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00008808
8809 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008810}
8811
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008812/// Try to combine a load/store with a add/sub of the base pointer node into a
8813/// post-indexed load/store. The transformation folded the add/subtract into the
8814/// new indexed load/store effectively and all of its uses are redirected to the
8815/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008816bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008817 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008818 return false;
8819
8820 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008821 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008822 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008823 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008824 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008825 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008826 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008827 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8828 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8829 return false;
8830 Ptr = LD->getBasePtr();
8831 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008832 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008833 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008834 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008835 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8836 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8837 return false;
8838 Ptr = ST->getBasePtr();
8839 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008840 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008841 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008842 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008843
Gabor Greiff304a7a2008-08-28 21:40:38 +00008844 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008845 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008846
Jim Grosbache8160032014-04-11 01:13:13 +00008847 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008848 if (Op == N ||
8849 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8850 continue;
8851
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008852 SDValue BasePtr;
8853 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008854 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8855 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00008856 // Don't create a indexed load / store with zero offset.
8857 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008858 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008859 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008860
Chris Lattnereabc15c2006-11-11 00:56:29 +00008861 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00008862 // 1) All uses are load / store ops that use it as base ptr (and
8863 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00008864 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8865 // nor a successor of N. Otherwise, if Op is folded that would
8866 // create a cycle.
8867
Evan Chengcfc05132009-05-06 18:25:01 +00008868 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8869 continue;
8870
Chris Lattnereabc15c2006-11-11 00:56:29 +00008871 // Check for #1.
8872 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008873 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008874 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00008875 continue;
8876
Chris Lattnereabc15c2006-11-11 00:56:29 +00008877 // If all the uses are load / store addresses, then don't do the
8878 // transformation.
8879 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8880 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008881 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00008882 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008883 RealUse = true;
8884 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008885
Chris Lattnereabc15c2006-11-11 00:56:29 +00008886 if (!RealUse) {
8887 TryNext = true;
8888 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00008889 }
8890 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008891 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008892
Chris Lattnereabc15c2006-11-11 00:56:29 +00008893 if (TryNext)
8894 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008895
Chris Lattnereabc15c2006-11-11 00:56:29 +00008896 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00008897 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008898 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00008899 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008900 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008901 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008902 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008903 ++PostIndexedNodes;
8904 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008905 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008906 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008907 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008908 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008909 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008910 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008911 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008912 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8913 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008914 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008915 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008916 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008917
Chris Lattnereabc15c2006-11-11 00:56:29 +00008918 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008919 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008920
8921 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008922 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008923 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008924 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008925 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008926 }
8927 }
8928 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008929
Chris Lattnerffad2162006-11-11 00:39:41 +00008930 return false;
8931}
8932
Hal Finkel51e6fa22014-09-02 06:24:04 +00008933/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8934SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8935 ISD::MemIndexedMode AM = LD->getAddressingMode();
8936 assert(AM != ISD::UNINDEXED);
8937 SDValue BP = LD->getOperand(1);
8938 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008939
8940 // Some backends use TargetConstants for load offsets, but don't expect
8941 // TargetConstants in general ADD nodes. We can convert these constants into
8942 // regular Constants (if the constant is not opaque).
8943 assert((Inc.getOpcode() != ISD::TargetConstant ||
8944 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8945 "Cannot split out indexing using opaque target constants");
8946 if (Inc.getOpcode() == ISD::TargetConstant) {
8947 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8948 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8949 ConstInc->getValueType(0));
8950 }
8951
Hal Finkel51e6fa22014-09-02 06:24:04 +00008952 unsigned Opc =
8953 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8954 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8955}
8956
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008957SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008958 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008959 SDValue Chain = LD->getChain();
8960 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008961
Evan Chenga684cd22007-05-01 00:38:21 +00008962 // If load is not volatile and there are no uses of the loaded value (and
8963 // the updated indexed value in case of indexed loads), change uses of the
8964 // chain value into uses of the chain input (i.e. delete the dead load).
8965 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008966 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008967 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008968 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008969 // It's not safe to use the two value CombineTo variant here. e.g.
8970 // v1, chain2 = load chain1, loc
8971 // v2, chain3 = load chain2, loc
8972 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008973 // Now we replace use of chain2 with chain1. This makes the second load
8974 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008975 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008976 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008977 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008978 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008979 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008980 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008981 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008982
Chandler Carruth18066972014-08-02 10:02:07 +00008983 if (N->use_empty())
8984 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008985
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008986 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008987 }
Evan Chengb68343c2007-05-01 08:53:39 +00008988 } else {
8989 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008990 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008991
Hal Finkele19006e2014-09-02 16:05:23 +00008992 // If this load has an opaque TargetConstant offset, then we cannot split
8993 // the indexing into an add/sub directly (that TargetConstant may not be
8994 // valid for a different type of node, and we cannot convert an opaque
8995 // target constant into a regular constant).
8996 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8997 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00008998
8999 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00009000 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00009001 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00009002 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00009003 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00009004 Index = SplitIndexingFromLoad(LD);
9005 // Try to fold the base pointer arithmetic into subsequent loads and
9006 // stores.
9007 AddUsersToWorklist(N);
9008 } else
9009 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00009010 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009011 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009012 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009013 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009014 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009015 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009016 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00009017 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009018 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00009019 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009020 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00009021 }
Evan Chenga684cd22007-05-01 00:38:21 +00009022 }
9023 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009024
Chris Lattnere260ed82005-10-10 22:04:48 +00009025 // If this load is directly stored, replace the load value with the stored
9026 // value.
9027 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009028 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00009029 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009030 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00009031 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9032 if (PrevST->getBasePtr() == Ptr &&
9033 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00009034 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00009035 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00009036 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009037
Evan Cheng43cd9e32010-04-01 06:04:33 +00009038 // Try to infer better alignment information than the load already has.
9039 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009040 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00009041 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9042 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00009043 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00009044 LD->getValueType(0),
9045 Chain, Ptr, LD->getPointerInfo(),
9046 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00009047 LD->isVolatile(), LD->isNonTemporal(),
9048 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00009049 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9050 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00009051 }
9052 }
9053
Eric Christopherf55d4712014-10-08 23:38:39 +00009054 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9055 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009056#ifndef NDEBUG
9057 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9058 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9059 UseAA = false;
9060#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009061 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009062 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009063 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009064
Jim Laskey708d0db2006-10-04 16:53:27 +00009065 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009066 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009067 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00009068
Jim Laskeyd07be232006-09-25 16:29:54 +00009069 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009070 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009071 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009072 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009073 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009074 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00009075 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009076 BetterChain, Ptr, LD->getMemoryVT(),
9077 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009078 }
Jim Laskeyd07be232006-09-25 16:29:54 +00009079
Jim Laskey708d0db2006-10-04 16:53:27 +00009080 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009081 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009082 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00009083
Nate Begeman879d8f12009-09-15 00:18:30 +00009084 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009085 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00009086
Jim Laskeydcf983c2006-10-13 23:32:28 +00009087 // Replace uses with load result and token factor. Don't add users
9088 // to work list.
9089 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009090 }
9091 }
9092
Evan Cheng357017f2006-11-03 03:06:21 +00009093 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00009094 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009095 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00009096
Quentin Colombetde0e0622013-10-11 18:29:42 +00009097 // Try to slice up N to more direct loads if the slices are mapped to
9098 // different register banks or pairing can take place.
9099 if (SliceUpLoad(N))
9100 return SDValue(N, 0);
9101
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009102 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00009103}
9104
Quentin Colombetde0e0622013-10-11 18:29:42 +00009105namespace {
9106/// \brief Helper structure used to slice a load in smaller loads.
9107/// Basically a slice is obtained from the following sequence:
9108/// Origin = load Ty1, Base
9109/// Shift = srl Ty1 Origin, CstTy Amount
9110/// Inst = trunc Shift to Ty2
9111///
9112/// Then, it will be rewriten into:
9113/// Slice = load SliceTy, Base + SliceOffset
9114/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9115///
9116/// SliceTy is deduced from the number of bits that are actually used to
9117/// build Inst.
9118struct LoadedSlice {
9119 /// \brief Helper structure used to compute the cost of a slice.
9120 struct Cost {
9121 /// Are we optimizing for code size.
9122 bool ForCodeSize;
9123 /// Various cost.
9124 unsigned Loads;
9125 unsigned Truncates;
9126 unsigned CrossRegisterBanksCopies;
9127 unsigned ZExts;
9128 unsigned Shift;
9129
9130 Cost(bool ForCodeSize = false)
9131 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9132 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9133
9134 /// \brief Get the cost of one isolated slice.
9135 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9136 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9137 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9138 EVT TruncType = LS.Inst->getValueType(0);
9139 EVT LoadedType = LS.getLoadedType();
9140 if (TruncType != LoadedType &&
9141 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9142 ZExts = 1;
9143 }
9144
9145 /// \brief Account for slicing gain in the current cost.
9146 /// Slicing provide a few gains like removing a shift or a
9147 /// truncate. This method allows to grow the cost of the original
9148 /// load with the gain from this slice.
9149 void addSliceGain(const LoadedSlice &LS) {
9150 // Each slice saves a truncate.
9151 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9152 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9153 LS.Inst->getOperand(0).getValueType()))
9154 ++Truncates;
9155 // If there is a shift amount, this slice gets rid of it.
9156 if (LS.Shift)
9157 ++Shift;
9158 // If this slice can merge a cross register bank copy, account for it.
9159 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9160 ++CrossRegisterBanksCopies;
9161 }
9162
9163 Cost &operator+=(const Cost &RHS) {
9164 Loads += RHS.Loads;
9165 Truncates += RHS.Truncates;
9166 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9167 ZExts += RHS.ZExts;
9168 Shift += RHS.Shift;
9169 return *this;
9170 }
9171
9172 bool operator==(const Cost &RHS) const {
9173 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9174 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9175 ZExts == RHS.ZExts && Shift == RHS.Shift;
9176 }
9177
9178 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9179
9180 bool operator<(const Cost &RHS) const {
9181 // Assume cross register banks copies are as expensive as loads.
9182 // FIXME: Do we want some more target hooks?
9183 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9184 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9185 // Unless we are optimizing for code size, consider the
9186 // expensive operation first.
9187 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9188 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9189 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9190 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9191 }
9192
9193 bool operator>(const Cost &RHS) const { return RHS < *this; }
9194
9195 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9196
9197 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9198 };
9199 // The last instruction that represent the slice. This should be a
9200 // truncate instruction.
9201 SDNode *Inst;
9202 // The original load instruction.
9203 LoadSDNode *Origin;
9204 // The right shift amount in bits from the original load.
9205 unsigned Shift;
9206 // The DAG from which Origin came from.
9207 // This is used to get some contextual information about legal types, etc.
9208 SelectionDAG *DAG;
9209
Craig Topperc0196b12014-04-14 00:51:57 +00009210 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9211 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00009212 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9213
Quentin Colombetde0e0622013-10-11 18:29:42 +00009214 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9215 /// \return Result is \p BitWidth and has used bits set to 1 and
9216 /// not used bits set to 0.
9217 APInt getUsedBits() const {
9218 // Reproduce the trunc(lshr) sequence:
9219 // - Start from the truncated value.
9220 // - Zero extend to the desired bit width.
9221 // - Shift left.
9222 assert(Origin && "No original load to compare against.");
9223 unsigned BitWidth = Origin->getValueSizeInBits(0);
9224 assert(Inst && "This slice is not bound to an instruction");
9225 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9226 "Extracted slice is bigger than the whole type!");
9227 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9228 UsedBits.setAllBits();
9229 UsedBits = UsedBits.zext(BitWidth);
9230 UsedBits <<= Shift;
9231 return UsedBits;
9232 }
9233
9234 /// \brief Get the size of the slice to be loaded in bytes.
9235 unsigned getLoadedSize() const {
9236 unsigned SliceSize = getUsedBits().countPopulation();
9237 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9238 return SliceSize / 8;
9239 }
9240
9241 /// \brief Get the type that will be loaded for this slice.
9242 /// Note: This may not be the final type for the slice.
9243 EVT getLoadedType() const {
9244 assert(DAG && "Missing context");
9245 LLVMContext &Ctxt = *DAG->getContext();
9246 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9247 }
9248
9249 /// \brief Get the alignment of the load used for this slice.
9250 unsigned getAlignment() const {
9251 unsigned Alignment = Origin->getAlignment();
9252 unsigned Offset = getOffsetFromBase();
9253 if (Offset != 0)
9254 Alignment = MinAlign(Alignment, Alignment + Offset);
9255 return Alignment;
9256 }
9257
9258 /// \brief Check if this slice can be rewritten with legal operations.
9259 bool isLegal() const {
9260 // An invalid slice is not legal.
9261 if (!Origin || !Inst || !DAG)
9262 return false;
9263
9264 // Offsets are for indexed load only, we do not handle that.
9265 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9266 return false;
9267
9268 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9269
9270 // Check that the type is legal.
9271 EVT SliceType = getLoadedType();
9272 if (!TLI.isTypeLegal(SliceType))
9273 return false;
9274
9275 // Check that the load is legal for this type.
9276 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9277 return false;
9278
9279 // Check that the offset can be computed.
9280 // 1. Check its type.
9281 EVT PtrType = Origin->getBasePtr().getValueType();
9282 if (PtrType == MVT::Untyped || PtrType.isExtended())
9283 return false;
9284
9285 // 2. Check that it fits in the immediate.
9286 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9287 return false;
9288
9289 // 3. Check that the computation is legal.
9290 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9291 return false;
9292
9293 // Check that the zext is legal if it needs one.
9294 EVT TruncateType = Inst->getValueType(0);
9295 if (TruncateType != SliceType &&
9296 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9297 return false;
9298
9299 return true;
9300 }
9301
9302 /// \brief Get the offset in bytes of this slice in the original chunk of
9303 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00009304 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009305 uint64_t getOffsetFromBase() const {
9306 assert(DAG && "Missing context.");
9307 bool IsBigEndian =
9308 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9309 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9310 uint64_t Offset = Shift / 8;
9311 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9312 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9313 "The size of the original loaded type is not a multiple of a"
9314 " byte.");
9315 // If Offset is bigger than TySizeInBytes, it means we are loading all
9316 // zeros. This should have been optimized before in the process.
9317 assert(TySizeInBytes > Offset &&
9318 "Invalid shift amount for given loaded size");
9319 if (IsBigEndian)
9320 Offset = TySizeInBytes - Offset - getLoadedSize();
9321 return Offset;
9322 }
9323
9324 /// \brief Generate the sequence of instructions to load the slice
9325 /// represented by this object and redirect the uses of this slice to
9326 /// this new sequence of instructions.
9327 /// \pre this->Inst && this->Origin are valid Instructions and this
9328 /// object passed the legal check: LoadedSlice::isLegal returned true.
9329 /// \return The last instruction of the sequence used to load the slice.
9330 SDValue loadSlice() const {
9331 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9332 const SDValue &OldBaseAddr = Origin->getBasePtr();
9333 SDValue BaseAddr = OldBaseAddr;
9334 // Get the offset in that chunk of bytes w.r.t. the endianess.
9335 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9336 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9337 if (Offset) {
9338 // BaseAddr = BaseAddr + Offset.
9339 EVT ArithType = BaseAddr.getValueType();
9340 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9341 DAG->getConstant(Offset, ArithType));
9342 }
9343
9344 // Create the type of the loaded slice according to its size.
9345 EVT SliceType = getLoadedType();
9346
9347 // Create the load for the slice.
9348 SDValue LastInst = DAG->getLoad(
9349 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9350 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9351 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9352 // If the final type is not the same as the loaded type, this means that
9353 // we have to pad with zero. Create a zero extend for that.
9354 EVT FinalType = Inst->getValueType(0);
9355 if (SliceType != FinalType)
9356 LastInst =
9357 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9358 return LastInst;
9359 }
9360
9361 /// \brief Check if this slice can be merged with an expensive cross register
9362 /// bank copy. E.g.,
9363 /// i = load i32
9364 /// f = bitcast i32 i to float
9365 bool canMergeExpensiveCrossRegisterBankCopy() const {
9366 if (!Inst || !Inst->hasOneUse())
9367 return false;
9368 SDNode *Use = *Inst->use_begin();
9369 if (Use->getOpcode() != ISD::BITCAST)
9370 return false;
9371 assert(DAG && "Missing context");
9372 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9373 EVT ResVT = Use->getValueType(0);
9374 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9375 const TargetRegisterClass *ArgRC =
9376 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9377 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9378 return false;
9379
9380 // At this point, we know that we perform a cross-register-bank copy.
9381 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00009382 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00009383 // Assume bitcasts are cheap, unless both register classes do not
9384 // explicitly share a common sub class.
9385 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9386 return false;
9387
9388 // Check if it will be merged with the load.
9389 // 1. Check the alignment constraint.
9390 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9391 ResVT.getTypeForEVT(*DAG->getContext()));
9392
9393 if (RequiredAlignment > getAlignment())
9394 return false;
9395
9396 // 2. Check that the load is a legal operation for that type.
9397 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9398 return false;
9399
9400 // 3. Check that we do not have a zext in the way.
9401 if (Inst->getValueType(0) != getLoadedType())
9402 return false;
9403
9404 return true;
9405 }
9406};
9407}
9408
Quentin Colombetde0e0622013-10-11 18:29:42 +00009409/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9410/// \p UsedBits looks like 0..0 1..1 0..0.
9411static bool areUsedBitsDense(const APInt &UsedBits) {
9412 // If all the bits are one, this is dense!
9413 if (UsedBits.isAllOnesValue())
9414 return true;
9415
9416 // Get rid of the unused bits on the right.
9417 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9418 // Get rid of the unused bits on the left.
9419 if (NarrowedUsedBits.countLeadingZeros())
9420 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9421 // Check that the chunk of bits is completely used.
9422 return NarrowedUsedBits.isAllOnesValue();
9423}
9424
9425/// \brief Check whether or not \p First and \p Second are next to each other
9426/// in memory. This means that there is no hole between the bits loaded
9427/// by \p First and the bits loaded by \p Second.
9428static bool areSlicesNextToEachOther(const LoadedSlice &First,
9429 const LoadedSlice &Second) {
9430 assert(First.Origin == Second.Origin && First.Origin &&
9431 "Unable to match different memory origins.");
9432 APInt UsedBits = First.getUsedBits();
9433 assert((UsedBits & Second.getUsedBits()) == 0 &&
9434 "Slices are not supposed to overlap.");
9435 UsedBits |= Second.getUsedBits();
9436 return areUsedBitsDense(UsedBits);
9437}
9438
9439/// \brief Adjust the \p GlobalLSCost according to the target
9440/// paring capabilities and the layout of the slices.
9441/// \pre \p GlobalLSCost should account for at least as many loads as
9442/// there is in the slices in \p LoadedSlices.
9443static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9444 LoadedSlice::Cost &GlobalLSCost) {
9445 unsigned NumberOfSlices = LoadedSlices.size();
9446 // If there is less than 2 elements, no pairing is possible.
9447 if (NumberOfSlices < 2)
9448 return;
9449
9450 // Sort the slices so that elements that are likely to be next to each
9451 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009452 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9453 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9454 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9455 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9456 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00009457 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9458 // First (resp. Second) is the first (resp. Second) potentially candidate
9459 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00009460 const LoadedSlice *First = nullptr;
9461 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009462 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9463 // Set the beginning of the pair.
9464 First = Second) {
9465
9466 Second = &LoadedSlices[CurrSlice];
9467
9468 // If First is NULL, it means we start a new pair.
9469 // Get to the next slice.
9470 if (!First)
9471 continue;
9472
9473 EVT LoadedType = First->getLoadedType();
9474
9475 // If the types of the slices are different, we cannot pair them.
9476 if (LoadedType != Second->getLoadedType())
9477 continue;
9478
9479 // Check if the target supplies paired loads for this type.
9480 unsigned RequiredAlignment = 0;
9481 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9482 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00009483 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009484 continue;
9485 }
9486 // Check if we meet the alignment requirement.
9487 if (RequiredAlignment > First->getAlignment())
9488 continue;
9489
9490 // Check that both loads are next to each other in memory.
9491 if (!areSlicesNextToEachOther(*First, *Second))
9492 continue;
9493
9494 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9495 --GlobalLSCost.Loads;
9496 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00009497 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009498 }
9499}
9500
9501/// \brief Check the profitability of all involved LoadedSlice.
9502/// Currently, it is considered profitable if there is exactly two
9503/// involved slices (1) which are (2) next to each other in memory, and
9504/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9505///
9506/// Note: The order of the elements in \p LoadedSlices may be modified, but not
9507/// the elements themselves.
9508///
9509/// FIXME: When the cost model will be mature enough, we can relax
9510/// constraints (1) and (2).
9511static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9512 const APInt &UsedBits, bool ForCodeSize) {
9513 unsigned NumberOfSlices = LoadedSlices.size();
9514 if (StressLoadSlicing)
9515 return NumberOfSlices > 1;
9516
9517 // Check (1).
9518 if (NumberOfSlices != 2)
9519 return false;
9520
9521 // Check (2).
9522 if (!areUsedBitsDense(UsedBits))
9523 return false;
9524
9525 // Check (3).
9526 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9527 // The original code has one big load.
9528 OrigCost.Loads = 1;
9529 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9530 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9531 // Accumulate the cost of all the slices.
9532 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9533 GlobalSlicingCost += SliceCost;
9534
9535 // Account as cost in the original configuration the gain obtained
9536 // with the current slices.
9537 OrigCost.addSliceGain(LS);
9538 }
9539
9540 // If the target supports paired load, adjust the cost accordingly.
9541 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9542 return OrigCost > GlobalSlicingCost;
9543}
9544
9545/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9546/// operations, split it in the various pieces being extracted.
9547///
9548/// This sort of thing is introduced by SROA.
9549/// This slicing takes care not to insert overlapping loads.
9550/// \pre LI is a simple load (i.e., not an atomic or volatile load).
9551bool DAGCombiner::SliceUpLoad(SDNode *N) {
9552 if (Level < AfterLegalizeDAG)
9553 return false;
9554
9555 LoadSDNode *LD = cast<LoadSDNode>(N);
9556 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9557 !LD->getValueType(0).isInteger())
9558 return false;
9559
9560 // Keep track of already used bits to detect overlapping values.
9561 // In that case, we will just abort the transformation.
9562 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9563
9564 SmallVector<LoadedSlice, 4> LoadedSlices;
9565
9566 // Check if this load is used as several smaller chunks of bits.
9567 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9568 // of computation for each trunc.
9569 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9570 UI != UIEnd; ++UI) {
9571 // Skip the uses of the chain.
9572 if (UI.getUse().getResNo() != 0)
9573 continue;
9574
9575 SDNode *User = *UI;
9576 unsigned Shift = 0;
9577
9578 // Check if this is a trunc(lshr).
9579 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9580 isa<ConstantSDNode>(User->getOperand(1))) {
9581 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9582 User = *User->use_begin();
9583 }
9584
9585 // At this point, User is a Truncate, iff we encountered, trunc or
9586 // trunc(lshr).
9587 if (User->getOpcode() != ISD::TRUNCATE)
9588 return false;
9589
9590 // The width of the type must be a power of 2 and greater than 8-bits.
9591 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00009592 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00009593 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009594 unsigned Width = User->getValueSizeInBits(0);
9595 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9596 return 0;
9597
9598 // Build the slice for this chain of computations.
9599 LoadedSlice LS(User, LD, Shift, &DAG);
9600 APInt CurrentUsedBits = LS.getUsedBits();
9601
9602 // Check if this slice overlaps with another.
9603 if ((CurrentUsedBits & UsedBits) != 0)
9604 return false;
9605 // Update the bits used globally.
9606 UsedBits |= CurrentUsedBits;
9607
9608 // Check if the new slice would be legal.
9609 if (!LS.isLegal())
9610 return false;
9611
9612 // Record the slice.
9613 LoadedSlices.push_back(LS);
9614 }
9615
9616 // Abort slicing if it does not seem to be profitable.
9617 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9618 return false;
9619
9620 ++SlicedLoads;
9621
9622 // Rewrite each chain to use an independent load.
9623 // By construction, each chain can be represented by a unique load.
9624
9625 // Prepare the argument for the new token factor for all the slices.
9626 SmallVector<SDValue, 8> ArgChains;
9627 for (SmallVectorImpl<LoadedSlice>::const_iterator
9628 LSIt = LoadedSlices.begin(),
9629 LSItEnd = LoadedSlices.end();
9630 LSIt != LSItEnd; ++LSIt) {
9631 SDValue SliceInst = LSIt->loadSlice();
9632 CombineTo(LSIt->Inst, SliceInst, true);
9633 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9634 SliceInst = SliceInst.getOperand(0);
9635 assert(SliceInst->getOpcode() == ISD::LOAD &&
9636 "It takes more than a zext to get to the loaded slice!!");
9637 ArgChains.push_back(SliceInst.getValue(1));
9638 }
9639
9640 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00009641 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00009642 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9643 return true;
9644}
9645
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009646/// Check to see if V is (and load (ptr), imm), where the load is having
9647/// specific bytes cleared out. If so, return the byte size being masked out
9648/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00009649static std::pair<unsigned, unsigned>
9650CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9651 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009652
Chris Lattner4041ab62010-04-15 04:48:01 +00009653 // Check for the structure we're looking for.
9654 if (V->getOpcode() != ISD::AND ||
9655 !isa<ConstantSDNode>(V->getOperand(1)) ||
9656 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9657 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009658
Chris Lattner3245afd2010-04-15 06:10:49 +00009659 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00009660 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00009661 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00009662
Chris Lattner3245afd2010-04-15 06:10:49 +00009663 // The store should be chained directly to the load or be an operand of a
9664 // tokenfactor.
9665 if (LD == Chain.getNode())
9666 ; // ok.
9667 else if (Chain->getOpcode() != ISD::TokenFactor)
9668 return Result; // Fail.
9669 else {
9670 bool isOk = false;
9671 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9672 if (Chain->getOperand(i).getNode() == LD) {
9673 isOk = true;
9674 break;
9675 }
9676 if (!isOk) return Result;
9677 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009678
Chris Lattner4041ab62010-04-15 04:48:01 +00009679 // This only handles simple types.
9680 if (V.getValueType() != MVT::i16 &&
9681 V.getValueType() != MVT::i32 &&
9682 V.getValueType() != MVT::i64)
9683 return Result;
9684
9685 // Check the constant mask. Invert it so that the bits being masked out are
9686 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9687 // follow the sign bit for uniformity.
9688 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009689 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009690 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009691 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009692 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9693 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00009694
Chris Lattner4041ab62010-04-15 04:48:01 +00009695 // See if we have a continuous run of bits. If so, we have 0*1+0*
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00009696 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
Chris Lattner4041ab62010-04-15 04:48:01 +00009697 return Result;
9698
9699 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9700 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9701 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00009702
Chris Lattner4041ab62010-04-15 04:48:01 +00009703 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9704 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00009705 case 1:
9706 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00009707 case 4: break;
9708 default: return Result; // All one mask, or 5-byte mask.
9709 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009710
Chris Lattner4041ab62010-04-15 04:48:01 +00009711 // Verify that the first bit starts at a multiple of mask so that the access
9712 // is aligned the same as the access width.
9713 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009714
Chris Lattner4041ab62010-04-15 04:48:01 +00009715 Result.first = MaskedBytes;
9716 Result.second = NotMaskTZ/8;
9717 return Result;
9718}
9719
9720
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009721/// Check to see if IVal is something that provides a value as specified by
9722/// MaskInfo. If so, replace the specified store with a narrower store of
9723/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00009724static SDNode *
9725ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9726 SDValue IVal, StoreSDNode *St,
9727 DAGCombiner *DC) {
9728 unsigned NumBytes = MaskInfo.first;
9729 unsigned ByteShift = MaskInfo.second;
9730 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00009731
Chris Lattner4041ab62010-04-15 04:48:01 +00009732 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9733 // that uses this. If not, this is not a replacement.
9734 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9735 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00009736 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009737
Chris Lattner4041ab62010-04-15 04:48:01 +00009738 // Check that it is legal on the target to do this. It is legal if the new
9739 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9740 // legalization.
9741 MVT VT = MVT::getIntegerVT(NumBytes*8);
9742 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00009743 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009744
Chris Lattner4041ab62010-04-15 04:48:01 +00009745 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9746 // shifted by ByteShift and truncated down to NumBytes.
9747 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009748 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00009749 DAG.getConstant(ByteShift*8,
9750 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00009751
9752 // Figure out the offset for the store and the alignment of the access.
9753 unsigned StOffset;
9754 unsigned NewAlign = St->getAlignment();
9755
9756 if (DAG.getTargetLoweringInfo().isLittleEndian())
9757 StOffset = ByteShift;
9758 else
9759 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00009760
Chris Lattner4041ab62010-04-15 04:48:01 +00009761 SDValue Ptr = St->getBasePtr();
9762 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009763 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00009764 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9765 NewAlign = MinAlign(NewAlign, StOffset);
9766 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009767
Chris Lattner4041ab62010-04-15 04:48:01 +00009768 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009769 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00009770
Chris Lattner4041ab62010-04-15 04:48:01 +00009771 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009772 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00009773 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00009774 false, false, NewAlign).getNode();
9775}
9776
Evan Chenga9cda8a2009-05-28 00:35:15 +00009777
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009778/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9779/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9780/// narrowing the load and store if it would end up being a win for performance
9781/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009782SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9783 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00009784 if (ST->isVolatile())
9785 return SDValue();
9786
Evan Chenga9cda8a2009-05-28 00:35:15 +00009787 SDValue Chain = ST->getChain();
9788 SDValue Value = ST->getValue();
9789 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009790 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009791
9792 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00009793 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009794
9795 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00009796
Chris Lattner4041ab62010-04-15 04:48:01 +00009797 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9798 // is a byte mask indicating a consecutive number of bytes, check to see if
9799 // Y is known to provide just those bytes. If so, we try to replace the
9800 // load + replace + store sequence with a single (narrower) store, which makes
9801 // the load dead.
9802 if (Opc == ISD::OR) {
9803 std::pair<unsigned, unsigned> MaskedLoad;
9804 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9805 if (MaskedLoad.first)
9806 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9807 Value.getOperand(1), ST,this))
9808 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009809
Chris Lattner4041ab62010-04-15 04:48:01 +00009810 // Or is commutative, so try swapping X and Y.
9811 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9812 if (MaskedLoad.first)
9813 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9814 Value.getOperand(0), ST,this))
9815 return SDValue(NewST, 0);
9816 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009817
Evan Chenga9cda8a2009-05-28 00:35:15 +00009818 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9819 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00009820 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009821
9822 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00009823 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9824 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00009825 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009826 if (LD->getBasePtr() != Ptr ||
9827 LD->getPointerInfo().getAddrSpace() !=
9828 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00009829 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009830
9831 // Find the type to narrow it the load / op / store to.
9832 SDValue N1 = Value.getOperand(1);
9833 unsigned BitWidth = N1.getValueSizeInBits();
9834 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9835 if (Opc == ISD::AND)
9836 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00009837 if (Imm == 0 || Imm.isAllOnesValue())
9838 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009839 unsigned ShAmt = Imm.countTrailingZeros();
9840 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9841 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00009842 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00009843 // The narrowing should be profitable, the load/store operation should be
Elena Demikhovsky9c264622015-01-22 09:39:08 +00009844 // legal (or custom) and the store size should be equal to the NewVT width.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009845 while (NewBW < BitWidth &&
Elena Demikhovsky9c264622015-01-22 09:39:08 +00009846 (NewVT.getStoreSizeInBits() != NewBW ||
9847 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9848 !TLI.isNarrowingProfitable(VT, NewVT))) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00009849 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00009850 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009851 }
Evan Cheng6673ff02009-05-28 18:41:02 +00009852 if (NewBW >= BitWidth)
9853 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009854
9855 // If the lsb changed does not start at the type bitwidth boundary,
9856 // start at the previous one.
9857 if (ShAmt % NewBW)
9858 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00009859 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9860 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009861 if ((Imm & Mask) == Imm) {
9862 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9863 if (Opc == ISD::AND)
9864 NewImm ^= APInt::getAllOnesValue(NewBW);
9865 uint64_t PtrOff = ShAmt / 8;
9866 // For big endian targets, we need to adjust the offset to the pointer to
9867 // load the correct bytes.
9868 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00009869 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00009870
9871 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00009872 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009873 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00009874 return SDValue();
9875
Andrew Trickef9de2a2013-05-25 02:42:55 +00009876 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009877 Ptr.getValueType(), Ptr,
9878 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009879 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009880 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009881 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009882 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009883 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009884 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009885 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00009886 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009887 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009888 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009889 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009890 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009891
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009892 AddToWorklist(NewPtr.getNode());
9893 AddToWorklist(NewLD.getNode());
9894 AddToWorklist(NewVal.getNode());
9895 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009896 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009897 ++OpsNarrowed;
9898 return NewST;
9899 }
9900 }
9901
Evan Cheng6673ff02009-05-28 18:41:02 +00009902 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009903}
9904
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009905/// For a given floating point load / store pair, if the load value isn't used
9906/// by any other operations, then consider transforming the pair to integer
9907/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00009908SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9909 StoreSDNode *ST = cast<StoreSDNode>(N);
9910 SDValue Chain = ST->getChain();
9911 SDValue Value = ST->getValue();
9912 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9913 Value.hasOneUse() &&
9914 Chain == SDValue(Value.getNode(), 1)) {
9915 LoadSDNode *LD = cast<LoadSDNode>(Value);
9916 EVT VT = LD->getMemoryVT();
9917 if (!VT.isFloatingPoint() ||
9918 VT != ST->getMemoryVT() ||
9919 LD->isNonTemporal() ||
9920 ST->isNonTemporal() ||
9921 LD->getPointerInfo().getAddrSpace() != 0 ||
9922 ST->getPointerInfo().getAddrSpace() != 0)
9923 return SDValue();
9924
9925 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9926 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9927 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9928 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9929 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9930 return SDValue();
9931
9932 unsigned LDAlign = LD->getAlignment();
9933 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009934 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009935 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009936 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9937 return SDValue();
9938
Andrew Trickef9de2a2013-05-25 02:42:55 +00009939 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009940 LD->getChain(), LD->getBasePtr(),
9941 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009942 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009943
Andrew Trickef9de2a2013-05-25 02:42:55 +00009944 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009945 NewLD, ST->getBasePtr(),
9946 ST->getPointerInfo(),
9947 false, false, STAlign);
9948
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009949 AddToWorklist(NewLD.getNode());
9950 AddToWorklist(NewST.getNode());
9951 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009952 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009953 ++LdStFP2Int;
9954 return NewST;
9955 }
9956
9957 return SDValue();
9958}
9959
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009960/// Helper struct to parse and store a memory address as base + index + offset.
9961/// We ignore sign extensions when it is safe to do so.
9962/// The following two expressions are not equivalent. To differentiate we need
9963/// to store whether there was a sign extension involved in the index
9964/// computation.
9965/// (load (i64 add (i64 copyfromreg %c)
9966/// (i64 signextend (add (i8 load %index)
9967/// (i8 1))))
9968/// vs
9969///
9970/// (load (i64 add (i64 copyfromreg %c)
9971/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9972/// (i32 1)))))
9973struct BaseIndexOffset {
9974 SDValue Base;
9975 SDValue Index;
9976 int64_t Offset;
9977 bool IsIndexSignExt;
9978
9979 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9980
9981 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9982 bool IsIndexSignExt) :
9983 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9984
9985 bool equalBaseIndex(const BaseIndexOffset &Other) {
9986 return Other.Base == Base && Other.Index == Index &&
9987 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009988 }
9989
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009990 /// Parses tree in Ptr for base, index, offset addresses.
9991 static BaseIndexOffset match(SDValue Ptr) {
9992 bool IsIndexSignExt = false;
9993
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009994 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9995 // instruction, then it could be just the BASE or everything else we don't
9996 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009997 if (Ptr->getOpcode() != ISD::ADD)
9998 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9999
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010000 // We know that we have at least an ADD instruction. Try to pattern match
10001 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010002 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10003 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10004 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10005 IsIndexSignExt);
10006 }
10007
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010008 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010009 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010010 // (i64 add (i64 %array_ptr)
10011 // (i64 mul (i64 %induction_var)
10012 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010013 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010014 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010015
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010016 // Look at Base + Index + Offset cases.
10017 SDValue Base = Ptr->getOperand(0);
10018 SDValue IndexOffset = Ptr->getOperand(1);
10019
10020 // Skip signextends.
10021 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10022 IndexOffset = IndexOffset->getOperand(0);
10023 IsIndexSignExt = true;
10024 }
10025
10026 // Either the case of Base + Index (no offset) or something else.
10027 if (IndexOffset->getOpcode() != ISD::ADD)
10028 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10029
10030 // Now we have the case of Base + Index + offset.
10031 SDValue Index = IndexOffset->getOperand(0);
10032 SDValue Offset = IndexOffset->getOperand(1);
10033
10034 if (!isa<ConstantSDNode>(Offset))
10035 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10036
10037 // Ignore signextends.
10038 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10039 Index = Index->getOperand(0);
10040 IsIndexSignExt = true;
10041 } else IsIndexSignExt = false;
10042
10043 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10044 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10045 }
10046};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010047
Sanjay Patel37c41c12015-01-22 18:21:26 +000010048bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10049 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
Quentin Colombet308b1712015-01-27 23:58:01 +000010050 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010051 // Make sure we have something to merge.
Quentin Colombet308b1712015-01-27 23:58:01 +000010052 if (NumElem < 2)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010053 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010054
Sanjay Patel37c41c12015-01-22 18:21:26 +000010055 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10056 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10057 unsigned EarliestNodeUsed = 0;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010058
Quentin Colombet308b1712015-01-27 23:58:01 +000010059 for (unsigned i=0; i < NumElem; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010060 // Find a chain for the new wide-store operand. Notice that some
10061 // of the store nodes that we found may not be selected for inclusion
10062 // in the wide store. The chain we use needs to be the chain of the
10063 // earliest store node which is *used* and replaced by the wide store.
10064 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10065 EarliestNodeUsed = i;
10066 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010067
Sanjay Patel37c41c12015-01-22 18:21:26 +000010068 // The earliest Node in the DAG.
10069 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10070 SDLoc DL(StoreNodes[0].MemNode);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010071
Sanjay Patel37c41c12015-01-22 18:21:26 +000010072 SDValue StoredVal;
10073 if (UseVector) {
Quentin Colombet308b1712015-01-27 23:58:01 +000010074 // Find a legal type for the vector store.
10075 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010076 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10077 if (IsConstantSrc) {
10078 // A vector store with a constant source implies that the constant is
10079 // zero; we only handle merging stores of constant zeros because the zero
10080 // can be materialized without a load.
10081 // It may be beneficial to loosen this restriction to allow non-zero
10082 // store merging.
10083 StoredVal = DAG.getConstant(0, Ty);
10084 } else {
10085 SmallVector<SDValue, 8> Ops;
Quentin Colombet308b1712015-01-27 23:58:01 +000010086 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010087 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10088 SDValue Val = St->getValue();
Quentin Colombet308b1712015-01-27 23:58:01 +000010089 // All of the operands of a BUILD_VECTOR must have the same type.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010090 if (Val.getValueType() != MemVT)
10091 return false;
10092 Ops.push_back(Val);
10093 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010094
Sanjay Patel37c41c12015-01-22 18:21:26 +000010095 // Build the extracted vector elements back into a vector.
Quentin Colombet308b1712015-01-27 23:58:01 +000010096 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010097 }
10098 } else {
10099 // We should always use a vector store when merging extracted vector
10100 // elements, so this path implies a store of constants.
10101 assert(IsConstantSrc && "Merged vector elements should use vector store");
10102
Quentin Colombet308b1712015-01-27 23:58:01 +000010103 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010104 APInt StoreInt(StoreBW, 0);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010105
Sanjay Patel37c41c12015-01-22 18:21:26 +000010106 // Construct a single integer constant which is made of the smaller
10107 // constant inputs.
10108 bool IsLE = TLI.isLittleEndian();
Quentin Colombet308b1712015-01-27 23:58:01 +000010109 for (unsigned i = 0; i < NumElem ; ++i) {
10110 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010111 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10112 SDValue Val = St->getValue();
10113 StoreInt <<= ElementSizeBytes*8;
10114 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10115 StoreInt |= C->getAPIntValue().zext(StoreBW);
10116 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10117 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10118 } else {
10119 llvm_unreachable("Invalid constant element type");
10120 }
10121 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010122
Sanjay Patel37c41c12015-01-22 18:21:26 +000010123 // Create the new Load and Store operations.
10124 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10125 StoredVal = DAG.getConstant(StoreInt, StoreTy);
10126 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010127
Sanjay Patel37c41c12015-01-22 18:21:26 +000010128 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
10129 FirstInChain->getBasePtr(),
10130 FirstInChain->getPointerInfo(),
10131 false, false,
10132 FirstInChain->getAlignment());
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010133
Sanjay Patel37c41c12015-01-22 18:21:26 +000010134 // Replace the first store with the new store
10135 CombineTo(EarliestOp, NewStore);
10136 // Erase all other stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010137 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010138 if (StoreNodes[i].MemNode == EarliestOp)
10139 continue;
10140 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10141 // ReplaceAllUsesWith will replace all uses that existed when it was
10142 // called, but graph optimizations may cause new ones to appear. For
10143 // example, the case in pr14333 looks like
10144 //
10145 // St's chain -> St -> another store -> X
10146 //
10147 // And the only difference from St to the other store is the chain.
10148 // When we change it's chain to be St's chain they become identical,
10149 // get CSEed and the net result is that X is now a use of St.
10150 // Since we know that St is redundant, just iterate.
10151 while (!St->use_empty())
10152 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10153 deleteAndRecombine(St);
10154 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010155
Sanjay Patel37c41c12015-01-22 18:21:26 +000010156 return true;
10157}
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010158
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010159bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
Paul Robinson093d6e12015-02-26 18:47:57 +000010160 if (OptLevel == CodeGenOpt::None)
10161 return false;
10162
Quentin Colombet308b1712015-01-27 23:58:01 +000010163 EVT MemVT = St->getMemoryVT();
10164 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +000010165 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10166 Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010167
Quentin Colombet308b1712015-01-27 23:58:01 +000010168 // Don't merge vectors into wider inputs.
10169 if (MemVT.isVector() || !MemVT.isSimple())
10170 return false;
10171
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010172 // Perform an early exit check. Do not bother looking at stored values that
Sanjay Patel37c41c12015-01-22 18:21:26 +000010173 // are not constants, loads, or extracted vector elements.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010174 SDValue StoredVal = St->getValue();
10175 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010176 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10177 isa<ConstantFPSDNode>(StoredVal);
Quentin Colombet308b1712015-01-27 23:58:01 +000010178 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010179
Quentin Colombet308b1712015-01-27 23:58:01 +000010180 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010181 return false;
10182
10183 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +000010184 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010185 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10186 return false;
10187
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010188 // This holds the base pointer, index, and the offset in bytes from the base
10189 // pointer.
10190 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010191
10192 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010193 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010194 return false;
10195
10196 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010197 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010198 return false;
10199
Nadav Rotem307d7672012-11-29 00:00:08 +000010200 // Save the LoadSDNodes that we find in the chain.
10201 // We need to make sure that these nodes do not interfere with
10202 // any of the store nodes.
10203 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10204
10205 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010206 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +000010207
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010208 // Walk up the chain and look for nodes with offsets from the same
10209 // base pointer. Stop when reaching an instruction with a different kind
10210 // or instruction which has a different base pointer.
10211 unsigned Seq = 0;
10212 StoreSDNode *Index = St;
10213 while (Index) {
10214 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +000010215 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010216 break;
10217
10218 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010219 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010220
10221 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010222 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010223 break;
10224
10225 // Check that the alignment is the same.
10226 if (Index->getAlignment() != St->getAlignment())
10227 break;
10228
10229 // The memory operands must not be volatile.
10230 if (Index->isVolatile() || Index->isIndexed())
10231 break;
10232
10233 // No truncation.
10234 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10235 if (St->isTruncatingStore())
10236 break;
10237
10238 // The stored memory type must be the same.
10239 if (Index->getMemoryVT() != MemVT)
10240 break;
10241
10242 // We do not allow unaligned stores because we want to prevent overriding
10243 // stores.
10244 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10245 break;
10246
10247 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010248 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010249
Nadav Rotem307d7672012-11-29 00:00:08 +000010250 // Find the next memory operand in the chain. If the next operand in the
10251 // chain is a store then move up and continue the scan with the next
10252 // memory operand. If the next operand is a load save it and use alias
10253 // information to check if it interferes with anything.
10254 SDNode *NextInChain = Index->getChain().getNode();
10255 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +000010256 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +000010257 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +000010258 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +000010259 break;
10260 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +000010261 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +000010262 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +000010263 break;
10264 }
10265
Nadav Rotem307d7672012-11-29 00:00:08 +000010266 // Save the load node for later. Continue the scan.
10267 AliasLoadNodes.push_back(Ldn);
10268 NextInChain = Ldn->getChain().getNode();
10269 continue;
10270 } else {
Craig Topperc0196b12014-04-14 00:51:57 +000010271 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +000010272 break;
10273 }
10274 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010275 }
10276
10277 // Check if there is anything to merge.
10278 if (StoreNodes.size() < 2)
10279 return false;
10280
10281 // Sort the memory operands according to their distance from the base pointer.
10282 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +000010283 [](MemOpLink LHS, MemOpLink RHS) {
10284 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10285 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10286 LHS.SequenceNum > RHS.SequenceNum);
10287 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010288
10289 // Scan the memory operations on the chain and find the first non-consecutive
10290 // store memory address.
10291 unsigned LastConsecutiveStore = 0;
10292 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +000010293 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10294
10295 // Check that the addresses are consecutive starting from the second
10296 // element in the list of stores.
10297 if (i > 0) {
10298 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10299 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10300 break;
10301 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010302
Nadav Rotem307d7672012-11-29 00:00:08 +000010303 bool Alias = false;
10304 // Check if this store interferes with any of the loads that we found.
10305 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10306 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10307 Alias = true;
10308 break;
10309 }
Nadav Rotem307d7672012-11-29 00:00:08 +000010310 // We found a load that alias with this store. Stop the sequence.
10311 if (Alias)
10312 break;
10313
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010314 // Mark this node as useful.
10315 LastConsecutiveStore = i;
10316 }
10317
10318 // The node with the lowest store address.
10319 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10320
10321 // Store the constants into memory as one consecutive store.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010322 if (IsConstantSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010323 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010324 unsigned LastLegalVectorType = 0;
10325 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010326 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10327 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10328 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010329
10330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010331 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010332 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010333 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010334 } else {
Alp Tokerf907b892013-12-05 05:44:44 +000010335 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010336 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010337 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010338
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010339 // Find a legal type for the constant store.
10340 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10341 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10342 if (TLI.isTypeLegal(StoreTy))
10343 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010344 // Or check whether a truncstore is legal.
10345 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10346 TargetLowering::TypePromoteInteger) {
10347 EVT LegalizedStoredValueTy =
10348 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10349 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10350 LastLegalType = i+1;
10351 }
Nadav Rotemb27777f2012-10-04 22:35:15 +000010352
10353 // Find a legal type for the vector store.
10354 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10355 if (TLI.isTypeLegal(Ty))
10356 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010357 }
10358
Bob Wilson3365b802012-12-20 01:36:20 +000010359 // We only use vectors if the constant is known to be zero and the
10360 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010361 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +000010362 LastLegalVectorType = 0;
10363
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010364 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +000010365 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010366 return false;
10367
Nadav Rotem495b1a42013-02-14 18:28:52 +000010368 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010369 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10370
Sanjay Patel37c41c12015-01-22 18:21:26 +000010371 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10372 true, UseVector);
10373 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010374
Sanjay Patel37c41c12015-01-22 18:21:26 +000010375 // When extracting multiple vector elements, try to store them
10376 // in one vector store rather than a sequence of scalar stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010377 if (IsExtractVecEltSrc) {
10378 unsigned NumElem = 0;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010379 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10380 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Quentin Colombet308b1712015-01-27 23:58:01 +000010381 SDValue StoredVal = St->getValue();
Sanjay Patel37c41c12015-01-22 18:21:26 +000010382 // This restriction could be loosened.
10383 // Bail out if any stored values are not elements extracted from a vector.
10384 // It should be possible to handle mixed sources, but load sources need
10385 // more careful handling (see the block of code below that handles
10386 // consecutive loads).
Quentin Colombet308b1712015-01-27 23:58:01 +000010387 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010388 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010389
Nadav Rotemb27777f2012-10-04 22:35:15 +000010390 // Find a legal type for the vector store.
Quentin Colombet308b1712015-01-27 23:58:01 +000010391 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10392 if (TLI.isTypeLegal(Ty))
10393 NumElem = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010394 }
10395
Quentin Colombet308b1712015-01-27 23:58:01 +000010396 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010397 false, true);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010398 }
10399
10400 // Below we handle the case of multiple consecutive stores that
10401 // come from multiple consecutive loads. We merge them into a single
10402 // wide load and a single wide store.
10403
10404 // Look for load nodes which are used by the stored values.
10405 SmallVector<MemOpLink, 8> LoadNodes;
10406
10407 // Find acceptable loads. Loads need to have the same chain (token factor),
10408 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010409 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010410 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10411 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10412 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10413 if (!Ld) break;
10414
10415 // Loads must only have one use.
10416 if (!Ld->hasNUsesOfValue(1, 0))
10417 break;
10418
10419 // Check that the alignment is the same as the stores.
10420 if (Ld->getAlignment() != St->getAlignment())
10421 break;
10422
10423 // The memory operands must not be volatile.
10424 if (Ld->isVolatile() || Ld->isIndexed())
10425 break;
10426
10427 // We do not accept ext loads.
10428 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10429 break;
10430
10431 // The stored memory type must be the same.
10432 if (Ld->getMemoryVT() != MemVT)
10433 break;
10434
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010435 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010436 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010437 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010438 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010439 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010440 break;
10441 } else {
10442 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010443 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010444 }
10445
10446 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010447 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010448 }
10449
10450 if (LoadNodes.size() < 2)
10451 return false;
10452
James Molloyce45be02014-08-02 14:51:24 +000010453 // If we have load/store pair instructions and we only have two values,
10454 // don't bother.
10455 unsigned RequiredAlignment;
10456 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10457 St->getAlignment() >= RequiredAlignment)
10458 return false;
10459
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010460 // Scan the memory operations on the chain and find the first non-consecutive
10461 // load memory address. These variables hold the index in the store node
10462 // array.
10463 unsigned LastConsecutiveLoad = 0;
10464 // This variable refers to the size and not index in the array.
10465 unsigned LastLegalVectorType = 0;
10466 unsigned LastLegalIntegerType = 0;
10467 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +000010468 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10469 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10470 // All loads much share the same chain.
10471 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10472 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +000010473
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010474 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10475 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10476 break;
10477 LastConsecutiveLoad = i;
10478
10479 // Find a legal type for the vector store.
10480 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10481 if (TLI.isTypeLegal(StoreTy))
10482 LastLegalVectorType = i + 1;
10483
10484 // Find a legal type for the integer store.
10485 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10486 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10487 if (TLI.isTypeLegal(StoreTy))
10488 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010489 // Or check whether a truncstore and extload is legal.
10490 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10491 TargetLowering::TypePromoteInteger) {
10492 EVT LegalizedStoredValueTy =
10493 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10494 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010495 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10496 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10497 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010498 LastLegalIntegerType = i+1;
10499 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010500 }
10501
10502 // Only use vector types if the vector type is larger than the integer type.
10503 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010504 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010505 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10506
10507 // We add +1 here because the LastXXX variables refer to location while
10508 // the NumElem refers to array/index size.
10509 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10510 NumElem = std::min(LastLegalType, NumElem);
10511
10512 if (NumElem < 2)
10513 return false;
10514
10515 // The earliest Node in the DAG.
10516 unsigned EarliestNodeUsed = 0;
10517 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10518 for (unsigned i=1; i<NumElem; ++i) {
10519 // Find a chain for the new wide-store operand. Notice that some
10520 // of the store nodes that we found may not be selected for inclusion
10521 // in the wide store. The chain we use needs to be the chain of the
10522 // earliest store node which is *used* and replaced by the wide store.
10523 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10524 EarliestNodeUsed = i;
10525 }
10526
10527 // Find if it is better to use vectors or integers to load and store
10528 // to memory.
10529 EVT JointMemOpVT;
10530 if (UseVectorTy) {
10531 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10532 } else {
10533 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10534 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10535 }
10536
Andrew Trickef9de2a2013-05-25 02:42:55 +000010537 SDLoc LoadDL(LoadNodes[0].MemNode);
10538 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010539
10540 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10541 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10542 FirstLoad->getChain(),
10543 FirstLoad->getBasePtr(),
10544 FirstLoad->getPointerInfo(),
10545 false, false, false,
10546 FirstLoad->getAlignment());
10547
10548 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10549 FirstInChain->getBasePtr(),
10550 FirstInChain->getPointerInfo(), false, false,
10551 FirstInChain->getAlignment());
10552
Nadav Rotemac920662012-10-03 19:30:31 +000010553 // Replace one of the loads with the new load.
10554 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10555 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10556 SDValue(NewLoad.getNode(), 1));
10557
10558 // Remove the rest of the load chains.
10559 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010560 // Replace all chain users of the old load nodes with the chain of the new
10561 // load node.
10562 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +000010563 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10564 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010565
Nadav Rotemac920662012-10-03 19:30:31 +000010566 // Replace the first store with the new store.
10567 CombineTo(EarliestOp, NewStore);
10568 // Erase all other stores.
10569 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010570 // Remove all Store nodes.
10571 if (StoreNodes[i].MemNode == EarliestOp)
10572 continue;
10573 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10574 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +000010575 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010576 }
10577
10578 return true;
10579}
10580
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010581SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +000010582 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010583 SDValue Chain = ST->getChain();
10584 SDValue Value = ST->getValue();
10585 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010586
Evan Chenga4cf58a2007-05-07 21:27:48 +000010587 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +000010588 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +000010589 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010590 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +000010591 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010592 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010593 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +000010594 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +000010595 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010596 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +000010597 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010598 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +000010599 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010600 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010601 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +000010602 }
Owen Andersona5192842011-04-14 17:30:49 +000010603
Chris Lattner41c80e82011-04-09 02:32:02 +000010604 // Turn 'store undef, Ptr' -> nothing.
10605 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10606 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +000010607
Nate Begeman8e20c762006-12-11 02:23:46 +000010608 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +000010609 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +000010610 // NOTE: If the original store is volatile, this transform must not increase
10611 // the number of stores. For example, on x86-32 an f64 can be stored in one
10612 // processor operation but an i64 (which is not legal) requires two. So the
10613 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +000010614 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010615 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +000010616 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +000010617 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +000010618 case MVT::f16: // We don't do this for these yet.
10619 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +000010620 case MVT::f128:
10621 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +000010622 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010623 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +000010624 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010625 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +000010626 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +000010627 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010628 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010629 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000010630 }
10631 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010632 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000010633 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000010634 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010635 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +000010636 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +000010637 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010638 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010639 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000010640 }
Owen Andersona5192842011-04-14 17:30:49 +000010641
Chris Lattner41c80e82011-04-09 02:32:02 +000010642 if (!ST->isVolatile() &&
10643 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000010644 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000010645 // argument passing. Since this is so common, custom legalize the
10646 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000010647 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +000010648 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10649 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000010650 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010651
Dan Gohman2af30632007-07-09 22:18:38 +000010652 unsigned Alignment = ST->getAlignment();
10653 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000010654 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000010655 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000010656
Andrew Trickef9de2a2013-05-25 02:42:55 +000010657 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000010658 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000010659 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010660 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010661 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +000010662 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000010663 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010664 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000010665 Ptr, ST->getPointerInfo().getWithOffset(4),
10666 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010667 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010668 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000010669 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010670 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010671
Chris Lattnerb7524b62006-12-12 04:16:14 +000010672 break;
Evan Cheng21836982006-12-11 17:25:19 +000010673 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010674 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010675 }
10676
Evan Cheng43cd9e32010-04-01 06:04:33 +000010677 // Try to infer better alignment information than the store already has.
10678 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000010679 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10680 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010681 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000010682 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010683 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000010684 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +000010685 }
10686 }
10687
Evan Chengd42641c2011-02-02 01:06:55 +000010688 // Try transforming a pair floating point load / store ops to integer
10689 // load / store ops.
10690 SDValue NewST = TransformFPLoadStorePair(N);
10691 if (NewST.getNode())
10692 return NewST;
10693
Eric Christopherf55d4712014-10-08 23:38:39 +000010694 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10695 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000010696#ifndef NDEBUG
10697 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10698 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10699 UseAA = false;
10700#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000010701 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000010702 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010703 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010704
Jim Laskey708d0db2006-10-04 16:53:27 +000010705 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000010706 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010707 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000010708
10709 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010710 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010711 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010712 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010713 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010714 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010715 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010716 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010717
Jim Laskeyd07be232006-09-25 16:29:54 +000010718 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010719 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000010720 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010721
Nate Begeman879d8f12009-09-15 00:18:30 +000010722 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010723 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000010724
Jim Laskeydcf983c2006-10-13 23:32:28 +000010725 // Don't add users to work list.
10726 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000010727 }
Jim Laskey5d19d592006-09-21 16:28:59 +000010728 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010729
Evan Cheng33157702006-11-05 09:31:14 +000010730 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000010731 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010732 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000010733
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010734 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010735 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010736 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000010737 // See if we can simplify the input to this truncstore with knowledge that
10738 // only the low bits are being used. For example:
10739 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000010740 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000010741 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010742 APInt::getLowBitsSet(
10743 Value.getValueType().getScalarType().getSizeInBits(),
10744 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010745 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000010746 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010747 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010748 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000010749
Chris Lattnerf47e3062007-10-13 06:58:48 +000010750 // Otherwise, see if we can simplify the operation with
10751 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000010752 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000010753 APInt::getLowBitsSet(
10754 Value.getValueType().getScalarType().getSizeInBits(),
10755 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010756 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000010757 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010758
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010759 // If this is a load followed by a store to the same location, then the store
10760 // is dead/noop.
10761 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010762 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010763 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000010764 // There can't be any side effects between the load and store, such as
10765 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010766 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010767 // The store is dead, remove it.
10768 return Chain;
10769 }
10770 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010771
James Molloy463db9a2014-09-27 17:02:54 +000010772 // If this is a store followed by a store with the same value to the same
10773 // location, then the store is dead/noop.
10774 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10775 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10776 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10777 ST1->isUnindexed() && !ST1->isVolatile()) {
10778 // The store is dead, remove it.
10779 return Chain;
10780 }
10781 }
10782
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010783 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10784 // truncating store. We can do this even if this is already a truncstore.
10785 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010786 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010787 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010788 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010789 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010790 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010791 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010792
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010793 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000010794 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000010795 if (!LegalTypes) {
10796 bool EverChanged = false;
10797
10798 do {
10799 // There can be multiple store sequences on the same chain.
10800 // Keep trying to merge store sequences until we are unable to do so
10801 // or until we merge the last store on the chain.
10802 bool Changed = MergeConsecutiveStores(ST);
10803 EverChanged |= Changed;
10804 if (!Changed) break;
10805 } while (ST->getOpcode() != ISD::DELETED_NODE);
10806
10807 if (EverChanged)
10808 return SDValue(N, 0);
10809 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010810
Evan Chenga9cda8a2009-05-28 00:35:15 +000010811 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000010812}
10813
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010814SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10815 SDValue InVec = N->getOperand(0);
10816 SDValue InVal = N->getOperand(1);
10817 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010818 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010819
Bob Wilson42603952010-05-19 23:42:58 +000010820 // If the inserted element is an UNDEF, just use the input vector.
10821 if (InVal.getOpcode() == ISD::UNDEF)
10822 return InVec;
10823
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010824 EVT VT = InVec.getValueType();
10825
Owen Andersonb2c80da2011-02-25 21:41:48 +000010826 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010827 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10828 return SDValue();
10829
Eli Friedmanb7910b72011-09-09 21:04:06 +000010830 // Check that we know which element is being inserted
10831 if (!isa<ConstantSDNode>(EltNo))
10832 return SDValue();
10833 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010834
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010835 // Canonicalize insert_vector_elt dag nodes.
10836 // Example:
10837 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10838 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10839 //
10840 // Do this only if the child insert_vector node has one use; also
10841 // do this only if indices are both constants and Idx1 < Idx0.
10842 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10843 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10844 unsigned OtherElt =
10845 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10846 if (Elt < OtherElt) {
10847 // Swap nodes.
10848 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10849 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010850 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010851 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10852 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10853 }
10854 }
10855
Eli Friedmanb7910b72011-09-09 21:04:06 +000010856 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10857 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10858 // vector elements.
10859 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000010860 // Do not combine these two vectors if the output vector will not replace
10861 // the input vector.
10862 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000010863 Ops.append(InVec.getNode()->op_begin(),
10864 InVec.getNode()->op_end());
10865 } else if (InVec.getOpcode() == ISD::UNDEF) {
10866 unsigned NElts = VT.getVectorNumElements();
10867 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10868 } else {
10869 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010870 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000010871
10872 // Insert the element
10873 if (Elt < Ops.size()) {
10874 // All the operands of BUILD_VECTOR must have the same type;
10875 // we enforce that here.
10876 EVT OpVT = Ops[0].getValueType();
10877 if (InVal.getValueType() != OpVT)
10878 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10879 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10880 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10881 Ops[Elt] = InVal;
10882 }
10883
10884 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000010885 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000010886}
10887
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010888SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10889 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10890 EVT ResultVT = EVE->getValueType(0);
10891 EVT VecEltVT = InVecVT.getVectorElementType();
10892 unsigned Align = OriginalLoad->getAlignment();
10893 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10894 VecEltVT.getTypeForEVT(*DAG.getContext()));
10895
10896 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10897 return SDValue();
10898
10899 Align = NewAlign;
10900
10901 SDValue NewPtr = OriginalLoad->getBasePtr();
10902 SDValue Offset;
10903 EVT PtrType = NewPtr.getValueType();
10904 MachinePointerInfo MPI;
10905 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10906 int Elt = ConstEltNo->getZExtValue();
10907 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10908 if (TLI.isBigEndian())
10909 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10910 Offset = DAG.getConstant(PtrOff, PtrType);
10911 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10912 } else {
10913 Offset = DAG.getNode(
10914 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10915 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10916 if (TLI.isBigEndian())
10917 Offset = DAG.getNode(
10918 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10919 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10920 MPI = OriginalLoad->getPointerInfo();
10921 }
10922 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10923
10924 // The replacement we need to do here is a little tricky: we need to
10925 // replace an extractelement of a load with a load.
10926 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10927 // Note that this replacement assumes that the extractvalue is the only
10928 // use of the load; that's okay because we don't want to perform this
10929 // transformation in other cases anyway.
10930 SDValue Load;
10931 SDValue Chain;
10932 if (ResultVT.bitsGT(VecEltVT)) {
10933 // If the result type of vextract is wider than the load, then issue an
10934 // extending load instead.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010935 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10936 VecEltVT)
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010937 ? ISD::ZEXTLOAD
10938 : ISD::EXTLOAD;
10939 Load = DAG.getExtLoad(
10940 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10941 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10942 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10943 Chain = Load.getValue(1);
10944 } else {
10945 Load = DAG.getLoad(
10946 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10947 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10948 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10949 Chain = Load.getValue(1);
10950 if (ResultVT.bitsLT(VecEltVT))
10951 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10952 else
10953 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10954 }
10955 WorklistRemover DeadNodes(*this);
10956 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10957 SDValue To[] = { Load, Chain };
10958 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10959 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10960 // worklist explicitly as well.
10961 AddToWorklist(Load.getNode());
10962 AddUsersToWorklist(Load.getNode()); // Add users too
10963 // Make sure to revisit this node to clean it up; it will usually be dead.
10964 AddToWorklist(EVE);
10965 ++OpsNarrowed;
10966 return SDValue(EVE, 0);
10967}
10968
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010969SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000010970 // (vextract (scalar_to_vector val, 0) -> val
10971 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010972 EVT VT = InVec.getValueType();
10973 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010974
Duncan Sands6be291a2011-05-09 08:03:33 +000010975 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10976 // Check if the result type doesn't match the inserted element type. A
10977 // SCALAR_TO_VECTOR may truncate the inserted element and the
10978 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10979 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010980 if (InOp.getValueType() != NVT) {
10981 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010982 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010983 }
10984 return InOp;
10985 }
Evan Cheng1120279a2008-05-13 08:35:03 +000010986
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010987 SDValue EltNo = N->getOperand(1);
10988 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10989
10990 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10991 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000010992 // we may introduce new vector instructions which are not backed by TD
10993 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000010994 // without using extract_subvector. However, if we can find an underlying
10995 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010996 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000010997 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010998 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10999 int NumElem = VT.getVectorNumElements();
11000 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11001 // Find the new index to extract from.
11002 int OrigElt = SVOp->getMaskElt(Elt);
11003
11004 // Extracting an undef index is undef.
11005 if (OrigElt == -1)
11006 return DAG.getUNDEF(NVT);
11007
11008 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000011009 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011010 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000011011 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011012 } else {
Hal Finkel02807592014-03-31 11:43:19 +000011013 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011014 OrigElt -= NumElem;
11015 }
11016
Hal Finkel02807592014-03-31 11:43:19 +000011017 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11018 SDValue InOp = SVInVec.getOperand(OrigElt);
11019 if (InOp.getValueType() != NVT) {
11020 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11021 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11022 }
11023
11024 return InOp;
11025 }
11026
11027 // FIXME: We should handle recursing on other vector shuffles and
11028 // scalar_to_vector here as well.
11029
11030 if (!LegalOperations) {
11031 EVT IndexTy = TLI.getVectorIdxTy();
11032 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
11033 SVInVec, DAG.getConstant(OrigElt, IndexTy));
11034 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011035 }
11036
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011037 bool BCNumEltsChanged = false;
11038 EVT ExtVT = VT.getVectorElementType();
11039 EVT LVT = ExtVT;
11040
11041 // If the result of load has to be truncated, then it's not necessarily
11042 // profitable.
11043 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11044 return SDValue();
11045
11046 if (InVec.getOpcode() == ISD::BITCAST) {
11047 // Don't duplicate a load with other uses.
11048 if (!InVec.hasOneUse())
11049 return SDValue();
11050
11051 EVT BCVT = InVec.getOperand(0).getValueType();
11052 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11053 return SDValue();
11054 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11055 BCNumEltsChanged = true;
11056 InVec = InVec.getOperand(0);
11057 ExtVT = BCVT.getVectorElementType();
11058 }
11059
11060 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11061 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11062 ISD::isNormalLoad(InVec.getNode()) &&
11063 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11064 SDValue Index = N->getOperand(1);
11065 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11066 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11067 OrigLoad);
11068 }
11069
Evan Cheng1120279a2008-05-13 08:35:03 +000011070 // Perform only after legalization to ensure build_vector / vector_shuffle
11071 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011072 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011073
Mon P Wangca6d6de2009-01-17 00:07:25 +000011074 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11075 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11076 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000011077
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011078 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000011079 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011080
Craig Topperc0196b12014-04-14 00:51:57 +000011081 LoadSDNode *LN0 = nullptr;
11082 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000011083 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011084 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000011085 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000011086 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000011087 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000011088 // Don't duplicate a load with other uses.
11089 if (!InVec.hasOneUse())
11090 return SDValue();
11091
Evan Cheng1120279a2008-05-13 08:35:03 +000011092 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000011093 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011094 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11095 // =>
11096 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000011097
Eli Friedmane96286c2011-12-26 22:49:32 +000011098 // Don't duplicate a load with other uses.
11099 if (!InVec.hasOneUse())
11100 return SDValue();
11101
Mon P Wangb5eb7202008-12-11 00:26:16 +000011102 // If the bit convert changed the number of elements, it is unsafe
11103 // to examine the mask.
11104 if (BCNumEltsChanged)
11105 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000011106
11107 // Select the input vector, guarding against out of range extract vector.
11108 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000011109 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000011110 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11111
Eli Friedmane96286c2011-12-26 22:49:32 +000011112 if (InVec.getOpcode() == ISD::BITCAST) {
11113 // Don't duplicate a load with other uses.
11114 if (!InVec.hasOneUse())
11115 return SDValue();
11116
Evan Cheng1120279a2008-05-13 08:35:03 +000011117 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000011118 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000011119 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011120 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000011121 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011122 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000011123 }
11124 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011125
Eli Friedmane96286c2011-12-26 22:49:32 +000011126 // Make sure we found a non-volatile load and the extractelement is
11127 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000011128 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011129 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011130
Eric Christopherc6418b12010-11-03 20:44:42 +000011131 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11132 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000011133 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000011134
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011135 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000011136 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011137
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011138 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011139}
Evan Cheng0de312d2007-10-06 08:19:55 +000011140
Michael Liao6d106b72012-10-23 23:06:52 +000011141// Simplify (build_vec (ext )) to (bitcast (build_vec ))
11142SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11143 // We perform this optimization post type-legalization because
11144 // the type-legalizer often scalarizes integer-promoted vectors.
11145 // Performing this optimization before may create bit-casts which
11146 // will be type-legalized to complex code sequences.
11147 // We perform this optimization only before the operation legalizer because we
11148 // may introduce illegal operations.
11149 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11150 return SDValue();
11151
Dan Gohmana8665142007-06-25 16:23:39 +000011152 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011153 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000011154 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011155
Nadav Rotembf6568b2011-10-29 21:23:04 +000011156 // Check to see if this is a BUILD_VECTOR of a bunch of values
11157 // which come from any_extend or zero_extend nodes. If so, we can create
11158 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000011159 // optimizations. We do not handle sign-extend because we can't fill the sign
11160 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011161 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000011162 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000011163
Craig Topper02cb0fb2012-01-17 09:09:48 +000011164 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000011165 SDValue In = N->getOperand(i);
11166 // Ignore undef inputs.
11167 if (In.getOpcode() == ISD::UNDEF) continue;
11168
11169 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11170 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11171
Nadav Rotemf3103612011-10-31 20:08:25 +000011172 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011173 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000011174 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011175 break;
11176 }
11177
11178 // The input is a ZeroExt or AnyExt. Check the original type.
11179 EVT InTy = In.getOperand(0).getValueType();
11180
11181 // Check that all of the widened source types are the same.
11182 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000011183 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011184 SourceType = InTy;
11185 else if (InTy != SourceType) {
11186 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000011187 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011188 break;
11189 }
11190
11191 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000011192 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011193 }
11194
Nadav Rotemf3103612011-10-31 20:08:25 +000011195 // In order to have valid types, all of the inputs must be extended from the
11196 // same source type and all of the inputs must be any or zero extend.
11197 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000011198 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011199 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000011200 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11201 isPowerOf2_32(SourceType.getSizeInBits());
11202
Nadav Rotem6fd1d322012-03-15 08:49:06 +000011203 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11204 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000011205 if (!ValidTypes)
11206 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000011207
Michael Liao6d106b72012-10-23 23:06:52 +000011208 bool isLE = TLI.isLittleEndian();
11209 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11210 assert(ElemRatio > 1 && "Invalid element size ratio");
11211 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11212 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011213
Michael Liao6d106b72012-10-23 23:06:52 +000011214 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11215 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011216
Michael Liao6d106b72012-10-23 23:06:52 +000011217 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000011218 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000011219 SDValue Cast = N->getOperand(i);
11220 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11221 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11222 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11223 SDValue In;
11224 if (Cast.getOpcode() == ISD::UNDEF)
11225 In = DAG.getUNDEF(SourceType);
11226 else
11227 In = Cast->getOperand(0);
11228 unsigned Index = isLE ? (i * ElemRatio) :
11229 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000011230
Michael Liao6d106b72012-10-23 23:06:52 +000011231 assert(Index < Ops.size() && "Invalid index");
11232 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011233 }
Chris Lattner5336a592006-03-19 01:27:56 +000011234
Michael Liao6d106b72012-10-23 23:06:52 +000011235 // The type of the new BUILD_VECTOR node.
11236 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11237 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11238 "Invalid vector size");
11239 // Check if the new vector type is legal.
11240 if (!isTypeLegal(VecVT)) return SDValue();
11241
11242 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000011243 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000011244
11245 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011246 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000011247 // Bitcast to the desired type.
11248 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11249}
11250
Michael Liao59229792012-10-24 04:14:18 +000011251SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11252 EVT VT = N->getValueType(0);
11253
11254 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011255 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000011256
11257 EVT SrcVT = MVT::Other;
11258 unsigned Opcode = ISD::DELETED_NODE;
11259 unsigned NumDefs = 0;
11260
11261 for (unsigned i = 0; i != NumInScalars; ++i) {
11262 SDValue In = N->getOperand(i);
11263 unsigned Opc = In.getOpcode();
11264
11265 if (Opc == ISD::UNDEF)
11266 continue;
11267
11268 // If all scalar values are floats and converted from integers.
11269 if (Opcode == ISD::DELETED_NODE &&
11270 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11271 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000011272 }
Tom Stellard567f8862013-01-02 22:13:01 +000011273
Michael Liao59229792012-10-24 04:14:18 +000011274 if (Opc != Opcode)
11275 return SDValue();
11276
11277 EVT InVT = In.getOperand(0).getValueType();
11278
11279 // If all scalar values are typed differently, bail out. It's chosen to
11280 // simplify BUILD_VECTOR of integer types.
11281 if (SrcVT == MVT::Other)
11282 SrcVT = InVT;
11283 if (SrcVT != InVT)
11284 return SDValue();
11285 NumDefs++;
11286 }
11287
11288 // If the vector has just one element defined, it's not worth to fold it into
11289 // a vectorized one.
11290 if (NumDefs < 2)
11291 return SDValue();
11292
11293 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11294 && "Should only handle conversion from integer to float.");
11295 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11296
11297 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000011298
11299 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11300 return SDValue();
11301
Hal Finkele2dd84e2015-02-22 16:10:22 +000011302 // Just because the floating-point vector type is legal does not necessarily
11303 // mean that the corresponding integer vector type is.
11304 if (!isTypeLegal(NVT))
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011305 return SDValue();
Hal Finkele2dd84e2015-02-22 16:10:22 +000011306
Michael Liao59229792012-10-24 04:14:18 +000011307 SmallVector<SDValue, 8> Opnds;
11308 for (unsigned i = 0; i != NumInScalars; ++i) {
11309 SDValue In = N->getOperand(i);
11310
11311 if (In.getOpcode() == ISD::UNDEF)
11312 Opnds.push_back(DAG.getUNDEF(SrcVT));
11313 else
11314 Opnds.push_back(In.getOperand(0));
11315 }
Craig Topper48d114b2014-04-26 18:35:24 +000011316 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011317 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000011318
11319 return DAG.getNode(Opcode, dl, VT, BV);
11320}
11321
Michael Liao6d106b72012-10-23 23:06:52 +000011322SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11323 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011324 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000011325 EVT VT = N->getValueType(0);
11326
11327 // A vector built entirely of undefs is undef.
11328 if (ISD::allOperandsUndef(N))
11329 return DAG.getUNDEF(VT);
11330
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011331 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
Michael Liao6d106b72012-10-23 23:06:52 +000011332 return V;
11333
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011334 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
Michael Liao59229792012-10-24 04:14:18 +000011335 return V;
11336
Dan Gohmana8665142007-06-25 16:23:39 +000011337 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11338 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11339 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011340
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000011341 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11342 if (!isTypeLegal(VT))
11343 return SDValue();
11344
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011345 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000011346 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011347 return SDValue();
11348
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011349 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011350 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000011351 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011352 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000011353 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011354 if (Op.getOpcode() == ISD::UNDEF) continue;
11355
11356 // See if we can combine this build_vector into a blend with a zero vector.
11357 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11358 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11359 (Op.getOpcode() == ISD::ConstantFP &&
11360 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11361 UsesZeroVector = true;
11362 continue;
11363 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011364
Dan Gohmana8665142007-06-25 16:23:39 +000011365 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000011366 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011367 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11368 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000011369 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011370 break;
11371 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011372
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011373 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011374 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011375 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11376 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011377
Craig Topperc0196b12014-04-14 00:51:57 +000011378 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011379 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011380 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011381 VecIn2 = ExtractedFromVec;
11382 } else {
11383 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000011384 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011385 break;
11386 }
11387 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011388
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000011389 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011390 if (VecIn1.getNode()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011391 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011392 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000011393 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011394 unsigned Opcode = N->getOperand(i).getOpcode();
11395 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011396 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000011397 continue;
11398 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011399
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011400 // Operands can also be zero.
11401 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11402 assert(UsesZeroVector &&
11403 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11404 "Unexpected node found!");
11405 Mask.push_back(NumInScalars+i);
11406 continue;
11407 }
11408
Rafael Espindolab93db662009-04-24 12:40:33 +000011409 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011410 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000011411 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011412 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011413 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000011414 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011415 continue;
11416 }
11417
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011418 // Otherwise, use InIdx + InputVecSize
11419 Mask.push_back(InNumElements + ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011420 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011421
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011422 // Avoid introducing illegal shuffles with zero.
11423 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11424 return SDValue();
11425
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011426 // We can't generate a shuffle node with mismatched input and output types.
11427 // Attempt to transform a single input vector to the correct type.
11428 if ((VT != VecIn1.getValueType())) {
James Molloy1e5c6112012-09-10 14:01:21 +000011429 // If the input vector type has a different base type to the output
11430 // vector type, bail out.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011431 EVT VTElemType = VT.getVectorElementType();
11432 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11433 (VecIn2.getNode() &&
11434 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
James Molloy1e5c6112012-09-10 14:01:21 +000011435 return SDValue();
11436
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011437 // If the input vector is too small, widen it.
11438 // We only support widening of vectors which are half the size of the
11439 // output registers. For example XMM->YMM widening on X86 with AVX.
11440 EVT VecInT = VecIn1.getValueType();
11441 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011442 // If we only have one small input, widen it by adding undef values.
11443 if (!VecIn2.getNode())
11444 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11445 DAG.getUNDEF(VecIn1.getValueType()));
11446 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11447 // If we have two small inputs of the same type, try to concat them.
11448 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11449 VecIn2 = SDValue(nullptr, 0);
11450 } else
11451 return SDValue();
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011452 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11453 // If the input vector is too large, try to split it.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011454 // We don't support having two input vectors that are too large.
Michael Kupersteinfb956972015-03-04 07:27:39 +000011455 // If the zero vector was used, we can not split the vector,
11456 // since we'd need 3 inputs.
11457 if (UsesZeroVector || VecIn2.getNode())
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011458 return SDValue();
11459
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011460 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11461 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011462
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011463 // Try to replace VecIn1 with two extract_subvectors
11464 // No need to update the masks, they should still be correct.
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011465 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011466 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11467 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11468 DAG.getConstant(0, TLI.getVectorIdxTy()));
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011469 } else
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011470 return SDValue();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011471 }
11472
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011473 if (UsesZeroVector)
11474 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11475 DAG.getConstantFP(0.0, VT);
11476 else
11477 // If VecIn2 is unused then change it to undef.
11478 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011479
Nadav Rotem841c9a82012-09-20 08:53:31 +000011480 // Check that we were able to transform all incoming values to the same
11481 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000011482 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11483 VecIn1.getValueType() != VT)
11484 return SDValue();
11485
Dan Gohmana8665142007-06-25 16:23:39 +000011486 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011487 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000011488 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011489 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000011490 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000011491 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011492
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011493 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011494}
11495
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011496SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000011497 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11498 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11499 // inputs come from at most two distinct vectors, turn this into a shuffle
11500 // node.
11501
11502 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000011503 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000011504 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011505
Nadav Rotem01892102012-07-14 21:30:27 +000011506 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011507 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011508 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011509 return DAG.getUNDEF(VT);
11510
11511 // Optimize concat_vectors where one of the vectors is undef.
11512 if (N->getNumOperands() == 2 &&
11513 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11514 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000011515 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011516
11517 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11518 if (In->getOpcode() == ISD::BITCAST &&
11519 !In->getOperand(0)->getValueType(0).isVector()) {
11520 SDValue Scalar = In->getOperand(0);
11521 EVT SclTy = Scalar->getValueType(0);
11522
11523 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11524 return SDValue();
11525
11526 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11527 VT.getSizeInBits() / SclTy.getSizeInBits());
11528 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11529 return SDValue();
11530
11531 SDLoc dl = SDLoc(N);
11532 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11533 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11534 }
11535 }
Nadav Rotem01892102012-07-14 21:30:27 +000011536
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011537 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
11538 // We have already tested above for an UNDEF only concatenation.
Robert Lougher7d9084f2014-02-11 15:42:46 +000011539 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11540 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011541 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
11542 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
11543 };
11544 bool AllBuildVectorsOrUndefs =
11545 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
11546 if (AllBuildVectorsOrUndefs) {
Robert Lougher7d9084f2014-02-11 15:42:46 +000011547 SmallVector<SDValue, 8> Opnds;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011548 EVT SVT = VT.getScalarType();
Robert Lougher7d9084f2014-02-11 15:42:46 +000011549
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011550 EVT MinVT = SVT;
11551 if (!SVT.isFloatingPoint()) {
Hao Liu71224b02014-07-10 03:41:50 +000011552 // If BUILD_VECTOR are from built from integer, they may have different
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011553 // operand types. Get the smallest type and truncate all operands to it.
11554 bool FoundMinVT = false;
11555 for (const SDValue &Op : N->ops())
11556 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11557 EVT OpSVT = Op.getOperand(0)->getValueType(0);
11558 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
11559 FoundMinVT = true;
11560 }
11561 assert(FoundMinVT && "Concat vector type mismatch");
Hao Liu71224b02014-07-10 03:41:50 +000011562 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000011563
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011564 for (const SDValue &Op : N->ops()) {
11565 EVT OpVT = Op.getValueType();
11566 unsigned NumElts = OpVT.getVectorNumElements();
11567
11568 if (ISD::UNDEF == Op.getOpcode())
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000011569 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011570
11571 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
11572 if (SVT.isFloatingPoint()) {
11573 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000011574 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011575 } else {
11576 for (unsigned i = 0; i != NumElts; ++i)
11577 Opnds.push_back(
11578 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
11579 }
11580 }
11581 }
11582
11583 assert(VT.getVectorNumElements() == Opnds.size() &&
11584 "Concat vector type mismatch");
Craig Topper48d114b2014-04-26 18:35:24 +000011585 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000011586 }
11587
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011588 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11589 // nodes often generate nop CONCAT_VECTOR nodes.
11590 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11591 // place the incoming vectors at the exact same location.
11592 SDValue SingleSource = SDValue();
11593 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11594
11595 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11596 SDValue Op = N->getOperand(i);
11597
11598 if (Op.getOpcode() == ISD::UNDEF)
11599 continue;
11600
11601 // Check if this is the identity extract:
11602 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11603 return SDValue();
11604
11605 // Find the single incoming vector for the extract_subvector.
11606 if (SingleSource.getNode()) {
11607 if (Op.getOperand(0) != SingleSource)
11608 return SDValue();
11609 } else {
11610 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000011611
11612 // Check the source type is the same as the type of the result.
11613 // If not, this concat may extend the vector, so we can not
11614 // optimize it away.
11615 if (SingleSource.getValueType() != N->getValueType(0))
11616 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011617 }
11618
11619 unsigned IdentityIndex = i * PartNumElem;
11620 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11621 // The extract index must be constant.
11622 if (!CS)
11623 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000011624
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011625 // Check that we are reading from the identity index.
11626 if (CS->getZExtValue() != IdentityIndex)
11627 return SDValue();
11628 }
11629
11630 if (SingleSource.getNode())
11631 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000011632
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011633 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000011634}
11635
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011636SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11637 EVT NVT = N->getValueType(0);
11638 SDValue V = N->getOperand(0);
11639
Michael Liao7a442c802012-10-17 20:48:33 +000011640 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11641 // Combine:
11642 // (extract_subvec (concat V1, V2, ...), i)
11643 // Into:
11644 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000011645 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11646 // type.
Michael Liao2c235802012-10-19 03:17:00 +000011647 if (V->getOperand(0).getValueType() != NVT)
11648 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000011649 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11650 unsigned NumElems = NVT.getVectorNumElements();
11651 assert((Idx % NumElems) == 0 &&
11652 "IDX in concat is not a multiple of the result vector length.");
11653 return V->getOperand(Idx / NumElems);
11654 }
11655
Michael Liaobb05a1d2013-03-25 23:47:35 +000011656 // Skip bitcasting
11657 if (V->getOpcode() == ISD::BITCAST)
11658 V = V.getOperand(0);
11659
11660 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011661 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000011662 // Handle only simple case where vector being inserted and vector
11663 // being extracted are of same type, and are half size of larger vectors.
11664 EVT BigVT = V->getOperand(0).getValueType();
11665 EVT SmallVT = V->getOperand(1).getValueType();
11666 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11667 return SDValue();
11668
11669 // Only handle cases where both indexes are constants with the same type.
11670 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11671 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11672
11673 if (InsIdx && ExtIdx &&
11674 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11675 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11676 // Combine:
11677 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11678 // Into:
11679 // indices are equal or bit offsets are equal => V1
11680 // otherwise => (extract_subvec V1, ExtIdx)
11681 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11682 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11683 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11684 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11685 DAG.getNode(ISD::BITCAST, dl,
11686 N->getOperand(0).getValueType(),
11687 V->getOperand(0)), N->getOperand(1));
11688 }
11689 }
11690
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011691 return SDValue();
11692}
11693
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011694static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11695 SDValue V, SelectionDAG &DAG) {
11696 SDLoc DL(V);
11697 EVT VT = V.getValueType();
11698
11699 switch (V.getOpcode()) {
11700 default:
11701 return V;
11702
11703 case ISD::CONCAT_VECTORS: {
11704 EVT OpVT = V->getOperand(0).getValueType();
11705 int OpSize = OpVT.getVectorNumElements();
11706 SmallBitVector OpUsedElements(OpSize, false);
11707 bool FoundSimplification = false;
11708 SmallVector<SDValue, 4> NewOps;
11709 NewOps.reserve(V->getNumOperands());
11710 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11711 SDValue Op = V->getOperand(i);
11712 bool OpUsed = false;
11713 for (int j = 0; j < OpSize; ++j)
11714 if (UsedElements[i * OpSize + j]) {
11715 OpUsedElements[j] = true;
11716 OpUsed = true;
11717 }
11718 NewOps.push_back(
11719 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11720 : DAG.getUNDEF(OpVT));
11721 FoundSimplification |= Op == NewOps.back();
11722 OpUsedElements.reset();
11723 }
11724 if (FoundSimplification)
11725 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11726 return V;
11727 }
11728
11729 case ISD::INSERT_SUBVECTOR: {
11730 SDValue BaseV = V->getOperand(0);
11731 SDValue SubV = V->getOperand(1);
11732 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11733 if (!IdxN)
11734 return V;
11735
11736 int SubSize = SubV.getValueType().getVectorNumElements();
11737 int Idx = IdxN->getZExtValue();
11738 bool SubVectorUsed = false;
11739 SmallBitVector SubUsedElements(SubSize, false);
11740 for (int i = 0; i < SubSize; ++i)
11741 if (UsedElements[i + Idx]) {
11742 SubVectorUsed = true;
11743 SubUsedElements[i] = true;
11744 UsedElements[i + Idx] = false;
11745 }
11746
11747 // Now recurse on both the base and sub vectors.
11748 SDValue SimplifiedSubV =
11749 SubVectorUsed
11750 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11751 : DAG.getUNDEF(SubV.getValueType());
11752 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11753 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11754 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11755 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11756 return V;
11757 }
11758 }
11759}
11760
11761static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11762 SDValue N1, SelectionDAG &DAG) {
11763 EVT VT = SVN->getValueType(0);
11764 int NumElts = VT.getVectorNumElements();
11765 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11766 for (int M : SVN->getMask())
11767 if (M >= 0 && M < NumElts)
11768 N0UsedElements[M] = true;
11769 else if (M >= NumElts)
11770 N1UsedElements[M - NumElts] = true;
11771
11772 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11773 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11774 if (S0 == N0 && S1 == N1)
11775 return SDValue();
11776
11777 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11778}
11779
Mehdi Amini37f316a2015-01-17 01:35:56 +000011780// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11781// or turn a shuffle of a single concat into simpler shuffle then concat.
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011782static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11783 EVT VT = N->getValueType(0);
11784 unsigned NumElts = VT.getVectorNumElements();
11785
11786 SDValue N0 = N->getOperand(0);
11787 SDValue N1 = N->getOperand(1);
11788 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11789
11790 SmallVector<SDValue, 4> Ops;
11791 EVT ConcatVT = N0.getOperand(0).getValueType();
11792 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11793 unsigned NumConcats = NumElts / NumElemsPerConcat;
11794
Mehdi Amini37f316a2015-01-17 01:35:56 +000011795 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11796 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11797 // half vector elements.
11798 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11799 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11800 SVN->getMask().end(), [](int i) { return i == -1; })) {
11801 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11802 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11803 N1 = DAG.getUNDEF(ConcatVT);
11804 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11805 }
11806
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011807 // Look at every vector that's inserted. We're looking for exact
11808 // subvector-sized copies from a concatenated vector
11809 for (unsigned I = 0; I != NumConcats; ++I) {
11810 // Make sure we're dealing with a copy.
11811 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000011812 bool AllUndef = true, NoUndef = true;
11813 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11814 if (SVN->getMaskElt(J) >= 0)
11815 AllUndef = false;
11816 else
11817 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011818 }
11819
Hao Liubc601962013-05-13 02:07:05 +000011820 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000011821 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11822 return SDValue();
11823
11824 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11825 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11826 return SDValue();
11827
11828 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11829 if (FirstElt < N0.getNumOperands())
11830 Ops.push_back(N0.getOperand(FirstElt));
11831 else
11832 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11833
11834 } else if (AllUndef) {
11835 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11836 } else { // Mixed with general masks and undefs, can't do optimization.
11837 return SDValue();
11838 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011839 }
11840
Craig Topper48d114b2014-04-26 18:35:24 +000011841 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011842}
11843
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011844SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011845 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011846 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011847
Mon P Wang25f01062008-11-10 04:46:22 +000011848 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000011849 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000011850
Craig Topper5894fe42012-04-09 05:16:56 +000011851 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000011852
Craig Topper279c77b2012-01-04 08:07:43 +000011853 // Canonicalize shuffle undef, undef -> undef
11854 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11855 return DAG.getUNDEF(VT);
11856
11857 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11858
11859 // Canonicalize shuffle v, v -> v, undef
11860 if (N0 == N1) {
11861 SmallVector<int, 8> NewMask;
11862 for (unsigned i = 0; i != NumElts; ++i) {
11863 int Idx = SVN->getMaskElt(i);
11864 if (Idx >= (int)NumElts) Idx -= NumElts;
11865 NewMask.push_back(Idx);
11866 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011867 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011868 &NewMask[0]);
11869 }
11870
11871 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11872 if (N0.getOpcode() == ISD::UNDEF) {
11873 SmallVector<int, 8> NewMask;
11874 for (unsigned i = 0; i != NumElts; ++i) {
11875 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000011876 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000011877 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000011878 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000011879 else
11880 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000011881 }
11882 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000011883 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011884 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011885 &NewMask[0]);
11886 }
11887
11888 // Remove references to rhs if it is undef
11889 if (N1.getOpcode() == ISD::UNDEF) {
11890 bool Changed = false;
11891 SmallVector<int, 8> NewMask;
11892 for (unsigned i = 0; i != NumElts; ++i) {
11893 int Idx = SVN->getMaskElt(i);
11894 if (Idx >= (int)NumElts) {
11895 Idx = -1;
11896 Changed = true;
11897 }
11898 NewMask.push_back(Idx);
11899 }
11900 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000011901 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000011902 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000011903
Bob Wilsonf63da122010-10-28 17:06:14 +000011904 // If it is a splat, check if the argument vector is another splat or a
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011905 // build_vector.
Bob Wilsonf63da122010-10-28 17:06:14 +000011906 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000011907 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000011908
Dan Gohmana8665142007-06-25 16:23:39 +000011909 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000011910 // not the number of vector elements, look through it. Be careful not to
11911 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000011912 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011913 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000011914 if (ConvInput.getValueType().isVector() &&
11915 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011916 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000011917 }
11918
Dan Gohmana8665142007-06-25 16:23:39 +000011919 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000011920 assert(V->getNumOperands() == NumElts &&
11921 "BUILD_VECTOR has wrong number of operands");
11922 SDValue Base;
11923 bool AllSame = true;
11924 for (unsigned i = 0; i != NumElts; ++i) {
11925 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11926 Base = V->getOperand(i);
11927 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000011928 }
Evan Cheng7c970b92006-07-21 08:25:53 +000011929 }
Bob Wilsonf63da122010-10-28 17:06:14 +000011930 // Splat of <u, u, u, u>, return <u, u, u, u>
11931 if (!Base.getNode())
11932 return N0;
11933 for (unsigned i = 0; i != NumElts; ++i) {
11934 if (V->getOperand(i) != Base) {
11935 AllSame = false;
11936 break;
11937 }
11938 }
11939 // Splat of <x, x, x, x>, return <x, x, x, x>
11940 if (AllSame)
11941 return N0;
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011942
Sanjay Patelab7e86e2015-02-17 16:54:32 +000011943 // Canonicalize any other splat as a build_vector.
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011944 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
Sanjay Patelab7e86e2015-02-17 16:54:32 +000011945 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
11946 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11947 V->getValueType(0), Ops);
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011948
Sanjay Patelab7e86e2015-02-17 16:54:32 +000011949 // We may have jumped through bitcasts, so the type of the
11950 // BUILD_VECTOR may not match the type of the shuffle.
11951 if (V->getValueType(0) != VT)
11952 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11953 return NewBV;
Evan Cheng7c970b92006-07-21 08:25:53 +000011954 }
11955 }
Nadav Rotemb0783502012-04-01 19:31:22 +000011956
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011957 // There are various patterns used to build up a vector from smaller vectors,
11958 // subvectors, or elements. Scan chains of these and replace unused insertions
11959 // or components with undef.
11960 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11961 return S;
11962
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011963 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11964 Level < AfterLegalizeVectorOps &&
11965 (N1.getOpcode() == ISD::UNDEF ||
11966 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11967 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11968 SDValue V = partitionShuffleOfConcats(N, DAG);
11969
11970 if (V.getNode())
11971 return V;
11972 }
11973
Simon Pilgrim7189084b2015-03-05 17:14:04 +000011974 // If this shuffle only has a single input that is a bitcasted shuffle,
11975 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
11976 // back to their original types.
11977 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
11978 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
11979 TLI.isTypeLegal(VT)) {
11980
11981 // Peek through the bitcast only if there is one user.
11982 SDValue BC0 = N0;
11983 while (BC0.getOpcode() == ISD::BITCAST) {
11984 if (!BC0.hasOneUse())
11985 break;
11986 BC0 = BC0.getOperand(0);
11987 }
11988
11989 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
11990 if (Scale == 1)
11991 return SmallVector<int, 8>(Mask.begin(), Mask.end());
11992
11993 SmallVector<int, 8> NewMask;
11994 for (int M : Mask)
11995 for (int s = 0; s != Scale; ++s)
11996 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
11997 return NewMask;
11998 };
11999
12000 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12001 EVT SVT = VT.getScalarType();
12002 EVT InnerVT = BC0->getValueType(0);
12003 EVT InnerSVT = InnerVT.getScalarType();
12004
12005 // Determine which shuffle works with the smaller scalar type.
12006 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12007 EVT ScaleSVT = ScaleVT.getScalarType();
12008
12009 if (TLI.isTypeLegal(ScaleVT) &&
12010 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12011 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12012
12013 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12014 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12015
12016 // Scale the shuffle masks to the smaller scalar type.
12017 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12018 SmallVector<int, 8> InnerMask =
12019 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12020 SmallVector<int, 8> OuterMask =
12021 ScaleShuffleMask(SVN->getMask(), OuterScale);
12022
12023 // Merge the shuffle masks.
12024 SmallVector<int, 8> NewMask;
12025 for (int M : OuterMask)
12026 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12027
12028 // Test for shuffle mask legality over both commutations.
12029 SDValue SV0 = BC0->getOperand(0);
12030 SDValue SV1 = BC0->getOperand(1);
12031 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12032 if (!LegalMask) {
12033 for (int i = 0, e = (int)NewMask.size(); i != e; ++i) {
12034 int idx = NewMask[i];
12035 if (idx < 0)
12036 continue;
12037 else if (idx < e)
12038 NewMask[i] = idx + e;
12039 else
12040 NewMask[i] = idx - e;
12041 }
12042 std::swap(SV0, SV1);
12043 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12044 }
12045
12046 if (LegalMask) {
12047 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12048 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12049 return DAG.getNode(
12050 ISD::BITCAST, SDLoc(N), VT,
12051 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12052 }
12053 }
12054 }
12055 }
12056
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012057 // Canonicalize shuffles according to rules:
12058 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12059 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12060 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012061 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012062 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12063 TLI.isTypeLegal(VT)) {
12064 // The incoming shuffle must be of the same type as the result of the
12065 // current shuffle.
12066 assert(N1->getOperand(0).getValueType() == VT &&
12067 "Shuffle types don't match");
12068
12069 SDValue SV0 = N1->getOperand(0);
12070 SDValue SV1 = N1->getOperand(1);
12071 bool HasSameOp0 = N0 == SV0;
12072 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12073 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12074 // Commute the operands of this shuffle so that next rule
12075 // will trigger.
12076 return DAG.getCommutedVectorShuffle(*SVN);
12077 }
12078
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012079 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012080 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12081 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12082 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012083 // Don't try to fold shuffles with illegal type.
Chandler Carruth499d7332015-02-15 07:01:10 +000012084 // Only fold if this shuffle is the only user of the other shuffle.
12085 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12086 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012087 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12088
12089 // The incoming shuffle must be of the same type as the result of the
12090 // current shuffle.
12091 assert(OtherSV->getOperand(0).getValueType() == VT &&
12092 "Shuffle types don't match");
12093
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012094 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012095 SmallVector<int, 4> Mask;
12096 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12097 // operand, and SV1 as the second operand.
12098 for (unsigned i = 0; i != NumElts; ++i) {
12099 int Idx = SVN->getMaskElt(i);
12100 if (Idx < 0) {
12101 // Propagate Undef.
12102 Mask.push_back(Idx);
12103 continue;
12104 }
12105
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012106 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012107 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012108 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12109 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012110 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012111 if (Idx < 0) {
12112 // Propagate Undef.
12113 Mask.push_back(Idx);
12114 continue;
12115 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012116
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012117 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12118 : OtherSV->getOperand(1);
12119 } else {
12120 // This shuffle index references an element within N1.
12121 CurrentVec = N1;
12122 }
12123
12124 // Simple case where 'CurrentVec' is UNDEF.
12125 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12126 Mask.push_back(-1);
12127 continue;
12128 }
12129
12130 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12131 // will be the first or second operand of the combined shuffle.
12132 Idx = Idx % NumElts;
12133 if (!SV0.getNode() || SV0 == CurrentVec) {
12134 // Ok. CurrentVec is the left hand side.
12135 // Update the mask accordingly.
12136 SV0 = CurrentVec;
12137 Mask.push_back(Idx);
12138 continue;
12139 }
12140
12141 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12142 if (SV1.getNode() && SV1 != CurrentVec)
12143 return SDValue();
12144
12145 // Ok. CurrentVec is the right hand side.
12146 // Update the mask accordingly.
12147 SV1 = CurrentVec;
12148 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012149 }
12150
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000012151 // Check if all indices in Mask are Undef. In case, propagate Undef.
12152 bool isUndefMask = true;
12153 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12154 isUndefMask &= Mask[i] < 0;
12155
12156 if (isUndefMask)
12157 return DAG.getUNDEF(VT);
12158
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012159 if (!SV0.getNode())
12160 SV0 = DAG.getUNDEF(VT);
12161 if (!SV1.getNode())
12162 SV1 = DAG.getUNDEF(VT);
12163
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012164 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012165 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12166 // Compute the commuted shuffle mask and test again.
12167 for (unsigned i = 0; i != NumElts; ++i) {
12168 int idx = Mask[i];
12169 if (idx < 0)
12170 continue;
12171 else if (idx < (int)NumElts)
12172 Mask[i] = idx + NumElts;
12173 else
12174 Mask[i] = idx - NumElts;
12175 }
12176
12177 if (!TLI.isShuffleMaskLegal(Mask, VT))
12178 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012179
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012180 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12181 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12182 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12183 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012184 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000012185
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012186 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12187 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12188 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12189 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012190 }
12191
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012192 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012193}
12194
Simon Pilgrimbede80a2015-03-07 05:52:42 +000012195SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12196 SDValue InVal = N->getOperand(0);
12197 EVT VT = N->getValueType(0);
12198
12199 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12200 // with a VECTOR_SHUFFLE.
12201 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12202 SDValue InVec = InVal->getOperand(0);
12203 SDValue EltNo = InVal->getOperand(1);
12204
12205 // FIXME: We could support implicit truncation if the shuffle can be
12206 // scaled to a smaller vector scalar type.
12207 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12208 if (C0 && VT == InVec.getValueType() &&
12209 VT.getScalarType() == InVal.getValueType()) {
12210 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12211 int Elt = C0->getZExtValue();
12212 NewMask[0] = Elt;
12213
12214 if (TLI.isShuffleMaskLegal(NewMask, VT))
12215 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12216 NewMask);
12217 }
12218 }
12219
12220 return SDValue();
12221}
12222
Manman Ren413a6cb2014-01-31 01:10:35 +000012223SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12224 SDValue N0 = N->getOperand(0);
12225 SDValue N2 = N->getOperand(2);
12226
12227 // If the input vector is a concatenation, and the insert replaces
12228 // one of the halves, we can optimize into a single concat_vectors.
12229 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12230 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12231 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12232 EVT VT = N->getValueType(0);
12233
12234 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12235 // (concat_vectors Z, Y)
12236 if (InsIdx == 0)
12237 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12238 N->getOperand(1), N0.getOperand(1));
12239
12240 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12241 // (concat_vectors X, Z)
12242 if (InsIdx == VT.getVectorNumElements()/2)
12243 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12244 N0.getOperand(0), N->getOperand(1));
12245 }
12246
12247 return SDValue();
12248}
12249
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012250/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12251/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000012252/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000012253/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012254SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012255 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000012256 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012257 SDValue LHS = N->getOperand(0);
12258 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000012259 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000012260 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000012261 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000012262 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012263 SmallVector<int, 8> Indices;
12264 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000012265 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012266 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000012267 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012268 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000012269
12270 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012271 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000012272 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Andrea Di Biagioce46b972014-11-05 13:04:14 +000012273 Indices.push_back(NumElts+i);
Evan Chenga320abc2006-04-20 08:56:16 +000012274 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012275 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012276 }
12277
Chandler Carruthb89464a2015-02-19 10:36:19 +000012278 // Let's see if the target supports this vector_shuffle and make sure
12279 // we're not running after operation legalization where it may have
12280 // custom lowered the vector shuffles.
Owen Anderson53aa7a92009-08-10 22:56:29 +000012281 EVT RVT = RHS.getValueType();
Chandler Carruthb89464a2015-02-19 10:36:19 +000012282 if (LegalOperations || !TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012283 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012284
Dan Gohmana8665142007-06-25 16:23:39 +000012285 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000012286 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012287 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000012288 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000012289 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000012290 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012291 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000012292 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000012293 }
12294 }
Bill Wendling31b50992009-01-30 23:59:18 +000012295
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012296 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012297}
12298
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012299/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012300SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000012301 assert(N->getValueType(0).isVector() &&
12302 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000012303
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012304 SDValue LHS = N->getOperand(0);
12305 SDValue RHS = N->getOperand(1);
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000012306
12307 if (SDValue Shuffle = XformToShuffleWithZero(N))
12308 return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000012309
Dan Gohmana8665142007-06-25 16:23:39 +000012310 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000012311 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012312 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000012313 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000012314 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000012315 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12316 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000012317 return SDValue();
12318
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012319 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000012320 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012321 SDValue LHSOp = LHS.getOperand(i);
12322 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000012323
Evan Cheng64d28462006-05-31 06:08:35 +000012324 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000012325 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12326 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000012327 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012328 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000012329 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012330 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000012331 break;
12332 }
Bill Wendling31b50992009-01-30 23:59:18 +000012333
Bob Wilson54081442010-12-17 23:06:49 +000012334 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000012335 EVT RVT = RHSOp.getValueType();
12336 if (RVT != VT) {
12337 // Integer BUILD_VECTOR operands may have types larger than the element
12338 // size (e.g., when the element type is not legal). Prior to type
12339 // legalization, the types may not match between the two BUILD_VECTORS.
12340 // Truncate one of the operands to make them match.
12341 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012342 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012343 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012344 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012345 VT = RVT;
12346 }
12347 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012348 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000012349 LHSOp, RHSOp);
12350 if (FoldOp.getOpcode() != ISD::UNDEF &&
12351 FoldOp.getOpcode() != ISD::Constant &&
12352 FoldOp.getOpcode() != ISD::ConstantFP)
12353 break;
12354 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012355 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000012356 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012357
Bob Wilson54081442010-12-17 23:06:49 +000012358 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000012359 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000012360 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012361
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012362 // Type legalization might introduce new shuffles in the DAG.
12363 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12364 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12365 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12366 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12367 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12368 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12369 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12370 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12371
12372 if (SVN0->getMask().equals(SVN1->getMask())) {
12373 EVT VT = N->getValueType(0);
12374 SDValue UndefVector = LHS.getOperand(1);
12375 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12376 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012377 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012378 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12379 &SVN0->getMask()[0]);
12380 }
12381 }
12382
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012383 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000012384}
12385
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012386/// Visit a binary vector operation, like FABS/FNEG.
Craig Topper82384612012-09-11 01:45:21 +000012387SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000012388 assert(N->getValueType(0).isVector() &&
12389 "SimplifyVUnaryOp only works on vectors!");
12390
12391 SDValue N0 = N->getOperand(0);
12392
12393 if (N0.getOpcode() != ISD::BUILD_VECTOR)
12394 return SDValue();
12395
12396 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12397 SmallVector<SDValue, 8> Ops;
12398 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12399 SDValue Op = N0.getOperand(i);
12400 if (Op.getOpcode() != ISD::UNDEF &&
12401 Op.getOpcode() != ISD::ConstantFP)
12402 break;
12403 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000012404 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000012405 if (FoldOp.getOpcode() != ISD::UNDEF &&
12406 FoldOp.getOpcode() != ISD::ConstantFP)
12407 break;
12408 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012409 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000012410 }
12411
12412 if (Ops.size() != N0.getNumOperands())
12413 return SDValue();
12414
Craig Topper48d114b2014-04-26 18:35:24 +000012415 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000012416}
12417
Andrew Trickef9de2a2013-05-25 02:42:55 +000012418SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012419 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000012420 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000012421
Bill Wendling31b50992009-01-30 23:59:18 +000012422 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000012423 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000012424
Nate Begeman2042aa52005-10-08 00:29:44 +000012425 // If we got a simplified select_cc node back from SimplifySelectCC, then
12426 // break it down into a new SETCC node, and a new SELECT node, and then return
12427 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000012428 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012429 // Check to see if we got a select_cc back (to turn into setcc/select).
12430 // Otherwise, just return whatever node we got back, like fabs.
12431 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012432 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012433 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000012434 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000012435 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012436 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000012437 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12438 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000012439 }
Bill Wendling31b50992009-01-30 23:59:18 +000012440
Nate Begeman2042aa52005-10-08 00:29:44 +000012441 return SCC;
12442 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012443 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012444}
12445
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012446/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12447/// being selected between, see if we can simplify the select. Callers of this
12448/// should assume that TheSelect is deleted if this returns true. As such, they
12449/// should return the appropriate thing (e.g. the node) back to the top-level of
12450/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012451bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012452 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012453
Nadav Rotema49a02a2011-02-11 19:57:47 +000012454 // Cannot simplify select with vector condition
12455 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12456
Chris Lattner6c14c352005-10-18 06:04:22 +000012457 // If this is a select from two identical things, try to pull the operation
12458 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000012459 if (LHS.getOpcode() != RHS.getOpcode() ||
12460 !LHS.hasOneUse() || !RHS.hasOneUse())
12461 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012462
Chris Lattner254c4452010-09-21 15:46:59 +000012463 // If this is a load and the token chain is identical, replace the select
12464 // of two loads with a load through a select of the address to load from.
12465 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12466 // constants have been dropped into the constant pool.
12467 if (LHS.getOpcode() == ISD::LOAD) {
12468 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12469 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000012470
Chris Lattner254c4452010-09-21 15:46:59 +000012471 // Token chains must be identical.
12472 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000012473 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000012474 LLD->isVolatile() || RLD->isVolatile() ||
12475 // If this is an EXTLOAD, the VT's must match.
12476 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000012477 // If this is an EXTLOAD, the kind of extension must match.
12478 (LLD->getExtensionType() != RLD->getExtensionType() &&
12479 // The only exception is if one of the extensions is anyext.
12480 LLD->getExtensionType() != ISD::EXTLOAD &&
12481 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000012482 // FIXME: this discards src value information. This is
12483 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000012484 // both potential memory locations. Since we are discarding
12485 // src value info, don't do the transformation if the memory
12486 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000012487 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000012488 RLD->getPointerInfo().getAddrSpace() != 0 ||
12489 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12490 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000012491 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012492
Chris Lattnere3267522010-09-21 15:58:55 +000012493 // Check that the select condition doesn't reach either load. If so,
12494 // folding this will induce a cycle into the DAG. If not, this is safe to
12495 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000012496 SDValue Addr;
12497 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000012498 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12499 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12500 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12501 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000012502 // The loads must not depend on one another.
12503 if (LLD->isPredecessorOf(RLD) ||
12504 RLD->isPredecessorOf(LLD))
12505 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012506 Addr = DAG.getSelect(SDLoc(TheSelect),
12507 LLD->getBasePtr().getValueType(),
12508 TheSelect->getOperand(0), LLD->getBasePtr(),
12509 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000012510 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000012511 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12512 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12513
12514 if ((LLD->hasAnyUseOfValue(1) &&
12515 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000012516 (RLD->hasAnyUseOfValue(1) &&
12517 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000012518 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012519
Andrew Trickef9de2a2013-05-25 02:42:55 +000012520 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000012521 LLD->getBasePtr().getValueType(),
12522 TheSelect->getOperand(0),
12523 TheSelect->getOperand(1),
12524 LLD->getBasePtr(), RLD->getBasePtr(),
12525 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000012526 }
12527
Chris Lattnere3267522010-09-21 15:58:55 +000012528 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000012529 // It is safe to replace the two loads if they have different alignments,
12530 // but the new load must be the minimum (most restrictive) alignment of the
12531 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000012532 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000012533 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000012534 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12535 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012536 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000012537 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012538 LLD->getChain(), Addr, MachinePointerInfo(),
12539 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012540 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000012541 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000012542 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12543 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012544 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000012545 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000012546 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012547 LLD->getChain(), Addr, MachinePointerInfo(),
12548 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012549 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000012550 }
Chris Lattnere3267522010-09-21 15:58:55 +000012551
12552 // Users of the select now use the result of the load.
12553 CombineTo(TheSelect, Load);
12554
12555 // Users of the old loads now use the new load's chain. We know the
12556 // old-load value is dead now.
12557 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12558 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12559 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000012560 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012561
Chris Lattner6c14c352005-10-18 06:04:22 +000012562 return false;
12563}
12564
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012565/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000012566/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000012567SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012568 SDValue N2, SDValue N3,
12569 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000012570 // (x ? y : y) -> y.
12571 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000012572
Owen Anderson53aa7a92009-08-10 22:56:29 +000012573 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000012574 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12575 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12576 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012577
12578 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000012579 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000012580 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012581 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000012582 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012583
12584 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000012585 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012586 return N2;
12587 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000012588 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012589 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012590
Nate Begeman2042aa52005-10-08 00:29:44 +000012591 // Check to see if we can simplify the select into an fabs node
12592 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12593 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000012594 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012595 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12596 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12597 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12598 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000012599 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012600
Nate Begeman2042aa52005-10-08 00:29:44 +000012601 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12602 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12603 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12604 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000012605 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000012606 }
12607 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012608
Chris Lattner43d63772009-03-11 05:08:08 +000012609 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12610 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12611 // in it. This is a win when the constant is not otherwise available because
12612 // it replaces two constant pool loads with one. We only do this if the FP
12613 // type is known to be legal, because if it isn't, then we are before legalize
12614 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000012615 // messing with soft float) and if the ConstantFP is not legal, because if
12616 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000012617 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12618 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12619 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000012620 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000012621 TargetLowering::Legal &&
12622 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12623 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000012624 // If both constants have multiple uses, then we won't need to do an
12625 // extra load, they are likely around in registers for other users.
12626 (TV->hasOneUse() || FV->hasOneUse())) {
12627 Constant *Elts[] = {
12628 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12629 const_cast<ConstantFP*>(TV->getConstantFPValue())
12630 };
Chris Lattner229907c2011-07-18 04:54:35 +000012631 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000012632 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000012633
Chris Lattner43d63772009-03-11 05:08:08 +000012634 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000012635 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000012636 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12637 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000012638 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000012639
12640 // Get the offsets to the 0 and 1 element of the array so that we can
12641 // select between them.
12642 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000012643 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000012644 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000012645
Chris Lattner43d63772009-03-11 05:08:08 +000012646 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000012647 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000012648 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012649 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012650 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12651 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012652 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000012653 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000012654 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012655 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000012656 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000012657 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000012658 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000012659
12660 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012661 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012662
Nate Begeman2042aa52005-10-08 00:29:44 +000012663 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000012664 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000012665 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000012666 (N1C->isNullValue() || // (a < 0) ? b : 0
12667 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000012668 EVT XType = N0.getValueType();
12669 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000012670 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000012671 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000012672 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012673 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12674 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000012675 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000012676 SDValue ShCt = DAG.getConstant(ShCtV,
12677 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012678 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012679 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012680 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000012681
Duncan Sands11dd4242008-06-08 20:54:56 +000012682 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000012683 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012684 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012685 }
Bill Wendling31b50992009-01-30 23:59:18 +000012686
12687 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000012688 }
Bill Wendling31b50992009-01-30 23:59:18 +000012689
Andrew Trickef9de2a2013-05-25 02:42:55 +000012690 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012691 XType, N0,
12692 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012693 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012694 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000012695
Duncan Sands11dd4242008-06-08 20:54:56 +000012696 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000012697 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012698 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012699 }
Bill Wendling31b50992009-01-30 23:59:18 +000012700
12701 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000012702 }
12703 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012704
Owen Anderson3231d132010-09-22 22:58:22 +000012705 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12706 // where y is has a single bit set.
12707 // A plaintext description would be, we can turn the SELECT_CC into an AND
12708 // when the condition can be materialized as an all-ones register. Any
12709 // single bit-test can be materialized as an all-ones register with
12710 // shift-left and shift-right-arith.
12711 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12712 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000012713 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000012714 N2C && N2C->isNullValue()) {
12715 SDValue AndLHS = N0->getOperand(0);
12716 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12717 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12718 // Shift the tested bit over the sign bit.
12719 APInt AndMask = ConstAndRHS->getAPIntValue();
12720 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000012721 DAG.getConstant(AndMask.countLeadingZeros(),
12722 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012723 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000012724
Owen Anderson3231d132010-09-22 22:58:22 +000012725 // Now arithmetic right shift it all the way over, so the result is either
12726 // all-ones, or zero.
12727 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000012728 DAG.getConstant(AndMask.getBitWidth()-1,
12729 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012730 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000012731
Owen Anderson3231d132010-09-22 22:58:22 +000012732 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12733 }
12734 }
12735
Nate Begeman6828ed92005-10-10 21:26:48 +000012736 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000012737 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000012738 TLI.getBooleanContents(N0.getValueType()) ==
12739 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012740
Chris Lattnera083ffc2007-04-11 06:50:51 +000012741 // If the caller doesn't want us to simplify this into a zext of a compare,
12742 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012743 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012744 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012745
Nate Begeman6828ed92005-10-10 21:26:48 +000012746 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012747 // NOTE: Don't create a SETCC if it's not legal on this target.
12748 if (!LegalOperations ||
12749 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000012750 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012751 SDValue Temp, SCC;
12752 // cast from setcc result type to select result type
12753 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000012754 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012755 N0, N1, CC);
12756 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000012757 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012758 N2.getValueType());
12759 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000012760 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012761 N2.getValueType(), SCC);
12762 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012763 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12764 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000012765 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012766 }
12767
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012768 AddToWorklist(SCC.getNode());
12769 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012770
12771 if (N2C->getAPIntValue() == 1)
12772 return Temp;
12773
12774 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000012775 return DAG.getNode(
12776 ISD::SHL, DL, N2.getValueType(), Temp,
12777 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12778 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000012779 }
Nate Begeman6828ed92005-10-10 21:26:48 +000012780 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012781
Nate Begeman2042aa52005-10-08 00:29:44 +000012782 // Check to see if this is the equivalent of setcc
12783 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12784 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012785 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012786 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000012787 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000012788 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12789 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000012790 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000012791 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000012792 return Res;
12793 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012794
Bill Wendling31b50992009-01-30 23:59:18 +000012795 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000012796 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000012797 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000012798 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012799 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012800 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000012801 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000012802 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000012803 }
Bill Wendling31b50992009-01-30 23:59:18 +000012804 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000012805 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012806 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012807 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000012808 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000012809 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000012810 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000012811 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012812 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000012813 }
Bill Wendling31b50992009-01-30 23:59:18 +000012814 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000012815 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012816 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012817 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012818 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000012819 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000012820 }
12821 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012822
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012823 // Check to see if this is an integer abs.
12824 // select_cc setg[te] X, 0, X, -X ->
12825 // select_cc setgt X, -1, X, -X ->
12826 // select_cc setl[te] X, 0, -X, X ->
12827 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000012828 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012829 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000012830 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012831 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12832 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12833 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12834 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12835 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12836 (N1C->isOne() && CC == ISD::SETLT)) &&
12837 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12838 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12839
Owen Anderson53aa7a92009-08-10 22:56:29 +000012840 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012841 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012842 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012843 N0,
12844 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012845 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012846 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012847 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012848 AddToWorklist(Shift.getNode());
12849 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012850 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000012851 }
12852 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012853
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012854 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012855}
12856
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012857/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000012858SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012859 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000012860 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012861 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000012862 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000012863 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000012864}
12865
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012866/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000012867/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000012868/// by a magic number.
12869/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012870SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012871 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12872 if (!C)
12873 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012874
12875 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012876 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012877 return SDValue();
12878
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012879 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012880 SDValue S =
12881 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012882
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012883 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012884 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012885 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012886}
12887
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012888/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12889/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000012890SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12891 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12892 if (!C)
12893 return SDValue();
12894
12895 // Avoid division by zero.
12896 if (!C->getAPIntValue())
12897 return SDValue();
12898
12899 std::vector<SDNode *> Built;
12900 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12901
12902 for (SDNode *N : Built)
12903 AddToWorklist(N);
12904 return S;
12905}
12906
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012907/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12908/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000012909/// number.
12910/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012911SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012912 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12913 if (!C)
12914 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012915
12916 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012917 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012918 return SDValue();
12919
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012920 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012921 SDValue S =
12922 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000012923
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012924 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012925 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012926 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012927}
12928
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012929SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12930 if (Level >= AfterLegalizeDAG)
12931 return SDValue();
12932
Sanjay Patelb67bd262014-09-21 15:19:15 +000012933 // Expose the DAG combiner to the target combiner implementations.
12934 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000012935
Sanjay Patelab7f4602014-09-30 20:44:23 +000012936 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000012937 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000012938 if (Iterations) {
12939 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12940 // For the reciprocal, we need to find the zero of the function:
12941 // F(X) = A X - 1 [which has a zero at X = 1/A]
12942 // =>
12943 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12944 // does not require additional intermediate precision]
12945 EVT VT = Op.getValueType();
12946 SDLoc DL(Op);
12947 SDValue FPOne = DAG.getConstantFP(1.0, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012948
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012949 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012950
Sanjay Patelab7f4602014-09-30 20:44:23 +000012951 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12952 for (unsigned i = 0; i < Iterations; ++i) {
12953 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12954 AddToWorklist(NewEst.getNode());
12955
12956 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12957 AddToWorklist(NewEst.getNode());
12958
12959 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12960 AddToWorklist(NewEst.getNode());
12961
12962 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12963 AddToWorklist(Est.getNode());
12964 }
12965 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012966 return Est;
12967 }
12968
12969 return SDValue();
12970}
12971
Sanjay Patel957efc232014-10-24 17:02:16 +000012972/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12973/// For the reciprocal sqrt, we need to find the zero of the function:
12974/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12975/// =>
12976/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12977/// As a result, we precompute A/2 prior to the iteration loop.
12978SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12979 unsigned Iterations) {
12980 EVT VT = Arg.getValueType();
12981 SDLoc DL(Arg);
12982 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012983
Sanjay Patel957efc232014-10-24 17:02:16 +000012984 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12985 // this entire sequence requires only one FP constant.
12986 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12987 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012988
Sanjay Patel957efc232014-10-24 17:02:16 +000012989 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12990 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012991
Sanjay Patel957efc232014-10-24 17:02:16 +000012992 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12993 for (unsigned i = 0; i < Iterations; ++i) {
12994 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12995 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012996
Sanjay Patel957efc232014-10-24 17:02:16 +000012997 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12998 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012999
Sanjay Patel957efc232014-10-24 17:02:16 +000013000 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13001 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013002
Sanjay Patel957efc232014-10-24 17:02:16 +000013003 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13004 AddToWorklist(Est.getNode());
13005 }
13006 return Est;
13007}
13008
13009/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13010/// For the reciprocal sqrt, we need to find the zero of the function:
13011/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13012/// =>
13013/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13014SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13015 unsigned Iterations) {
13016 EVT VT = Arg.getValueType();
13017 SDLoc DL(Arg);
13018 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
13019 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
13020
13021 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13022 for (unsigned i = 0; i < Iterations; ++i) {
13023 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13024 AddToWorklist(HalfEst.getNode());
13025
13026 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13027 AddToWorklist(Est.getNode());
13028
13029 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13030 AddToWorklist(Est.getNode());
13031
13032 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13033 AddToWorklist(Est.getNode());
13034
13035 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13036 AddToWorklist(Est.getNode());
13037 }
13038 return Est;
13039}
13040
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013041SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13042 if (Level >= AfterLegalizeDAG)
13043 return SDValue();
13044
13045 // Expose the DAG combiner to the target combiner implementations.
13046 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013047 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000013048 bool UseOneConstNR = false;
13049 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13050 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000013051 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000013052 Est = UseOneConstNR ?
13053 BuildRsqrtNROneConst(Op, Est, Iterations) :
13054 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013055 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013056 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000013057 }
13058
13059 return SDValue();
13060}
13061
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013062/// Return true if base is a frame index, which is known not to alias with
13063/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000013064static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000013065 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000013066 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000013067 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013068
Jim Laskey0463e082006-10-07 23:37:56 +000013069 // If it's an adding a simple constant then integrate the offset.
13070 if (Base.getOpcode() == ISD::ADD) {
13071 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13072 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000013073 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000013074 }
13075 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013076
Nate Begeman18150d52009-09-25 06:05:26 +000013077 // Return the underlying GlobalValue, and update the Offset. Return false
13078 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13079 // by multiple nodes with different offsets.
13080 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13081 GV = G->getGlobal();
13082 Offset += G->getOffset();
13083 return false;
13084 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013085
Nate Begeman18150d52009-09-25 06:05:26 +000013086 // Return the underlying Constant value, and update the Offset. Return false
13087 // for ConstantSDNodes since the same constant pool entry may be represented
13088 // by multiple nodes with different offsets.
13089 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000013090 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13091 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000013092 Offset += C->getOffset();
13093 return false;
13094 }
Jim Laskey0463e082006-10-07 23:37:56 +000013095 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000013096 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000013097}
13098
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013099/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013100bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000013101 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013102 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013103
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013104 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013105 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013106
Jim Laskey0463e082006-10-07 23:37:56 +000013107 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013108 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000013109 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000013110 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000013111 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013112 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13113 Base1, Offset1, GV1, CV1);
13114 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13115 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013116
Nate Begeman18150d52009-09-25 06:05:26 +000013117 // If they have a same base address then check to see if they overlap.
13118 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013119 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13120 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013121
Owen Anderson272ff942010-09-20 20:39:59 +000013122 // It is possible for different frame indices to alias each other, mostly
13123 // when tail call optimization reuses return address slots for arguments.
13124 // To catch this case, look up the actual index of frame indices to compute
13125 // the real alias relationship.
13126 if (isFrameIndex1 && isFrameIndex2) {
13127 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13128 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13129 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013130 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13131 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000013132 }
13133
Wesley Peck527da1b2010-11-23 03:31:01 +000013134 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000013135 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000013136 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13137 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013138
Nate Begeman879d8f12009-09-15 00:18:30 +000013139 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13140 // compared to the size and offset of the access, we may be able to prove they
13141 // do not alias. This check is conservative for now to catch cases created by
13142 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013143 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13144 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13145 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13146 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13147 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13148 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13149 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000013150
Nate Begeman879d8f12009-09-15 00:18:30 +000013151 // There is no overlap between these relatively aligned accesses of similar
13152 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013153 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13154 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000013155 return false;
13156 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013157
Eric Christopherf55d4712014-10-08 23:38:39 +000013158 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13159 ? CombinerGlobalAA
13160 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000013161#ifndef NDEBUG
13162 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13163 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13164 UseAA = false;
13165#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013166 if (UseAA &&
13167 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000013168 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013169 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13170 Op1->getSrcValueOffset());
13171 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13172 Op0->getSrcValueOffset() - MinOffset;
13173 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13174 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013175 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013176 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13177 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000013178 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013179 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13180 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000013181 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000013182 if (AAResult == AliasAnalysis::NoAlias)
13183 return false;
13184 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013185
13186 // Otherwise we have to assume they alias.
13187 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000013188}
13189
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013190/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000013191/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013192void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000013193 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013194 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000013195 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013196
Jim Laskeyd07be232006-09-25 16:29:54 +000013197 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013198 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000013199
Jim Laskey708d0db2006-10-04 16:53:27 +000013200 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000013201 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013202 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000013203
Jim Laskey6549d222006-10-05 15:07:25 +000013204 // Look at each chain and determine if it is an alias. If so, add it to the
13205 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000013206 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000013207 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013208 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000013209 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000013210
13211 // For TokenFactor nodes, look at each operand and only continue up the
13212 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013213 // find more and revert to original chain since the xform is unlikely to be
13214 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000013215 //
13216 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013217 // chain we found before we hit a tokenfactor rather than the original
13218 // chain.
13219 if (Depth > 6 || Aliases.size() == 2) {
13220 Aliases.clear();
13221 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000013222 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013223 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013224
Nate Begeman879d8f12009-09-15 00:18:30 +000013225 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000013226 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000013227 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013228
Jim Laskey6549d222006-10-05 15:07:25 +000013229 switch (Chain.getOpcode()) {
13230 case ISD::EntryToken:
13231 // Entry token is ideal chain operand, but handled in FindBetterChain.
13232 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013233
Jim Laskey6549d222006-10-05 15:07:25 +000013234 case ISD::LOAD:
13235 case ISD::STORE: {
13236 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013237 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13238 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013239
Jim Laskey6549d222006-10-05 15:07:25 +000013240 // If chain is alias then stop here.
13241 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013242 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000013243 Aliases.push_back(Chain);
13244 } else {
13245 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013246 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013247 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000013248 }
Jim Laskey6549d222006-10-05 15:07:25 +000013249 break;
13250 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013251
Jim Laskey6549d222006-10-05 15:07:25 +000013252 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000013253 // We have to check each of the operands of the token factor for "small"
13254 // token factors, so we queue them up. Adding the operands to the queue
13255 // (stack) in reverse order maintains the original order and increases the
13256 // likelihood that getNode will find a matching token factor (CSE.)
13257 if (Chain.getNumOperands() > 16) {
13258 Aliases.push_back(Chain);
13259 break;
13260 }
Jim Laskey6549d222006-10-05 15:07:25 +000013261 for (unsigned n = Chain.getNumOperands(); n;)
13262 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013263 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000013264 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013265
Jim Laskey6549d222006-10-05 15:07:25 +000013266 default:
13267 // For all other instructions we will just have to take what we can get.
13268 Aliases.push_back(Chain);
13269 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000013270 }
13271 }
Hal Finkel51a98382014-01-24 20:12:02 +000013272
13273 // We need to be careful here to also search for aliases through the
13274 // value operand of a store, etc. Consider the following situation:
13275 // Token1 = ...
13276 // L1 = load Token1, %52
13277 // S1 = store Token1, L1, %51
13278 // L2 = load Token1, %52+8
13279 // S2 = store Token1, L2, %51+8
13280 // Token2 = Token(S1, S2)
13281 // L3 = load Token2, %53
13282 // S3 = store Token2, L3, %52
13283 // L4 = load Token2, %53+8
13284 // S4 = store Token2, L4, %52+8
13285 // If we search for aliases of S3 (which loads address %52), and we look
13286 // only through the chain, then we'll miss the trivial dependence on L1
13287 // (which also loads from %52). We then might change all loads and
13288 // stores to use Token1 as their chain operand, which could result in
13289 // copying %53 into %52 before copying %52 into %51 (which should
13290 // happen first).
13291 //
13292 // The problem is, however, that searching for such data dependencies
13293 // can become expensive, and the cost is not directly related to the
13294 // chain depth. Instead, we'll rule out such configurations here by
13295 // insisting that we've visited all chain users (except for users
13296 // of the original chain, which is not necessary). When doing this,
13297 // we need to look through nodes we don't care about (otherwise, things
13298 // like register copies will interfere with trivial cases).
13299
13300 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000013301 for (const SDNode *N : Visited)
13302 if (N != OriginalChain.getNode())
13303 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000013304
13305 while (!Worklist.empty()) {
13306 const SDNode *M = Worklist.pop_back_val();
13307
13308 // We have already visited M, and want to make sure we've visited any uses
13309 // of M that we care about. For uses that we've not visisted, and don't
13310 // care about, queue them to the worklist.
13311
13312 for (SDNode::use_iterator UI = M->use_begin(),
13313 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000013314 if (UI.getUse().getValueType() == MVT::Other &&
13315 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000013316 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13317 // We've not visited this use, and we care about it (it could have an
13318 // ordering dependency with the original node).
13319 Aliases.clear();
13320 Aliases.push_back(OriginalChain);
13321 return;
13322 }
13323
13324 // We've not visited this use, but we don't care about it. Mark it as
13325 // visited and enqueue it to the worklist.
13326 Worklist.push_back(*UI);
13327 }
13328 }
Jim Laskey708d0db2006-10-04 16:53:27 +000013329}
13330
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013331/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13332/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013333SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13334 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013335
Jim Laskey708d0db2006-10-04 16:53:27 +000013336 // Accumulate all the aliases to this node.
13337 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013338
Dan Gohman4298df62011-05-17 22:20:36 +000013339 // If no operands then chain to entry token.
13340 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000013341 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000013342
13343 // If a single operand then chain to it. We don't need to revisit it.
13344 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000013345 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000013346
Jim Laskey708d0db2006-10-04 16:53:27 +000013347 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000013348 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000013349}
13350
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013351/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000013352void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000013353 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013354 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000013355 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000013356}