blob: aee6455713afbd14cbae306293a6b0292179b721 [file] [log] [blame]
Nate Begeman2504fe22005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman21158fc2005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman21158fc2005-09-01 00:19:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012//
Dan Gohman45399872009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman21158fc2005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
Nate Begeman21158fc2005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth9a0051c2014-07-23 07:08:53 +000021#include "llvm/ADT/SetVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000022#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043#define DEBUG_TYPE "dagcombine"
44
Chris Lattneraee775a2006-12-19 22:41:21 +000045STATISTIC(NodesCombined , "Number of dag nodes combined");
46STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000048STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000049STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000050STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000051
Nate Begeman21158fc2005-09-01 00:19:25 +000052namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000053 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000054 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000055 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000056
Jim Laskey55e4dca2006-10-18 19:08:31 +000057 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000059 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000060
Hal Finkeldbebb522014-01-25 19:24:54 +000061 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000062 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000063 cl::desc("Enable DAG combiner's use of TBAA"));
64
Hal Finkel9b2617a2014-01-25 17:32:39 +000065#ifndef NDEBUG
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
69 " function"));
70#endif
71
Quentin Colombetde0e0622013-10-11 18:29:42 +000072 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
74 static cl::opt<bool>
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
77 "slicing"),
78 cl::init(false));
79
Hal Finkel51e6fa22014-09-02 06:24:04 +000080 static cl::opt<bool>
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
83
Jim Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
Chandler Carruth9a0051c2014-07-23 07:08:53 +000095 /// \brief Worklist of all of the nodes that need to be simplified.
96 ///
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
99 ///
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
103
104 /// \brief Mapping from an SDNode to its position on the worklist.
105 ///
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000110
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000111 /// \brief Set of nodes which have been combined (at least once).
112 ///
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
116
Jim Laskeydcb2b832006-10-16 20:52:31 +0000117 // AA - Used for DAG load/store alias analysis.
118 AliasAnalysis &AA;
119
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000123 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000124 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000125 }
126
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000127 /// Call the node-specific routine that folds each particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000128 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000129
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000130 public:
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000131 /// Add to the worklist making sure its instance is at the back (next to be
132 /// processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000133 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
137 return;
138
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000141 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000142
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000143 /// Remove all instances of N from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000144 void removeFromWorklist(SDNode *N) {
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000145 CombinedNodes.erase(N);
146
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
150
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000155
Chandler Carruth18066972014-08-02 10:02:07 +0000156 void deleteAndRecombine(SDNode *N);
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000157 bool recursivelyDeleteUnusedNodes(SDNode *N);
158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000160 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000161
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000163 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000164 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000167 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000168 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000169 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000170 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000171
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000173
174 private:
175
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000179 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000182 return SimplifyDemandedBits(Op, Demanded);
183 }
184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000186
Chris Lattnerffad2162006-11-11 00:39:41 +0000187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
Hal Finkel51e6fa22014-09-02 06:24:04 +0000189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000190 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000191
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193 /// load.
194 ///
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000206 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000207 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000210
Craig Toppere0b71182013-07-13 07:43:40 +0000211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000213 ISD::NodeType ExtType);
214
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000215 /// Call the node-specific routine that knows how to fold each
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000218 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000219
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
222 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000226 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000232 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000234 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000252 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000256 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000257 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000259 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000263 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000271 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000276 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000279 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000293 SDValue visitBRCOND(SDNode *N);
294 SDValue visitBR_CC(SDNode *N);
295 SDValue visitLOAD(SDNode *N);
296 SDValue visitSTORE(SDNode *N);
297 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
298 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
299 SDValue visitBUILD_VECTOR(SDNode *N);
300 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000301 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000302 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000303 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000304
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000305 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000306 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000307
Matt Arsenault985b9de2014-03-17 18:58:01 +0000308 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000309
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000310 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
311 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000312 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
313 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000314 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000315 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000316 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000317 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000318
319 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
320 SDValue &CC) const;
321 bool isOneUseSetCC(SDValue N) const;
322
Scott Michelcf0da6c2009-02-17 22:15:04 +0000323 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000324 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000325 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000326 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000327 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000328 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000329 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000330 SDValue BuildReciprocalEstimate(SDValue Op);
331 SDValue BuildRsqrtEstimate(SDValue Op);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000332 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
333 bool DemandHighBits = true);
334 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000335 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
336 SDValue InnerPos, SDValue InnerNeg,
337 unsigned PosOpcode, unsigned NegOpcode,
338 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000339 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000340 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000341 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000342 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000343 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000344 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000345
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000346 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000347
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000348 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000349 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000350 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000351 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000352
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000353 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000354 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000355
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000356 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
357 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000358 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000359
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000360 /// Merge consecutive store operations into a wide store.
361 /// This optimization uses wide integers or vectors when possible.
362 /// \return True if some memory operations were changed.
363 bool MergeConsecutiveStores(StoreSDNode *N);
364
Adam Nemet67483892014-03-04 23:28:31 +0000365 /// \brief Try to transform a truncation where C is a constant:
366 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
367 ///
368 /// \p N needs to be a truncation and its first operand an AND. Other
369 /// requirements are checked by the function (e.g. that trunc is
370 /// single-use) and if missed an empty SDValue is returned.
371 SDValue distributeTruncateThroughAnd(SDNode *N);
372
Chris Lattner4041ab62010-04-15 04:48:01 +0000373 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000374 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000375 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
376 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
377 AttributeSet FnAttrs =
378 DAG.getMachineFunction().getFunction()->getAttributes();
379 ForCodeSize =
380 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
381 Attribute::OptimizeForSize) ||
382 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
383 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000384
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000385 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000386 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000387
Chris Lattner4041ab62010-04-15 04:48:01 +0000388 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000389
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000390 /// Returns a type large enough to hold any valid shift amount - before type
391 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000392 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000393 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
394 if (LHSTy.isVector())
395 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000396 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
397 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000398 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000399
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000400 /// This method returns true if we are running before type legalization or
401 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000402 bool isTypeLegal(const EVT &VT) {
403 if (!LegalTypes) return true;
404 return TLI.isTypeLegal(VT);
405 }
Matt Arsenault758659232013-05-18 00:21:46 +0000406
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000407 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000408 EVT getSetCCResultType(EVT VT) const {
409 return TLI.getSetCCResultType(*DAG.getContext(), VT);
410 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000411 };
412}
413
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000414
415namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000416/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000417/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000418class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000419 DAGCombiner &DC;
420public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000421 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000422 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000423
Craig Topper7b883b32014-03-08 06:31:39 +0000424 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000425 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000426 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000427};
428}
429
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000430//===----------------------------------------------------------------------===//
431// TargetLowering::DAGCombinerInfo implementation
432//===----------------------------------------------------------------------===//
433
434void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000435 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000436}
437
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000438void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000439 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000440}
441
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000442SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000443CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
444 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000445}
446
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000447SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000448CombineTo(SDNode *N, SDValue Res, bool AddTo) {
449 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000450}
451
452
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000453SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000454CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
455 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000456}
457
Dan Gohmane58ab792009-01-29 01:59:02 +0000458void TargetLowering::DAGCombinerInfo::
459CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
460 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
461}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000462
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000463//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000464// Helper Functions
465//===----------------------------------------------------------------------===//
466
Chandler Carruth18066972014-08-02 10:02:07 +0000467void DAGCombiner::deleteAndRecombine(SDNode *N) {
468 removeFromWorklist(N);
469
470 // If the operands of this node are only used by the node, they will now be
471 // dead. Make sure to re-visit them and recursively delete dead nodes.
472 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000473 // For an operand generating multiple values, one of the values may
474 // become dead allowing further simplification (e.g. split index
475 // arithmetic from an indexed load).
476 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000477 AddToWorklist(Op.getNode());
478
479 DAG.DeleteNode(N);
480}
481
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000482/// Return 1 if we can compute the negated form of the specified expression for
483/// the same cost as the expression itself, or 2 if we can compute the negated
484/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000485static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000486 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000487 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000488 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000489 // fneg is removable even if it has multiple uses.
490 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000491
Chris Lattnere49c9742007-05-14 22:04:50 +0000492 // Don't allow anything with multiple uses.
493 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000494
Chris Lattner46980832007-05-25 02:19:06 +0000495 // Don't recurse exponentially.
496 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000497
Chris Lattnere49c9742007-05-14 22:04:50 +0000498 switch (Op.getOpcode()) {
499 default: return false;
500 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000501 // Don't invert constant FP values after legalize. The negated constant
502 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000503 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000504 case ISD::FADD:
505 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000506 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000507
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000508 // After operation legalization, it might not be legal to create new FSUBs.
509 if (LegalOperations &&
510 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
511 return 0;
512
Craig Topper03f39772012-09-09 22:58:45 +0000513 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000514 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
515 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000516 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000517 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000518 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000519 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000520 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000521 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000522 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000523
Bill Wendling6fbf5492009-01-30 23:10:18 +0000524 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000525 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000526
Chris Lattnere49c9742007-05-14 22:04:50 +0000527 case ISD::FMUL:
528 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000529 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000530
Bill Wendling6fbf5492009-01-30 23:10:18 +0000531 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000532 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
533 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000534 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000535
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000536 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000537 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000538
Chris Lattnere49c9742007-05-14 22:04:50 +0000539 case ISD::FP_EXTEND:
540 case ISD::FP_ROUND:
541 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000542 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000543 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000544 }
545}
546
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000547/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000548static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000549 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000550 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000551 // fneg is removable even if it has multiple uses.
552 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000553
Chris Lattnere49c9742007-05-14 22:04:50 +0000554 // Don't allow anything with multiple uses.
555 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000556
Chris Lattner46980832007-05-25 02:19:06 +0000557 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000558 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000559 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000560 case ISD::ConstantFP: {
561 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
562 V.changeSign();
563 return DAG.getConstantFP(V, Op.getValueType());
564 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000565 case ISD::FADD:
566 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000567 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000568
Bill Wendling6fbf5492009-01-30 23:10:18 +0000569 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000570 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000571 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000572 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000573 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000574 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000575 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000576 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000577 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000578 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000579 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000580 Op.getOperand(0));
581 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000582 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000583 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000584
Bill Wendling6fbf5492009-01-30 23:10:18 +0000585 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000586 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000587 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000588 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000589
Bill Wendling6fbf5492009-01-30 23:10:18 +0000590 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000591 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000592 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000593
Chris Lattnere49c9742007-05-14 22:04:50 +0000594 case ISD::FMUL:
595 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000596 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000597
Bill Wendling6fbf5492009-01-30 23:10:18 +0000598 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
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(Op.getOpcode(), 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));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000605
Bill Wendling6fbf5492009-01-30 23:10:18 +0000606 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000607 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000608 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000609 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000610 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000611
Chris Lattnere49c9742007-05-14 22:04:50 +0000612 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000613 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000614 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000615 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000616 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000617 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000618 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000619 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000620 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000621 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000622 }
623}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000624
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000625// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000626// that selects between the target values used for true and false, making it
627// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
628// the appropriate nodes based on the type of node we are checking. This
629// simplifies life a bit for the callers.
630bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
631 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000632 if (N.getOpcode() == ISD::SETCC) {
633 LHS = N.getOperand(0);
634 RHS = N.getOperand(1);
635 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000636 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000637 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000638
639 if (N.getOpcode() != ISD::SELECT_CC ||
640 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
641 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
642 return false;
643
644 LHS = N.getOperand(0);
645 RHS = N.getOperand(1);
646 CC = N.getOperand(4);
647 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000648}
649
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000650/// Return true if this is a SetCC-equivalent operation with only one use.
651/// If this is true, it allows the users to invert the operation for free when
652/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000653bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000654 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000655 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000656 return true;
657 return false;
658}
659
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000660/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000661/// elements are all the same constant or undefined.
662static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
663 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
664 if (!C)
665 return false;
666
667 APInt SplatUndef;
668 unsigned SplatBitSize;
669 bool HasAnyUndefs;
670 EVT EltVT = N->getValueType(0).getVectorElementType();
671 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
672 HasAnyUndefs) &&
673 EltVT.getSizeInBits() >= SplatBitSize);
674}
675
676// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000677static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
678 if (isa<ConstantSDNode>(N))
679 return N.getNode();
680 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000681 if (BV && BV->isConstant())
Juergen Ributzka68402822014-01-13 21:49:25 +0000682 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000683 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000684}
685
Matt Arsenault985b9de2014-03-17 18:58:01 +0000686// \brief Returns the SDNode if it is a constant splat BuildVector or constant
687// int.
688static ConstantSDNode *isConstOrConstSplat(SDValue N) {
689 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
690 return CN;
691
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000692 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000693 BitVector UndefElements;
694 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000695
696 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000697 // FIXME: We blindly ignore splats which include undef which is overly
698 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000699 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000700 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000701 return CN;
702 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000703
704 return nullptr;
705}
706
Matt Arsenault6cc00422014-08-16 10:14:19 +0000707// \brief Returns the SDNode if it is a constant splat BuildVector or constant
708// float.
709static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
710 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
711 return CN;
712
713 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
714 BitVector UndefElements;
715 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
716
Matt Arsenault965de302014-09-02 18:33:51 +0000717 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000718 return CN;
719 }
720
721 return nullptr;
722}
723
Andrew Trickef9de2a2013-05-25 02:42:55 +0000724SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000725 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000726 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000727 if (N0.getOpcode() == Opc) {
728 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
729 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
730 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
731 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
732 if (!OpNode.getNode())
733 return SDValue();
734 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000735 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000736 if (N0.hasOneUse()) {
737 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
738 // use
739 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
740 if (!OpNode.getNode())
741 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000742 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000743 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000744 }
745 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000746 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000747
Juergen Ributzka68402822014-01-13 21:49:25 +0000748 if (N1.getOpcode() == Opc) {
749 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
750 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
751 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
752 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
753 if (!OpNode.getNode())
754 return SDValue();
755 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
756 }
757 if (N1.hasOneUse()) {
758 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
759 // use
760 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
761 if (!OpNode.getNode())
762 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000763 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000764 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
765 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000766 }
767 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000768
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000769 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000770}
771
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000772SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
773 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000774 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
775 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000776 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000777 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000778 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000779 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000780 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000781 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000782 assert((!To[i].getNode() ||
783 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000784 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000785 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000786 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000787 if (AddTo) {
788 // Push the new nodes and any users onto the worklist
789 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000790 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000791 AddToWorklist(To[i].getNode());
792 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000793 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000794 }
795 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000796
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000797 // Finally, if the node is now dead, remove it from the graph. The node
798 // may not be dead if the replacement process recursively simplified to
799 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000800 if (N->use_empty())
801 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000802 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000803}
804
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000805void DAGCombiner::
806CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000807 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000808 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000809 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000810 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000811
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000812 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000813 AddToWorklist(TLO.New.getNode());
814 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000815
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000816 // Finally, if the node is now dead, remove it from the graph. The node
817 // may not be dead if the replacement process recursively simplified to
818 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000819 if (TLO.Old.getNode()->use_empty())
820 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000821}
822
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000823/// Check the specified integer node value to see if it can be simplified or if
824/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000825bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000826 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000827 APInt KnownZero, KnownOne;
828 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
829 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000830
Dan Gohmane58ab792009-01-29 01:59:02 +0000831 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000832 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000833
Dan Gohmane58ab792009-01-29 01:59:02 +0000834 // Replace the old value with the new one.
835 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000836 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000837 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000838 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000839 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000840 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000841
Dan Gohmane58ab792009-01-29 01:59:02 +0000842 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000843 return true;
844}
845
Evan Cheng0abb54d2010-04-24 04:43:44 +0000846void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000847 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000848 EVT VT = Load->getValueType(0);
849 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000850
Evan Cheng0abb54d2010-04-24 04:43:44 +0000851 DEBUG(dbgs() << "\nReplacing.9 ";
852 Load->dump(&DAG);
853 dbgs() << "\nWith: ";
854 Trunc.getNode()->dump(&DAG);
855 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000856 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000857 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
858 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000859 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000860 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000861}
862
863SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
864 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000865 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000866 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000867 EVT MemVT = LD->getMemoryVT();
868 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000869 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000870 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000871 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000872 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000873 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000874 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000875 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000876 }
877
Evan Chenge19aa5c2010-04-19 19:29:22 +0000878 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000879 switch (Opc) {
880 default: break;
881 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000882 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000883 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000884 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000885 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000886 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000887 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000888 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000889 case ISD::Constant: {
890 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000891 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000892 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000893 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000894 }
895
896 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000897 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000898 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000899}
900
Evan Cheng0abb54d2010-04-24 04:43:44 +0000901SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000902 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
903 return SDValue();
904 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000905 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000906 bool Replace = false;
907 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000908 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000909 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000910 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000911
912 if (Replace)
913 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
914 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000915 DAG.getValueType(OldVT));
916}
917
Evan Cheng0abb54d2010-04-24 04:43:44 +0000918SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000919 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000920 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000921 bool Replace = false;
922 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000923 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000924 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000925 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000926
927 if (Replace)
928 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
929 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000930}
931
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000932/// Promote the specified integer binary operation if the target indicates it is
933/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
934/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000935SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
936 if (!LegalOperations)
937 return SDValue();
938
939 EVT VT = Op.getValueType();
940 if (VT.isVector() || !VT.isInteger())
941 return SDValue();
942
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000943 // If operation type is 'undesirable', e.g. i16 on x86, consider
944 // promoting it.
945 unsigned Opc = Op.getOpcode();
946 if (TLI.isTypeDesirableForOp(Opc, VT))
947 return SDValue();
948
Evan Chengaf56fac2010-04-16 06:14:10 +0000949 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000950 // Consult target whether it is a good idea to promote this operation and
951 // what's the right type to promote it to.
952 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000953 assert(PVT != VT && "Don't know what type to promote to!");
954
Evan Cheng0abb54d2010-04-24 04:43:44 +0000955 bool Replace0 = false;
956 SDValue N0 = Op.getOperand(0);
957 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000958 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000959 return SDValue();
960
Evan Cheng0abb54d2010-04-24 04:43:44 +0000961 bool Replace1 = false;
962 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000963 SDValue NN1;
964 if (N0 == N1)
965 NN1 = NN0;
966 else {
967 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000968 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000969 return SDValue();
970 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000971
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000972 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000973 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000974 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000975
976 if (Replace0)
977 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
978 if (Replace1)
979 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000980
Evan Chenge8136902010-04-27 19:48:13 +0000981 DEBUG(dbgs() << "\nPromoting ";
982 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000983 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000984 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000985 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000986 }
987 return SDValue();
988}
989
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000990/// Promote the specified integer shift operation if the target indicates it is
991/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
992/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +0000993SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
994 if (!LegalOperations)
995 return SDValue();
996
997 EVT VT = Op.getValueType();
998 if (VT.isVector() || !VT.isInteger())
999 return SDValue();
1000
1001 // If operation type is 'undesirable', e.g. i16 on x86, consider
1002 // promoting it.
1003 unsigned Opc = Op.getOpcode();
1004 if (TLI.isTypeDesirableForOp(Opc, VT))
1005 return SDValue();
1006
1007 EVT PVT = VT;
1008 // Consult target whether it is a good idea to promote this operation and
1009 // what's the right type to promote it to.
1010 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1011 assert(PVT != VT && "Don't know what type to promote to!");
1012
Evan Cheng0abb54d2010-04-24 04:43:44 +00001013 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001014 SDValue N0 = Op.getOperand(0);
1015 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001016 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001017 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001018 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001019 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001020 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001021 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001022 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001023
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001024 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001025 if (Replace)
1026 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001027
Evan Chenge8136902010-04-27 19:48:13 +00001028 DEBUG(dbgs() << "\nPromoting ";
1029 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001030 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001031 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001032 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001033 }
1034 return SDValue();
1035}
1036
Evan Chenge19aa5c2010-04-19 19:29:22 +00001037SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1038 if (!LegalOperations)
1039 return SDValue();
1040
1041 EVT VT = Op.getValueType();
1042 if (VT.isVector() || !VT.isInteger())
1043 return SDValue();
1044
1045 // If operation type is 'undesirable', e.g. i16 on x86, consider
1046 // promoting it.
1047 unsigned Opc = Op.getOpcode();
1048 if (TLI.isTypeDesirableForOp(Opc, VT))
1049 return SDValue();
1050
1051 EVT PVT = VT;
1052 // Consult target whether it is a good idea to promote this operation and
1053 // what's the right type to promote it to.
1054 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055 assert(PVT != VT && "Don't know what type to promote to!");
1056 // fold (aext (aext x)) -> (aext x)
1057 // fold (aext (zext x)) -> (zext x)
1058 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001059 DEBUG(dbgs() << "\nPromoting ";
1060 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001061 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001062 }
1063 return SDValue();
1064}
1065
1066bool DAGCombiner::PromoteLoad(SDValue Op) {
1067 if (!LegalOperations)
1068 return false;
1069
1070 EVT VT = Op.getValueType();
1071 if (VT.isVector() || !VT.isInteger())
1072 return false;
1073
1074 // If operation type is 'undesirable', e.g. i16 on x86, consider
1075 // promoting it.
1076 unsigned Opc = Op.getOpcode();
1077 if (TLI.isTypeDesirableForOp(Opc, VT))
1078 return false;
1079
1080 EVT PVT = VT;
1081 // Consult target whether it is a good idea to promote this operation and
1082 // what's the right type to promote it to.
1083 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1084 assert(PVT != VT && "Don't know what type to promote to!");
1085
Andrew Trickef9de2a2013-05-25 02:42:55 +00001086 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001087 SDNode *N = Op.getNode();
1088 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001089 EVT MemVT = LD->getMemoryVT();
1090 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001091 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001092 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001093 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001094 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001095 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001096 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001097 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1098
Evan Cheng0abb54d2010-04-24 04:43:44 +00001099 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001100 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001101 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001102 Result.getNode()->dump(&DAG);
1103 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001104 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001105 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1106 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001107 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001108 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001109 return true;
1110 }
1111 return false;
1112}
1113
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001114/// \brief Recursively delete a node which has no uses and any operands for
1115/// which it is the only use.
1116///
1117/// Note that this both deletes the nodes and removes them from the worklist.
1118/// It also adds any nodes who have had a user deleted to the worklist as they
1119/// may now have only one use and subject to other combines.
1120bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1121 if (!N->use_empty())
1122 return false;
1123
1124 SmallSetVector<SDNode *, 16> Nodes;
1125 Nodes.insert(N);
1126 do {
1127 N = Nodes.pop_back_val();
1128 if (!N)
1129 continue;
1130
1131 if (N->use_empty()) {
1132 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1133 Nodes.insert(N->getOperand(i).getNode());
1134
1135 removeFromWorklist(N);
1136 DAG.DeleteNode(N);
1137 } else {
1138 AddToWorklist(N);
1139 }
1140 } while (!Nodes.empty());
1141 return true;
1142}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001143
Chris Lattnere49c9742007-05-14 22:04:50 +00001144//===----------------------------------------------------------------------===//
1145// Main DAG Combiner implementation
1146//===----------------------------------------------------------------------===//
1147
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001148void DAGCombiner::Run(CombineLevel AtLevel) {
1149 // set the instance variables, so that the various visit routines may use it.
1150 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001151 LegalOperations = Level >= AfterLegalizeVectorOps;
1152 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001153
Evan Cheng5e7658c2008-08-29 22:21:44 +00001154 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001155 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1156 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001157 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001158
Evan Cheng5e7658c2008-08-29 22:21:44 +00001159 // Create a dummy node (which is not added to allnodes), that adds a reference
1160 // to the root node, preventing it from being deleted, and tracking any
1161 // changes of the root.
1162 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001163
James Molloy67b6b112012-02-16 09:17:04 +00001164 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001165 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001166 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001167 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001168 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001169 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001170 N = Worklist.pop_back_val();
1171 } while (!N);
1172
1173 bool GoodWorklistEntry = WorklistMap.erase(N);
1174 (void)GoodWorklistEntry;
1175 assert(GoodWorklistEntry &&
1176 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001177
Evan Cheng5e7658c2008-08-29 22:21:44 +00001178 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1179 // N is deleted from the DAG, since they too may now be dead or may have a
1180 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001181 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001182 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001183
1184 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001185
Chandler Carruth411fb402014-07-26 05:49:40 +00001186 // If this combine is running after legalizing the DAG, re-legalize any
1187 // nodes pulled off the worklist.
1188 if (Level == AfterLegalizeDAG) {
1189 SmallSetVector<SDNode *, 16> UpdatedNodes;
1190 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1191
1192 for (SDNode *LN : UpdatedNodes) {
1193 AddToWorklist(LN);
1194 AddUsersToWorklist(LN);
1195 }
1196 if (!NIsValid)
1197 continue;
1198 }
1199
Chandler Carruthb1432742014-07-28 17:55:07 +00001200 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1201
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001202 // Add any operands of the new node which have not yet been combined to the
1203 // worklist as well. Because the worklist uniques things already, this
1204 // won't repeatedly process the same operand.
1205 CombinedNodes.insert(N);
1206 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1207 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1208 AddToWorklist(N->getOperand(i).getNode());
1209
Evan Cheng5e7658c2008-08-29 22:21:44 +00001210 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001211
Craig Topperc0196b12014-04-14 00:51:57 +00001212 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001213 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001214
Evan Cheng5e7658c2008-08-29 22:21:44 +00001215 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001216
Evan Cheng5e7658c2008-08-29 22:21:44 +00001217 // If we get back the same node we passed in, rather than a new node or
1218 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001219 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001220 // mechanics for us, we have no work to do in this case.
1221 if (RV.getNode() == N)
1222 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001223
Evan Cheng5e7658c2008-08-29 22:21:44 +00001224 assert(N->getOpcode() != ISD::DELETED_NODE &&
1225 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1226 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001227
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001228 DEBUG(dbgs() << " ... into: ";
1229 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001230
Devang Patelefec7712011-05-23 22:04:42 +00001231 // Transfer debug value.
1232 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001233 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001234 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001235 else {
1236 assert(N->getValueType(0) == RV.getValueType() &&
1237 N->getNumValues() == 1 && "Type mismatch");
1238 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001239 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001241
Evan Cheng5e7658c2008-08-29 22:21:44 +00001242 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001243 AddToWorklist(RV.getNode());
1244 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001245
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001246 // Finally, if the node is now dead, remove it from the graph. The node
1247 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001248 // something else needing this node. This will also take care of adding any
1249 // operands which have lost a user to the worklist.
1250 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001251 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001252
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001253 // If the root changed (e.g. it was a dead load, update the root).
1254 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001255 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001256}
1257
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001258SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001259 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001260 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001261 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001262 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001263 case ISD::ADD: return visitADD(N);
1264 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001265 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001266 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001267 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001268 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001269 case ISD::MUL: return visitMUL(N);
1270 case ISD::SDIV: return visitSDIV(N);
1271 case ISD::UDIV: return visitUDIV(N);
1272 case ISD::SREM: return visitSREM(N);
1273 case ISD::UREM: return visitUREM(N);
1274 case ISD::MULHU: return visitMULHU(N);
1275 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001276 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1277 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001278 case ISD::SMULO: return visitSMULO(N);
1279 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001280 case ISD::SDIVREM: return visitSDIVREM(N);
1281 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001282 case ISD::AND: return visitAND(N);
1283 case ISD::OR: return visitOR(N);
1284 case ISD::XOR: return visitXOR(N);
1285 case ISD::SHL: return visitSHL(N);
1286 case ISD::SRA: return visitSRA(N);
1287 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001288 case ISD::ROTR:
1289 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001290 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001291 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001292 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001293 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001294 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001295 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001296 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001297 case ISD::SELECT_CC: return visitSELECT_CC(N);
1298 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001299 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1300 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001301 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001302 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1303 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001304 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001305 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001306 case ISD::FADD: return visitFADD(N);
1307 case ISD::FSUB: return visitFSUB(N);
1308 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001309 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001310 case ISD::FDIV: return visitFDIV(N);
1311 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001312 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001313 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001314 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1315 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1316 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1317 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1318 case ISD::FP_ROUND: return visitFP_ROUND(N);
1319 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1320 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1321 case ISD::FNEG: return visitFNEG(N);
1322 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001323 case ISD::FFLOOR: return visitFFLOOR(N);
1324 case ISD::FCEIL: return visitFCEIL(N);
1325 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001326 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001327 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001328 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001329 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001330 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001331 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001332 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1333 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001334 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001335 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001336 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001337 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001338 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001339}
1340
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001341SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001342 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001343
1344 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001345 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001346 assert(N->getOpcode() != ISD::DELETED_NODE &&
1347 "Node was deleted but visit returned NULL!");
1348
1349 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1350 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1351
1352 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001353 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001354 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001355
1356 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1357 }
1358 }
1359
Evan Chengf1005572010-04-28 07:10:39 +00001360 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001361 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001362 switch (N->getOpcode()) {
1363 default: break;
1364 case ISD::ADD:
1365 case ISD::SUB:
1366 case ISD::MUL:
1367 case ISD::AND:
1368 case ISD::OR:
1369 case ISD::XOR:
1370 RV = PromoteIntBinOp(SDValue(N, 0));
1371 break;
1372 case ISD::SHL:
1373 case ISD::SRA:
1374 case ISD::SRL:
1375 RV = PromoteIntShiftOp(SDValue(N, 0));
1376 break;
1377 case ISD::SIGN_EXTEND:
1378 case ISD::ZERO_EXTEND:
1379 case ISD::ANY_EXTEND:
1380 RV = PromoteExtend(SDValue(N, 0));
1381 break;
1382 case ISD::LOAD:
1383 if (PromoteLoad(SDValue(N, 0)))
1384 RV = SDValue(N, 0);
1385 break;
1386 }
1387 }
1388
Scott Michelcf0da6c2009-02-17 22:15:04 +00001389 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001390 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001391 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001392 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001393 SDValue N0 = N->getOperand(0);
1394 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001395
Evan Cheng31604a62008-03-22 01:55:50 +00001396 // Constant operands are canonicalized to RHS.
1397 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001398 SDValue Ops[] = {N1, N0};
1399 SDNode *CSENode;
1400 if (const BinaryWithFlagsSDNode *BinNode =
1401 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1402 CSENode = DAG.getNodeIfExists(
1403 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1404 BinNode->hasNoSignedWrap(), BinNode->isExact());
1405 } else {
1406 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1407 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001408 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001409 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001410 }
1411 }
1412
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001413 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001414}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001415
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001416/// Given a node, return its input chain if it has one, otherwise return a null
1417/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001418static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001419 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001420 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001421 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001422 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001423 return N->getOperand(NumOps-1);
1424 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001425 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001426 return N->getOperand(i);
1427 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001428 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001429}
1430
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001431SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001432 // If N has two operands, where one has an input chain equal to the other,
1433 // the 'other' chain is redundant.
1434 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001435 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001436 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001437 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001438 return N->getOperand(1);
1439 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001440
Chris Lattner48fb92f2007-05-16 06:37:59 +00001441 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001442 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001443 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001444 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001445
Jim Laskey708d0db2006-10-04 16:53:27 +00001446 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001447 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001448
Jim Laskey0463e082006-10-07 23:37:56 +00001449 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001450 // encountered.
1451 for (unsigned i = 0; i < TFs.size(); ++i) {
1452 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001453
Jim Laskey708d0db2006-10-04 16:53:27 +00001454 // Check each of the operands.
1455 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001456 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001457
Jim Laskey708d0db2006-10-04 16:53:27 +00001458 switch (Op.getOpcode()) {
1459 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001460 // Entry tokens don't need to be added to the list. They are
1461 // rededundant.
1462 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001463 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001464
Jim Laskey708d0db2006-10-04 16:53:27 +00001465 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001466 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001467 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001468 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001469 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001470 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001471 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001472 Changed = true;
1473 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001474 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001475 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001476
Jim Laskey708d0db2006-10-04 16:53:27 +00001477 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001478 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001479 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001480 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001481 else
1482 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001483 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001484 }
1485 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001486 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001487
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001488 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001489
1490 // If we've change things around then replace token factor.
1491 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001492 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001493 // The entry token is the only possible outcome.
1494 Result = DAG.getEntryNode();
1495 } else {
1496 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001497 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001498 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001499
Jim Laskeydcf983c2006-10-13 23:32:28 +00001500 // Don't add users to work list.
1501 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001502 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001503
Jim Laskey708d0db2006-10-04 16:53:27 +00001504 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001505}
1506
Chris Lattneree322b42008-02-13 07:25:05 +00001507/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001508SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001509 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001510 // Replacing results may cause a different MERGE_VALUES to suddenly
1511 // be CSE'd with N, and carry its uses with it. Iterate until no
1512 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001513 // First add the users of this node to the work list so that they
1514 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001515 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001516 do {
1517 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001518 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001519 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001520 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001521 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001522}
1523
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001524SDValue DAGCombiner::visitADD(SDNode *N) {
1525 SDValue N0 = N->getOperand(0);
1526 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001527 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1528 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001529 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001530
1531 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001532 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001533 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001534 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001535
1536 // fold (add x, 0) -> x, vector edition
1537 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1538 return N0;
1539 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1540 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001541 }
Bill Wendling0864a752008-12-10 22:36:00 +00001542
Dan Gohman06563a82007-07-03 14:03:57 +00001543 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001544 if (N0.getOpcode() == ISD::UNDEF)
1545 return N0;
1546 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001547 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001548 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001549 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001550 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001551 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001552 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001553 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001554 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001555 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001556 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001557 // fold (add Sym, c) -> Sym+c
1558 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001559 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001560 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001561 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001562 GA->getOffset() +
1563 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001564 // fold ((c1-A)+c2) -> (c1+c2)-A
1565 if (N1C && N0.getOpcode() == ISD::SUB)
1566 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001567 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001568 DAG.getConstant(N1C->getAPIntValue()+
1569 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001570 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001571 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001572 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001573 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001574 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001575 // fold ((0-A) + B) -> B-A
1576 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1577 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001578 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001579 // fold (A + (0-B)) -> A-B
1580 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1581 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001582 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001583 // fold (A+(B-A)) -> B
1584 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001585 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001586 // fold ((B-A)+A) -> B
1587 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1588 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001589 // fold (A+(B-(A+C))) to (B-C)
1590 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001591 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001592 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001593 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001594 // fold (A+(B-(C+A))) to (B-C)
1595 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001596 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001597 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001598 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001599 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001600 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1601 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001602 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001603 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001604 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001605
Dale Johannesen8c766702008-12-02 01:30:54 +00001606 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1607 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1608 SDValue N00 = N0.getOperand(0);
1609 SDValue N01 = N0.getOperand(1);
1610 SDValue N10 = N1.getOperand(0);
1611 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001612
1613 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001614 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1615 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1616 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001617 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001618
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001619 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1620 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001621
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001622 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001623 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001624 APInt LHSZero, LHSOne;
1625 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001626 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001627
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001628 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001629 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001630
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001631 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1632 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001633 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1634 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1635 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1636 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001637 }
1638 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001639
Dan Gohman954f4902010-01-19 23:30:49 +00001640 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1641 if (N1.getOpcode() == ISD::SHL &&
1642 N1.getOperand(0).getOpcode() == ISD::SUB)
1643 if (ConstantSDNode *C =
1644 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1645 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001646 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1647 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001648 N1.getOperand(0).getOperand(1),
1649 N1.getOperand(1)));
1650 if (N0.getOpcode() == ISD::SHL &&
1651 N0.getOperand(0).getOpcode() == ISD::SUB)
1652 if (ConstantSDNode *C =
1653 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1654 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001655 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1656 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001657 N0.getOperand(0).getOperand(1),
1658 N0.getOperand(1)));
1659
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001660 if (N1.getOpcode() == ISD::AND) {
1661 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001662 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001663 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1664 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001665
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001666 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1667 // and similar xforms where the inner op is either ~0 or 0.
1668 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001669 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001670 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1671 }
1672 }
1673
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001674 // add (sext i1), X -> sub X, (zext i1)
1675 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1676 N0.getOperand(0).getValueType() == MVT::i1 &&
1677 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001678 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001679 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1680 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1681 }
1682
Evan Chengf1005572010-04-28 07:10:39 +00001683 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001684}
1685
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001686SDValue DAGCombiner::visitADDC(SDNode *N) {
1687 SDValue N0 = N->getOperand(0);
1688 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001689 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1690 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001691 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001692
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001693 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001694 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001695 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001696 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001697 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001698
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001699 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001700 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001701 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001702
Chris Lattner47206662007-03-04 20:40:38 +00001703 // fold (addc x, 0) -> x + no carry out
1704 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001705 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001706 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001707
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001708 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001709 APInt LHSZero, LHSOne;
1710 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001711 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001712
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001713 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001714 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001715
Chris Lattner47206662007-03-04 20:40:38 +00001716 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1717 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001718 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001719 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001720 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001721 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001722 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001723
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001724 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001725}
1726
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001727SDValue DAGCombiner::visitADDE(SDNode *N) {
1728 SDValue N0 = N->getOperand(0);
1729 SDValue N1 = N->getOperand(1);
1730 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001731 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1732 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001733
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001734 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001735 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001736 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001737 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001738
Chris Lattner47206662007-03-04 20:40:38 +00001739 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001740 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001741 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001742
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001743 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001744}
1745
Eric Christophere5ca1e02011-02-16 04:50:12 +00001746// Since it may not be valid to emit a fold to zero for vector initializers
1747// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001748static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001749 SelectionDAG &DAG,
1750 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001751 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001752 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001753 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1754 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001755 return SDValue();
1756}
1757
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001758SDValue DAGCombiner::visitSUB(SDNode *N) {
1759 SDValue N0 = N->getOperand(0);
1760 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001761 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1762 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001763 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001764 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001765 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001766
Dan Gohmana8665142007-06-25 16:23:39 +00001767 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001768 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001769 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001770 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001771
1772 // fold (sub x, 0) -> x, vector edition
1773 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1774 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001775 }
Bill Wendling0864a752008-12-10 22:36:00 +00001776
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001777 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001778 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001779 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001780 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001781 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001782 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001783 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001784 // fold (sub x, c) -> (add x, -c)
1785 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001786 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001787 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001788 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1789 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001790 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001791 // fold A-(A-B) -> B
1792 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1793 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001794 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001795 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001796 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001797 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001798 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001799 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001800 // fold C2-(A+C1) -> (C2-C1)-A
1801 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001802 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1803 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001804 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001805 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001806 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001807 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001808 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001809 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1810 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001811 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001812 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001813 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001814 // fold ((A+(C+B))-B) -> A+C
1815 if (N0.getOpcode() == ISD::ADD &&
1816 N0.getOperand(1).getOpcode() == ISD::ADD &&
1817 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001818 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001819 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001820 // fold ((A-(B-C))-C) -> A-B
1821 if (N0.getOpcode() == ISD::SUB &&
1822 N0.getOperand(1).getOpcode() == ISD::SUB &&
1823 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001824 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001825 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001826
Dan Gohman06563a82007-07-03 14:03:57 +00001827 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001828 if (N0.getOpcode() == ISD::UNDEF)
1829 return N0;
1830 if (N1.getOpcode() == ISD::UNDEF)
1831 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001832
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001833 // If the relocation model supports it, consider symbol offsets.
1834 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001835 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001836 // fold (sub Sym, c) -> Sym-c
1837 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001838 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001839 GA->getOffset() -
1840 (uint64_t)N1C->getSExtValue());
1841 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1842 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1843 if (GA->getGlobal() == GB->getGlobal())
1844 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1845 VT);
1846 }
1847
Evan Chengf1005572010-04-28 07:10:39 +00001848 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001849}
1850
Craig Topper43a1bd62012-01-07 09:06:39 +00001851SDValue DAGCombiner::visitSUBC(SDNode *N) {
1852 SDValue N0 = N->getOperand(0);
1853 SDValue N1 = N->getOperand(1);
1854 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1855 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1856 EVT VT = N0.getValueType();
1857
1858 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001859 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001860 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1861 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001862 MVT::Glue));
1863
1864 // fold (subc x, x) -> 0 + no borrow
1865 if (N0 == N1)
1866 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001867 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001868 MVT::Glue));
1869
1870 // fold (subc x, 0) -> x + no borrow
1871 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001872 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001873 MVT::Glue));
1874
1875 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1876 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001877 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1878 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001879 MVT::Glue));
1880
1881 return SDValue();
1882}
1883
1884SDValue DAGCombiner::visitSUBE(SDNode *N) {
1885 SDValue N0 = N->getOperand(0);
1886 SDValue N1 = N->getOperand(1);
1887 SDValue CarryIn = N->getOperand(2);
1888
1889 // fold (sube x, y, false) -> (subc x, y)
1890 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001891 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001892
1893 return SDValue();
1894}
1895
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001896SDValue DAGCombiner::visitMUL(SDNode *N) {
1897 SDValue N0 = N->getOperand(0);
1898 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001899 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001900
Dan Gohman06563a82007-07-03 14:03:57 +00001901 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001902 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001903 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001904
1905 bool N0IsConst = false;
1906 bool N1IsConst = false;
1907 APInt ConstValue0, ConstValue1;
1908 // fold vector ops
1909 if (VT.isVector()) {
1910 SDValue FoldedVOp = SimplifyVBinOp(N);
1911 if (FoldedVOp.getNode()) return FoldedVOp;
1912
1913 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1914 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1915 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001916 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001917 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1918 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001919 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001920 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1921 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001922 }
1923
Nate Begeman21158fc2005-09-01 00:19:25 +00001924 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001925 if (N0IsConst && N1IsConst)
1926 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1927
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001928 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001929 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001930 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001931 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001932 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001933 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001934 // We require a splat of the entire scalar bit width for non-contiguous
1935 // bit patterns.
1936 bool IsFullSplat =
1937 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001938 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001939 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001940 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001941 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001942 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001943 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001944 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001945 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001946 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001947 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001948 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001949 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001950 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001951 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001952 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001953 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001954 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001955 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001956 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001957 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001958 DAG.getConstant(Log2Val,
1959 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001960 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001961
1962 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001963 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001964 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001965 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1966 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001967 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001968 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001969 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001970 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001971 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001972 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001973
Chris Lattner324871e2006-03-01 03:44:24 +00001974 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1975 // use.
1976 {
Craig Topperc0196b12014-04-14 00:51:57 +00001977 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001978 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001979 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001980 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1981 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001982 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001983 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001984 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001985 isa<ConstantSDNode>(N1.getOperand(1)) &&
1986 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001987 Sh = N1; Y = N0;
1988 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001989
Gabor Greiff304a7a2008-08-28 21:40:38 +00001990 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001991 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001992 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001993 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001994 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001995 }
1996 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001997
Chris Lattnerf29f5202006-03-04 23:33:26 +00001998 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001999 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2000 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2001 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002002 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2003 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002004 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002005 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002006 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002007
Nate Begeman22e251a2006-02-03 06:46:56 +00002008 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002009 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002010 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002011 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002012
Evan Chengf1005572010-04-28 07:10:39 +00002013 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002014}
2015
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002016SDValue DAGCombiner::visitSDIV(SDNode *N) {
2017 SDValue N0 = N->getOperand(0);
2018 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002019 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2020 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002021 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002022
Dan Gohmana8665142007-06-25 16:23:39 +00002023 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002024 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002025 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002026 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002027 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002028
Nate Begeman21158fc2005-09-01 00:19:25 +00002029 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002030 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002031 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002032 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002033 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002034 return N0;
2035 // fold (sdiv X, -1) -> 0-X
2036 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002037 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002038 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002039 // If we know the sign bits of both operands are zero, strength reduce to a
2040 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002041 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002042 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002043 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002044 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002045 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002046
Nate Begeman57b35672006-02-17 07:26:20 +00002047 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002048 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2049 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002050 // If dividing by powers of two is cheap, then don't perform the following
2051 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002052 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002053 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002054
Chad Rosier17020f92014-07-23 14:57:52 +00002055 // Target-specific implementation of sdiv x, pow2.
2056 SDValue Res = BuildSDIVPow2(N);
2057 if (Res.getNode())
2058 return Res;
2059
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002060 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002061
Chris Lattner471627c2006-02-16 08:02:36 +00002062 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002063 SDValue SGN =
2064 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2065 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2066 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002067 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002068
Chris Lattner471627c2006-02-16 08:02:36 +00002069 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002070 SDValue SRL =
2071 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2072 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2073 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002074 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002075 AddToWorklist(SRL.getNode());
2076 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002077 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002078 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002079
Nate Begeman4dd38312005-10-21 00:02:42 +00002080 // If we're dividing by a positive value, we're done. Otherwise, we must
2081 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002082 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002083 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002084
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002085 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002086 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002087 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002088
Nate Begemanc6f067a2005-10-20 02:15:44 +00002089 // if integer divide is expensive and we satisfy the requirements, emit an
2090 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002091 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002092 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002093 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002094 }
Dan Gohmana8665142007-06-25 16:23:39 +00002095
Dan Gohman06563a82007-07-03 14:03:57 +00002096 // undef / X -> 0
2097 if (N0.getOpcode() == ISD::UNDEF)
2098 return DAG.getConstant(0, VT);
2099 // X / undef -> undef
2100 if (N1.getOpcode() == ISD::UNDEF)
2101 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002102
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002103 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002104}
2105
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002106SDValue DAGCombiner::visitUDIV(SDNode *N) {
2107 SDValue N0 = N->getOperand(0);
2108 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002109 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2110 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002111 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002112
Dan Gohmana8665142007-06-25 16:23:39 +00002113 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002114 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002115 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002116 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002117 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002118
Nate Begeman21158fc2005-09-01 00:19:25 +00002119 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002120 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002121 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002122 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002123 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002124 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002125 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002126 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002127 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002128 if (N1.getOpcode() == ISD::SHL) {
2129 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002130 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002131 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002132 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002133 N1.getOperand(1),
2134 DAG.getConstant(SHC->getAPIntValue()
2135 .logBase2(),
2136 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002137 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002138 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002139 }
2140 }
2141 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002142 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002143 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002144 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002145 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002146 }
Dan Gohmana8665142007-06-25 16:23:39 +00002147
Dan Gohman06563a82007-07-03 14:03:57 +00002148 // undef / X -> 0
2149 if (N0.getOpcode() == ISD::UNDEF)
2150 return DAG.getConstant(0, VT);
2151 // X / undef -> undef
2152 if (N1.getOpcode() == ISD::UNDEF)
2153 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002154
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002155 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002156}
2157
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002158SDValue DAGCombiner::visitSREM(SDNode *N) {
2159 SDValue N0 = N->getOperand(0);
2160 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002161 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2162 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002163 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002164
Nate Begeman21158fc2005-09-01 00:19:25 +00002165 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002166 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002167 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002168 // If we know the sign bits of both operands are zero, strength reduce to a
2169 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002170 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002171 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002172 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002173 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002174
Dan Gohman9a693412007-11-26 23:46:11 +00002175 // If X/C can be simplified by the division-by-constant logic, lower
2176 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002177 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002178 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002179 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002180 SDValue OptimizedDiv = combine(Div.getNode());
2181 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002182 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002183 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002184 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002185 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002186 return Sub;
2187 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002188 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002189
Dan Gohman06563a82007-07-03 14:03:57 +00002190 // undef % X -> 0
2191 if (N0.getOpcode() == ISD::UNDEF)
2192 return DAG.getConstant(0, VT);
2193 // X % undef -> undef
2194 if (N1.getOpcode() == ISD::UNDEF)
2195 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002196
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002197 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002198}
2199
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002200SDValue DAGCombiner::visitUREM(SDNode *N) {
2201 SDValue N0 = N->getOperand(0);
2202 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002203 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2204 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002205 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002206
Nate Begeman21158fc2005-09-01 00:19:25 +00002207 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002208 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002209 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002210 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002211 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002212 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002213 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002214 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2215 if (N1.getOpcode() == ISD::SHL) {
2216 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002217 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002218 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002219 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002220 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002221 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002222 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002223 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002224 }
2225 }
2226 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002227
Dan Gohman9a693412007-11-26 23:46:11 +00002228 // If X/C can be simplified by the division-by-constant logic, lower
2229 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002230 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002231 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002232 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002233 SDValue OptimizedDiv = combine(Div.getNode());
2234 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002235 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002236 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002237 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002238 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002239 return Sub;
2240 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002241 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002242
Dan Gohman06563a82007-07-03 14:03:57 +00002243 // undef % X -> 0
2244 if (N0.getOpcode() == ISD::UNDEF)
2245 return DAG.getConstant(0, VT);
2246 // X % undef -> undef
2247 if (N1.getOpcode() == ISD::UNDEF)
2248 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002249
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002250 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002251}
2252
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002253SDValue DAGCombiner::visitMULHS(SDNode *N) {
2254 SDValue N0 = N->getOperand(0);
2255 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002256 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002257 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002258 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002259
Nate Begeman21158fc2005-09-01 00:19:25 +00002260 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002261 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002262 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002263 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002264 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002265 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002266 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002267 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002268 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002269 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002270 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002271
Chris Lattner10bd29f2010-12-13 08:39:01 +00002272 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2273 // plus a shift.
2274 if (VT.isSimple() && !VT.isVector()) {
2275 MVT Simple = VT.getSimpleVT();
2276 unsigned SimpleSize = Simple.getSizeInBits();
2277 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2278 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2279 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2280 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2281 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002282 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002283 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002284 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2285 }
2286 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002287
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002288 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002289}
2290
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002291SDValue DAGCombiner::visitMULHU(SDNode *N) {
2292 SDValue N0 = N->getOperand(0);
2293 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002294 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002295 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002296 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002297
Nate Begeman21158fc2005-09-01 00:19:25 +00002298 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002299 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002300 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002301 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002302 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002303 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002304 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002305 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002306 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002307
Chris Lattner10bd29f2010-12-13 08:39:01 +00002308 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2309 // plus a shift.
2310 if (VT.isSimple() && !VT.isVector()) {
2311 MVT Simple = VT.getSimpleVT();
2312 unsigned SimpleSize = Simple.getSizeInBits();
2313 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2314 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2315 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2316 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2317 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2318 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002319 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002320 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2321 }
2322 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002323
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002324 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002325}
2326
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002327/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2328/// give the opcodes for the two computations that are being performed. Return
2329/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002330SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002331 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002332 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002333 bool HiExists = N->hasAnyUseOfValue(1);
2334 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002335 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002336 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002337 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002338 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002339 }
2340
2341 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002342 bool LoExists = N->hasAnyUseOfValue(0);
2343 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002344 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002345 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002346 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002347 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002348 }
2349
Evan Chengece4c682007-11-08 09:25:29 +00002350 // If both halves are used, return as it is.
2351 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002352 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002353
2354 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002355 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002356 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002357 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002358 SDValue LoOpt = combine(Lo.getNode());
2359 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002360 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002361 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002362 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002363 }
2364
Evan Chengece4c682007-11-08 09:25:29 +00002365 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002366 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002367 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002368 SDValue HiOpt = combine(Hi.getNode());
2369 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002370 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002371 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002372 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002373 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002374
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002375 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002376}
2377
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002378SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2379 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002380 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002381
Chris Lattner15090e12010-12-15 06:04:19 +00002382 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002383 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002384
2385 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2386 // plus a shift.
2387 if (VT.isSimple() && !VT.isVector()) {
2388 MVT Simple = VT.getSimpleVT();
2389 unsigned SimpleSize = Simple.getSizeInBits();
2390 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2391 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2392 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2393 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2394 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2395 // Compute the high part as N1.
2396 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002397 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002398 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2399 // Compute the low part as N0.
2400 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2401 return CombineTo(N, Lo, Hi);
2402 }
2403 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002404
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002405 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002406}
2407
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002408SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2409 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002410 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002411
Chris Lattner15090e12010-12-15 06:04:19 +00002412 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002413 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002414
Chris Lattner15090e12010-12-15 06:04:19 +00002415 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2416 // plus a shift.
2417 if (VT.isSimple() && !VT.isVector()) {
2418 MVT Simple = VT.getSimpleVT();
2419 unsigned SimpleSize = Simple.getSizeInBits();
2420 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2421 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2422 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2423 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2424 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2425 // Compute the high part as N1.
2426 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002427 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002428 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2429 // Compute the low part as N0.
2430 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2431 return CombineTo(N, Lo, Hi);
2432 }
2433 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002434
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002435 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002436}
2437
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002438SDValue DAGCombiner::visitSMULO(SDNode *N) {
2439 // (smulo x, 2) -> (saddo x, x)
2440 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2441 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002442 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002443 N->getOperand(0), N->getOperand(0));
2444
2445 return SDValue();
2446}
2447
2448SDValue DAGCombiner::visitUMULO(SDNode *N) {
2449 // (umulo x, 2) -> (uaddo x, x)
2450 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2451 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002452 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002453 N->getOperand(0), N->getOperand(0));
2454
2455 return SDValue();
2456}
2457
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002458SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2459 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002460 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002461
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002462 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002463}
2464
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002465SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2466 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002467 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002468
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002469 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002470}
2471
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002472/// If this is a binary operator with two operands of the same opcode, try to
2473/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002474SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2475 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002476 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002477 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002478
Dan Gohmandd5286d2010-01-14 03:08:49 +00002479 // Bail early if none of these transforms apply.
2480 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2481
Chris Lattner002ee912006-05-05 06:31:05 +00002482 // For each of OP in AND/OR/XOR:
2483 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2484 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2485 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002486 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002487 //
2488 // do not sink logical op inside of a vector extend, since it may combine
2489 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002490 EVT Op0VT = N0.getOperand(0).getValueType();
2491 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002492 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002493 // Avoid infinite looping with PromoteIntBinOp.
2494 (N0.getOpcode() == ISD::ANY_EXTEND &&
2495 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002496 (N0.getOpcode() == ISD::TRUNCATE &&
2497 (!TLI.isZExtFree(VT, Op0VT) ||
2498 !TLI.isTruncateFree(Op0VT, VT)) &&
2499 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002500 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002501 Op0VT == N1.getOperand(0).getValueType() &&
2502 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002503 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002504 N0.getOperand(0).getValueType(),
2505 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002506 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002507 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002508 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002509
Chris Lattner5ac42932006-05-05 06:10:43 +00002510 // For each of OP in SHL/SRL/SRA/AND...
2511 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2512 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2513 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002514 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002515 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002516 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002517 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002518 N0.getOperand(0).getValueType(),
2519 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002520 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002521 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002522 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002523 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002524
Nadav Rotemb0783502012-04-01 19:31:22 +00002525 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2526 // Only perform this optimization after type legalization and before
2527 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2528 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2529 // we don't want to undo this promotion.
2530 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2531 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002532 if ((N0.getOpcode() == ISD::BITCAST ||
2533 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2534 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002535 SDValue In0 = N0.getOperand(0);
2536 SDValue In1 = N1.getOperand(0);
2537 EVT In0Ty = In0.getValueType();
2538 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002539 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002540 // If both incoming values are integers, and the original types are the
2541 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002542 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002543 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2544 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002545 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002546 return BC;
2547 }
2548 }
2549
2550 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2551 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2552 // If both shuffles use the same mask, and both shuffle within a single
2553 // vector, then it is worthwhile to move the swizzle after the operation.
2554 // The type-legalizer generates this pattern when loading illegal
2555 // vector types from memory. In many cases this allows additional shuffle
2556 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002557 // There are other cases where moving the shuffle after the xor/and/or
2558 // is profitable even if shuffles don't perform a swizzle.
2559 // If both shuffles use the same mask, and both shuffles have the same first
2560 // or second operand, then it might still be profitable to move the shuffle
2561 // after the xor/and/or operation.
2562 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002563 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2564 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002565
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002566 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002567 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002568
Nadav Rotemb0783502012-04-01 19:31:22 +00002569 // Check that both shuffles use the same mask. The masks are known to be of
2570 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002571 // Check also that shuffles have only one use to avoid introducing extra
2572 // instructions.
2573 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2574 SVN0->getMask().equals(SVN1->getMask())) {
2575 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002576
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002577 // Don't try to fold this node if it requires introducing a
2578 // build vector of all zeros that might be illegal at this stage.
2579 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2580 if (!LegalTypes)
2581 ShOp = DAG.getConstant(0, VT);
2582 else
2583 ShOp = SDValue();
2584 }
2585
2586 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2587 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2588 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2589 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2590 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2591 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002592 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002593 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2594 &SVN0->getMask()[0]);
2595 }
2596
2597 // Don't try to fold this node if it requires introducing a
2598 // build vector of all zeros that might be illegal at this stage.
2599 ShOp = N0->getOperand(0);
2600 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2601 if (!LegalTypes)
2602 ShOp = DAG.getConstant(0, VT);
2603 else
2604 ShOp = SDValue();
2605 }
2606
2607 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2608 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2609 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2610 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2611 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2612 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002613 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002614 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2615 &SVN0->getMask()[0]);
2616 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002617 }
2618 }
Craig Topper9c3da312012-04-09 07:19:09 +00002619
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002620 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002621}
2622
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002623SDValue DAGCombiner::visitAND(SDNode *N) {
2624 SDValue N0 = N->getOperand(0);
2625 SDValue N1 = N->getOperand(1);
2626 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002627 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2628 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002629 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002630 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002631
Dan Gohmana8665142007-06-25 16:23:39 +00002632 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002633 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002634 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002635 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002636
2637 // fold (and x, 0) -> 0, vector edition
2638 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002639 // do not return N0, because undef node may exist in N0
2640 return DAG.getConstant(
2641 APInt::getNullValue(
2642 N0.getValueType().getScalarType().getSizeInBits()),
2643 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002644 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002645 // do not return N1, because undef node may exist in N1
2646 return DAG.getConstant(
2647 APInt::getNullValue(
2648 N1.getValueType().getScalarType().getSizeInBits()),
2649 N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002650
2651 // fold (and x, -1) -> x, vector edition
2652 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2653 return N1;
2654 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2655 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002656 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002657
Dan Gohman06563a82007-07-03 14:03:57 +00002658 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002659 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002660 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002661 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002662 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002663 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002664 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002665 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002666 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002667 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002668 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002669 return N0;
2670 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002671 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002672 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002673 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002674 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002675 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002676 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002677 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002678 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002679 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002680 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002681 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002682 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002683 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2684 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002685 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002686 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002687 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002688 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002689 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002690 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002691
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002692 // Replace uses of the AND with uses of the Zero extend node.
2693 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002694
Chris Lattner49beaf42006-02-02 07:17:31 +00002695 // We actually want to replace all uses of the any_extend with the
2696 // zero_extend, to avoid duplicating things. This will later cause this
2697 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002698 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002699 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002700 }
2701 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002702 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002703 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2704 // already be zero by virtue of the width of the base type of the load.
2705 //
2706 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2707 // more cases.
2708 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2709 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2710 N0.getOpcode() == ISD::LOAD) {
2711 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2712 N0 : N0.getOperand(0) );
2713
2714 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2715 // This can be a pure constant or a vector splat, in which case we treat the
2716 // vector as a scalar and use the splat value.
2717 APInt Constant = APInt::getNullValue(1);
2718 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2719 Constant = C->getAPIntValue();
2720 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2721 APInt SplatValue, SplatUndef;
2722 unsigned SplatBitSize;
2723 bool HasAnyUndefs;
2724 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2725 SplatBitSize, HasAnyUndefs);
2726 if (IsSplat) {
2727 // Undef bits can contribute to a possible optimisation if set, so
2728 // set them.
2729 SplatValue |= SplatUndef;
2730
2731 // The splat value may be something like "0x00FFFFFF", which means 0 for
2732 // the first vector value and FF for the rest, repeating. We need a mask
2733 // that will apply equally to all members of the vector, so AND all the
2734 // lanes of the constant together.
2735 EVT VT = Vector->getValueType(0);
2736 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002737
2738 // If the splat value has been compressed to a bitlength lower
2739 // than the size of the vector lane, we need to re-expand it to
2740 // the lane size.
2741 if (BitWidth > SplatBitSize)
2742 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2743 SplatBitSize < BitWidth;
2744 SplatBitSize = SplatBitSize * 2)
2745 SplatValue |= SplatValue.shl(SplatBitSize);
2746
James Molloy862fe492012-02-20 12:02:38 +00002747 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002748 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002749 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2750 }
2751 }
2752
2753 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2754 // actually legal and isn't going to get expanded, else this is a false
2755 // optimisation.
2756 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2757 Load->getMemoryVT());
2758
2759 // Resize the constant to the same size as the original memory access before
2760 // extension. If it is still the AllOnesValue then this AND is completely
2761 // unneeded.
2762 Constant =
2763 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2764
2765 bool B;
2766 switch (Load->getExtensionType()) {
2767 default: B = false; break;
2768 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2769 case ISD::ZEXTLOAD:
2770 case ISD::NON_EXTLOAD: B = true; break;
2771 }
2772
2773 if (B && Constant.isAllOnesValue()) {
2774 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2775 // preserve semantics once we get rid of the AND.
2776 SDValue NewLoad(Load, 0);
2777 if (Load->getExtensionType() == ISD::EXTLOAD) {
2778 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002779 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002780 Load->getChain(), Load->getBasePtr(),
2781 Load->getOffset(), Load->getMemoryVT(),
2782 Load->getMemOperand());
2783 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002784 if (Load->getNumValues() == 3) {
2785 // PRE/POST_INC loads have 3 values.
2786 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2787 NewLoad.getValue(2) };
2788 CombineTo(Load, To, 3, true);
2789 } else {
2790 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2791 }
James Molloy862fe492012-02-20 12:02:38 +00002792 }
2793
2794 // Fold the AND away, taking care not to fold to the old load node if we
2795 // replaced it.
2796 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2797
2798 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2799 }
2800 }
Nate Begeman049b7482005-09-09 19:49:52 +00002801 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2802 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2803 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2804 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002805
Tom Stellard7783b0a2014-06-12 16:04:47 +00002806 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002807 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002808 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002809 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002810 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002811 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002812 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002813 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002814 }
Bill Wendling86171912009-01-30 20:43:18 +00002815 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002816 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002817 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002818 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002819 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002820 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002821 }
Bill Wendling86171912009-01-30 20:43:18 +00002822 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002823 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002824 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002825 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002826 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002827 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002828 }
2829 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002830 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2831 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2832 Op0 == Op1 && LL.getValueType().isInteger() &&
2833 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2834 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2835 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2836 cast<ConstantSDNode>(RR)->isNullValue()))) {
2837 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2838 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002839 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002840 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2841 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2842 }
Nate Begeman049b7482005-09-09 19:49:52 +00002843 // canonicalize equivalent to ll == rl
2844 if (LL == RR && LR == RL) {
2845 Op1 = ISD::getSetCCSwappedOperands(Op1);
2846 std::swap(RL, RR);
2847 }
2848 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002849 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002850 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002851 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002852 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002853 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2854 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002855 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002856 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002857 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002858 }
2859 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002860
Bill Wendling86171912009-01-30 20:43:18 +00002861 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002862 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002863 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002864 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002865 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002866
Nate Begemandc7bba92006-02-03 22:24:05 +00002867 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2868 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002869 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002870 SimplifyDemandedBits(SDValue(N, 0)))
2871 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002872
Nate Begeman02b23c62005-10-13 03:11:28 +00002873 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002874 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002875 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002876 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002877 // If we zero all the possible extended bits, then we can turn this into
2878 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002879 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002880 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002881 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002882 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002883 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002884 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002885 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002886 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002887 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002888 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002889 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002890 }
2891 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002892 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002893 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002894 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002895 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002896 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002897 // If we zero all the possible extended bits, then we can turn this into
2898 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002899 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002900 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002901 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002902 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002903 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002904 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002905 LN0->getChain(), LN0->getBasePtr(),
2906 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002907 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002908 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002910 }
2911 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002912
Chris Lattnerf0032b32006-02-28 06:49:37 +00002913 // fold (and (load x), 255) -> (zextload x, i8)
2914 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002915 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2916 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2917 (N0.getOpcode() == ISD::ANY_EXTEND &&
2918 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2919 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2920 LoadSDNode *LN0 = HasAnyExt
2921 ? cast<LoadSDNode>(N0.getOperand(0))
2922 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002923 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002924 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002925 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002926 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2927 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2928 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002929
Evan Cheng166a4e62010-01-06 19:38:29 +00002930 if (ExtVT == LoadedVT &&
2931 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002932 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002933
2934 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002935 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002936 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2937 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002938 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002939 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2940 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2941 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002942
Chris Lattner88de3842010-01-07 21:53:27 +00002943 // Do not change the width of a volatile load.
2944 // Do not generate loads of non-round integer types since these can
2945 // be expensive (and would be wrong if the type is not byte sized).
2946 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2947 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2948 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002949
Chris Lattner88de3842010-01-07 21:53:27 +00002950 unsigned Alignment = LN0->getAlignment();
2951 SDValue NewPtr = LN0->getBasePtr();
2952
2953 // For big endian targets, we need to add an offset to the pointer
2954 // to load the correct bytes. For little endian systems, we merely
2955 // need to read fewer bytes from the same pointer.
2956 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002957 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2958 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2959 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002960 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002961 NewPtr, DAG.getConstant(PtrOff, PtrType));
2962 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002963 }
Chris Lattner88de3842010-01-07 21:53:27 +00002964
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002965 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002966
Chris Lattner88de3842010-01-07 21:53:27 +00002967 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2968 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002969 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002970 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002971 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002972 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00002973 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002974 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002975 CombineTo(LN0, Load, Load.getValue(1));
2976 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002977 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002978 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002979 }
2980 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002981
Evan Chenge6a3b032012-07-17 18:54:11 +00002982 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2983 VT.getSizeInBits() <= 64) {
2984 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2985 APInt ADDC = ADDI->getAPIntValue();
2986 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2987 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2988 // immediate for an add, but it is legal if its top c2 bits are set,
2989 // transform the ADD so the immediate doesn't need to be materialized
2990 // in a register.
2991 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2992 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2993 SRLI->getZExtValue());
2994 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2995 ADDC |= Mask;
2996 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2997 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002998 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002999 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3000 CombineTo(N0.getNode(), NewAdd);
3001 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3002 }
3003 }
3004 }
3005 }
3006 }
3007 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003008
Tim Northover819bfb52013-08-27 13:46:45 +00003009 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3010 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3011 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3012 N0.getOperand(1), false);
3013 if (BSwap.getNode())
3014 return BSwap;
3015 }
3016
Evan Chengf1005572010-04-28 07:10:39 +00003017 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003018}
3019
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003020/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003021SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3022 bool DemandHighBits) {
3023 if (!LegalOperations)
3024 return SDValue();
3025
3026 EVT VT = N->getValueType(0);
3027 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3028 return SDValue();
3029 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3030 return SDValue();
3031
3032 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3033 bool LookPassAnd0 = false;
3034 bool LookPassAnd1 = false;
3035 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3036 std::swap(N0, N1);
3037 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3038 std::swap(N0, N1);
3039 if (N0.getOpcode() == ISD::AND) {
3040 if (!N0.getNode()->hasOneUse())
3041 return SDValue();
3042 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3043 if (!N01C || N01C->getZExtValue() != 0xFF00)
3044 return SDValue();
3045 N0 = N0.getOperand(0);
3046 LookPassAnd0 = true;
3047 }
3048
3049 if (N1.getOpcode() == ISD::AND) {
3050 if (!N1.getNode()->hasOneUse())
3051 return SDValue();
3052 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3053 if (!N11C || N11C->getZExtValue() != 0xFF)
3054 return SDValue();
3055 N1 = N1.getOperand(0);
3056 LookPassAnd1 = true;
3057 }
3058
3059 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3060 std::swap(N0, N1);
3061 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3062 return SDValue();
3063 if (!N0.getNode()->hasOneUse() ||
3064 !N1.getNode()->hasOneUse())
3065 return SDValue();
3066
3067 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3068 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3069 if (!N01C || !N11C)
3070 return SDValue();
3071 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3072 return SDValue();
3073
3074 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3075 SDValue N00 = N0->getOperand(0);
3076 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3077 if (!N00.getNode()->hasOneUse())
3078 return SDValue();
3079 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3080 if (!N001C || N001C->getZExtValue() != 0xFF)
3081 return SDValue();
3082 N00 = N00.getOperand(0);
3083 LookPassAnd0 = true;
3084 }
3085
3086 SDValue N10 = N1->getOperand(0);
3087 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3088 if (!N10.getNode()->hasOneUse())
3089 return SDValue();
3090 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3091 if (!N101C || N101C->getZExtValue() != 0xFF00)
3092 return SDValue();
3093 N10 = N10.getOperand(0);
3094 LookPassAnd1 = true;
3095 }
3096
3097 if (N00 != N10)
3098 return SDValue();
3099
Tim Northover819bfb52013-08-27 13:46:45 +00003100 // Make sure everything beyond the low halfword gets set to zero since the SRL
3101 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003102 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003103 if (DemandHighBits && OpSizeInBits > 16) {
3104 // If the left-shift isn't masked out then the only way this is a bswap is
3105 // if all bits beyond the low 8 are 0. In that case the entire pattern
3106 // reduces to a left shift anyway: leave it for other parts of the combiner.
3107 if (!LookPassAnd0)
3108 return SDValue();
3109
3110 // However, if the right shift isn't masked out then it might be because
3111 // it's not needed. See if we can spot that too.
3112 if (!LookPassAnd1 &&
3113 !DAG.MaskedValueIsZero(
3114 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3115 return SDValue();
3116 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003117
Andrew Trickef9de2a2013-05-25 02:42:55 +00003118 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003119 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003120 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003121 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3122 return Res;
3123}
3124
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003125/// Return true if the specified node is an element that makes up a 32-bit
3126/// packed halfword byteswap.
3127/// ((x & 0x000000ff) << 8) |
3128/// ((x & 0x0000ff00) >> 8) |
3129/// ((x & 0x00ff0000) << 8) |
3130/// ((x & 0xff000000) >> 8)
Craig Topperb94011f2013-07-14 04:42:23 +00003131static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003132 if (!N.getNode()->hasOneUse())
3133 return false;
3134
3135 unsigned Opc = N.getOpcode();
3136 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3137 return false;
3138
3139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3140 if (!N1C)
3141 return false;
3142
3143 unsigned Num;
3144 switch (N1C->getZExtValue()) {
3145 default:
3146 return false;
3147 case 0xFF: Num = 0; break;
3148 case 0xFF00: Num = 1; break;
3149 case 0xFF0000: Num = 2; break;
3150 case 0xFF000000: Num = 3; break;
3151 }
3152
3153 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3154 SDValue N0 = N.getOperand(0);
3155 if (Opc == ISD::AND) {
3156 if (Num == 0 || Num == 2) {
3157 // (x >> 8) & 0xff
3158 // (x >> 8) & 0xff0000
3159 if (N0.getOpcode() != ISD::SRL)
3160 return false;
3161 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3162 if (!C || C->getZExtValue() != 8)
3163 return false;
3164 } else {
3165 // (x << 8) & 0xff00
3166 // (x << 8) & 0xff000000
3167 if (N0.getOpcode() != ISD::SHL)
3168 return false;
3169 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3170 if (!C || C->getZExtValue() != 8)
3171 return false;
3172 }
3173 } else if (Opc == ISD::SHL) {
3174 // (x & 0xff) << 8
3175 // (x & 0xff0000) << 8
3176 if (Num != 0 && Num != 2)
3177 return false;
3178 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3179 if (!C || C->getZExtValue() != 8)
3180 return false;
3181 } else { // Opc == ISD::SRL
3182 // (x & 0xff00) >> 8
3183 // (x & 0xff000000) >> 8
3184 if (Num != 1 && Num != 3)
3185 return false;
3186 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3187 if (!C || C->getZExtValue() != 8)
3188 return false;
3189 }
3190
3191 if (Parts[Num])
3192 return false;
3193
3194 Parts[Num] = N0.getOperand(0).getNode();
3195 return true;
3196}
3197
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003198/// Match a 32-bit packed halfword bswap. That is
3199/// ((x & 0x000000ff) << 8) |
3200/// ((x & 0x0000ff00) >> 8) |
3201/// ((x & 0x00ff0000) << 8) |
3202/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003203/// => (rotl (bswap x), 16)
3204SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3205 if (!LegalOperations)
3206 return SDValue();
3207
3208 EVT VT = N->getValueType(0);
3209 if (VT != MVT::i32)
3210 return SDValue();
3211 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3212 return SDValue();
3213
Craig Topperc0196b12014-04-14 00:51:57 +00003214 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003215 // Look for either
3216 // (or (or (and), (and)), (or (and), (and)))
3217 // (or (or (or (and), (and)), (and)), (and))
3218 if (N0.getOpcode() != ISD::OR)
3219 return SDValue();
3220 SDValue N00 = N0.getOperand(0);
3221 SDValue N01 = N0.getOperand(1);
3222
Evan Chengbf0baa92012-12-13 01:34:32 +00003223 if (N1.getOpcode() == ISD::OR &&
3224 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003225 // (or (or (and), (and)), (or (and), (and)))
3226 SDValue N000 = N00.getOperand(0);
3227 if (!isBSwapHWordElement(N000, Parts))
3228 return SDValue();
3229
3230 SDValue N001 = N00.getOperand(1);
3231 if (!isBSwapHWordElement(N001, Parts))
3232 return SDValue();
3233 SDValue N010 = N01.getOperand(0);
3234 if (!isBSwapHWordElement(N010, Parts))
3235 return SDValue();
3236 SDValue N011 = N01.getOperand(1);
3237 if (!isBSwapHWordElement(N011, Parts))
3238 return SDValue();
3239 } else {
3240 // (or (or (or (and), (and)), (and)), (and))
3241 if (!isBSwapHWordElement(N1, Parts))
3242 return SDValue();
3243 if (!isBSwapHWordElement(N01, Parts))
3244 return SDValue();
3245 if (N00.getOpcode() != ISD::OR)
3246 return SDValue();
3247 SDValue N000 = N00.getOperand(0);
3248 if (!isBSwapHWordElement(N000, Parts))
3249 return SDValue();
3250 SDValue N001 = N00.getOperand(1);
3251 if (!isBSwapHWordElement(N001, Parts))
3252 return SDValue();
3253 }
3254
3255 // Make sure the parts are all coming from the same node.
3256 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3257 return SDValue();
3258
Andrew Trickef9de2a2013-05-25 02:42:55 +00003259 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003260 SDValue(Parts[0],0));
3261
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003262 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003263 // do (x << 16) | (x >> 16).
3264 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3265 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003266 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003267 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003268 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3269 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3270 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3271 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003272}
3273
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003274SDValue DAGCombiner::visitOR(SDNode *N) {
3275 SDValue N0 = N->getOperand(0);
3276 SDValue N1 = N->getOperand(1);
3277 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003278 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003280 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003281
Dan Gohmana8665142007-06-25 16:23:39 +00003282 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003283 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003284 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003285 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003286
3287 // fold (or x, 0) -> x, vector edition
3288 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3289 return N1;
3290 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3291 return N0;
3292
3293 // fold (or x, -1) -> -1, vector edition
3294 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003295 // do not return N0, because undef node may exist in N0
3296 return DAG.getConstant(
3297 APInt::getAllOnesValue(
3298 N0.getValueType().getScalarType().getSizeInBits()),
3299 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003300 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003301 // do not return N1, because undef node may exist in N1
3302 return DAG.getConstant(
3303 APInt::getAllOnesValue(
3304 N1.getValueType().getScalarType().getSizeInBits()),
3305 N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003306
3307 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3308 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3309 // Do this only if the resulting shuffle is legal.
3310 if (isa<ShuffleVectorSDNode>(N0) &&
3311 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003312 // Avoid folding a node with illegal type.
3313 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003314 N0->getOperand(1) == N1->getOperand(1) &&
3315 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3316 bool CanFold = true;
3317 unsigned NumElts = VT.getVectorNumElements();
3318 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3319 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3320 // We construct two shuffle masks:
3321 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3322 // and N1 as the second operand.
3323 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3324 // and N0 as the second operand.
3325 // We do this because OR is commutable and therefore there might be
3326 // two ways to fold this node into a shuffle.
3327 SmallVector<int,4> Mask1;
3328 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003329
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003330 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3331 int M0 = SV0->getMaskElt(i);
3332 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003333
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003334 // Both shuffle indexes are undef. Propagate Undef.
3335 if (M0 < 0 && M1 < 0) {
3336 Mask1.push_back(M0);
3337 Mask2.push_back(M0);
3338 continue;
3339 }
3340
3341 if (M0 < 0 || M1 < 0 ||
3342 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3343 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3344 CanFold = false;
3345 break;
3346 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003347
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003348 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3349 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3350 }
3351
3352 if (CanFold) {
3353 // Fold this sequence only if the resulting shuffle is 'legal'.
3354 if (TLI.isShuffleMaskLegal(Mask1, VT))
3355 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3356 N1->getOperand(0), &Mask1[0]);
3357 if (TLI.isShuffleMaskLegal(Mask2, VT))
3358 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3359 N0->getOperand(0), &Mask2[0]);
3360 }
3361 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003362 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003363
Dan Gohman06563a82007-07-03 14:03:57 +00003364 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003365 if (!LegalOperations &&
3366 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003367 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3368 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3369 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003370 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003371 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003372 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003373 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003374 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003375 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003376 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003377 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003378 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003379 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003380 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003381 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003382 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003383 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003384 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003385
3386 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3387 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003388 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003389 return BSwap;
3390 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003391 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003392 return BSwap;
3393
Nate Begeman22e251a2006-02-03 06:46:56 +00003394 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003395 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003396 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003397 return ROR;
3398 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003399 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003400 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003401 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003402 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003403 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3404 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3405 if (!COR.getNode())
3406 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003407 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3408 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003409 N0.getOperand(0), N1), COR);
3410 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003411 }
Nate Begeman049b7482005-09-09 19:49:52 +00003412 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3413 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3414 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3415 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003416
Nate Begeman049b7482005-09-09 19:49:52 +00003417 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003418 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003419 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3420 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003421 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003422 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003423 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003424 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003425 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003426 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003427 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003428 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3429 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003430 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003431 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003432 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003433 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003434 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003435 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003436 }
3437 }
3438 // canonicalize equivalent to ll == rl
3439 if (LL == RR && LR == RL) {
3440 Op1 = ISD::getSetCCSwappedOperands(Op1);
3441 std::swap(RL, RR);
3442 }
3443 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003444 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003445 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003446 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003447 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003448 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3449 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003450 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003451 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003452 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003453 }
3454 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003455
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003456 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003457 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003458 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003459 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003460 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003461
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003462 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003463 if (N0.getOpcode() == ISD::AND &&
3464 N1.getOpcode() == ISD::AND &&
3465 N0.getOperand(1).getOpcode() == ISD::Constant &&
3466 N1.getOperand(1).getOpcode() == ISD::Constant &&
3467 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003468 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003469 // We can only do this xform if we know that bits from X that are set in C2
3470 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003471 const APInt &LHSMask =
3472 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3473 const APInt &RHSMask =
3474 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003475
Dan Gohman309d3d52007-06-22 14:59:07 +00003476 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3477 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003478 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003479 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003480 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003481 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003482 }
3483 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003484
Chris Lattner97614c82006-09-14 20:50:57 +00003485 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003486 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003487 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003488
Dan Gohman600f62b2010-06-24 14:30:44 +00003489 // Simplify the operands using demanded-bits information.
3490 if (!VT.isVector() &&
3491 SimplifyDemandedBits(SDValue(N, 0)))
3492 return SDValue(N, 0);
3493
Evan Chengf1005572010-04-28 07:10:39 +00003494 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003495}
3496
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003497/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003498static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003499 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003500 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003501 Mask = Op.getOperand(1);
3502 Op = Op.getOperand(0);
3503 } else {
3504 return false;
3505 }
3506 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003507
Chris Lattner97614c82006-09-14 20:50:57 +00003508 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3509 Shift = Op;
3510 return true;
3511 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003512
Scott Michelcf0da6c2009-02-17 22:15:04 +00003513 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003514}
3515
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003516// Return true if we can prove that, whenever Neg and Pos are both in the
3517// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003518// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3519//
3520// (or (shift1 X, Neg), (shift2 X, Pos))
3521//
Adam Nemetc6553a82014-03-07 23:56:24 +00003522// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3523// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3524// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003525static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003526 // If OpSize is a power of 2 then:
3527 //
3528 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3529 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3530 //
3531 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3532 // for the stronger condition:
3533 //
3534 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3535 //
3536 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3537 // we can just replace Neg with Neg' for the rest of the function.
3538 //
3539 // In other cases we check for the even stronger condition:
3540 //
3541 // Neg == OpSize - Pos [B]
3542 //
3543 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3544 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003545 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003546 // We could actually use [A] whenever OpSize is a power of 2, but the
3547 // only extra cases that it would match are those uninteresting ones
3548 // where Neg and Pos are never in range at the same time. E.g. for
3549 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3550 // as well as (sub 32, Pos), but:
3551 //
3552 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3553 //
3554 // always invokes undefined behavior for 32-bit X.
3555 //
3556 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003557 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003558 if (Neg.getOpcode() == ISD::AND &&
3559 isPowerOf2_64(OpSize) &&
3560 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3561 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3562 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003563 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003564 }
3565
Richard Sandiford0f264db2014-01-09 10:49:40 +00003566 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3567 if (Neg.getOpcode() != ISD::SUB)
3568 return 0;
3569 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3570 if (!NegC)
3571 return 0;
3572 SDValue NegOp1 = Neg.getOperand(1);
3573
Adam Nemet5117f5d2014-03-07 23:56:28 +00003574 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3575 // Pos'. The truncation is redundant for the purpose of the equality.
3576 if (MaskLoBits &&
3577 Pos.getOpcode() == ISD::AND &&
3578 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3579 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3580 Pos = Pos.getOperand(0);
3581
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003582 // The condition we need is now:
3583 //
3584 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3585 //
3586 // If NegOp1 == Pos then we need:
3587 //
3588 // OpSize & Mask == NegC & Mask
3589 //
3590 // (because "x & Mask" is a truncation and distributes through subtraction).
3591 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003592 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003593 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003594 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3595 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003596 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003597 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3598 //
3599 // which, again because "x & Mask" is a truncation, becomes:
3600 //
3601 // NegC & Mask == (OpSize - PosC) & Mask
3602 // OpSize & Mask == (NegC + PosC) & Mask
3603 else if (Pos.getOpcode() == ISD::ADD &&
3604 Pos.getOperand(0) == NegOp1 &&
3605 Pos.getOperand(1).getOpcode() == ISD::Constant)
3606 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3607 NegC->getAPIntValue());
3608 else
3609 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003610
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003611 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003612 if (MaskLoBits)
3613 // Opsize & Mask is 0 since Mask is Opsize - 1.
3614 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003615 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003616}
3617
Richard Sandiford95c864d2014-01-08 15:40:47 +00003618// A subroutine of MatchRotate used once we have found an OR of two opposite
3619// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3620// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3621// former being preferred if supported. InnerPos and InnerNeg are Pos and
3622// Neg with outer conversions stripped away.
3623SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3624 SDValue Neg, SDValue InnerPos,
3625 SDValue InnerNeg, unsigned PosOpcode,
3626 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003627 // fold (or (shl x, (*ext y)),
3628 // (srl x, (*ext (sub 32, y)))) ->
3629 // (rotl x, y) or (rotr x, (sub 32, y))
3630 //
3631 // fold (or (shl x, (*ext (sub 32, y))),
3632 // (srl x, (*ext y))) ->
3633 // (rotr x, y) or (rotl x, (sub 32, y))
3634 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003635 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003636 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3637 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3638 HasPos ? Pos : Neg).getNode();
3639 }
3640
Craig Topperc0196b12014-04-14 00:51:57 +00003641 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003642}
3643
Chris Lattner97614c82006-09-14 20:50:57 +00003644// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3645// idioms for rotate, and if the target supports rotation instructions, generate
3646// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003647SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003648 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003649 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003650 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003651
3652 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003653 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3654 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003655 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003656
Chris Lattner97614c82006-09-14 20:50:57 +00003657 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003658 SDValue LHSShift; // The shift.
3659 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003660 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003661 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003662
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003663 SDValue RHSShift; // The shift.
3664 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003665 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003666 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003667
Chris Lattner97614c82006-09-14 20:50:57 +00003668 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003669 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003670
3671 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003672 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003673
Chris Lattner97614c82006-09-14 20:50:57 +00003674 // Canonicalize shl to left side in a shl/srl pair.
3675 if (RHSShift.getOpcode() == ISD::SHL) {
3676 std::swap(LHS, RHS);
3677 std::swap(LHSShift, RHSShift);
3678 std::swap(LHSMask , RHSMask );
3679 }
3680
Duncan Sands13237ac2008-06-06 12:08:01 +00003681 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003682 SDValue LHSShiftArg = LHSShift.getOperand(0);
3683 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003684 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003685 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003686
3687 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3688 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003689 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3690 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003691 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3692 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003693 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003694 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003695
Craig Topper65161fa2012-09-29 06:54:22 +00003696 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3697 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003698
Chris Lattner97614c82006-09-14 20:50:57 +00003699 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003700 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003701 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003702
Gabor Greiff304a7a2008-08-28 21:40:38 +00003703 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003704 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3705 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003706 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003707 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003708 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3709 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003710 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003711
Bill Wendling35972a92009-01-30 21:14:50 +00003712 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003713 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003714
Gabor Greiff304a7a2008-08-28 21:40:38 +00003715 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003716 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003717
Chris Lattner97614c82006-09-14 20:50:57 +00003718 // If there is a mask here, and we have a variable shift, we can't be sure
3719 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003720 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003721 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003722
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003723 // If the shift amount is sign/zext/any-extended just peel it off.
3724 SDValue LExtOp0 = LHSShiftAmt;
3725 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003726 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3727 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3728 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3729 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3730 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3731 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3732 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3733 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003734 LExtOp0 = LHSShiftAmt.getOperand(0);
3735 RExtOp0 = RHSShiftAmt.getOperand(0);
3736 }
3737
Richard Sandiford95c864d2014-01-08 15:40:47 +00003738 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3739 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3740 if (TryL)
3741 return TryL;
3742
3743 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3744 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3745 if (TryR)
3746 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003747
Craig Topperc0196b12014-04-14 00:51:57 +00003748 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003749}
3750
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003751SDValue DAGCombiner::visitXOR(SDNode *N) {
3752 SDValue N0 = N->getOperand(0);
3753 SDValue N1 = N->getOperand(1);
3754 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003755 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3756 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003757 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003758
Dan Gohmana8665142007-06-25 16:23:39 +00003759 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003760 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003761 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003762 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003763
3764 // fold (xor x, 0) -> x, vector edition
3765 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3766 return N1;
3767 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3768 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003769 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003770
Evan Chengdf1690d2008-03-25 20:08:07 +00003771 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3772 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3773 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003774 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003775 if (N0.getOpcode() == ISD::UNDEF)
3776 return N0;
3777 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003778 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003779 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003780 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003781 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003782 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003783 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003784 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003785 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003786 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003787 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003788 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003789 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003790 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003791 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003792
Nate Begeman21158fc2005-09-01 00:19:25 +00003793 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003794 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003795 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003796 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3797 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003798
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003799 if (!LegalOperations ||
3800 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003801 switch (N0.getOpcode()) {
3802 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003803 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003804 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003805 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003806 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003807 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003808 N0.getOperand(3), NotCC);
3809 }
3810 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003811 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003812
Chris Lattner58c227b2007-09-10 21:39:07 +00003813 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003814 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003815 N0.getNode()->hasOneUse() &&
3816 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003817 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003818 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003819 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003820 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003821 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003822 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003823
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003824 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003825 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003826 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003827 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003828 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3829 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003830 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3831 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003832 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003833 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003834 }
3835 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003836 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003837 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003838 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003839 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003840 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3841 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003842 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3843 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003844 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003845 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003846 }
3847 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003848 // fold (xor (and x, y), y) -> (and (not x), y)
3849 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003850 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003851 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003852 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003853 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003854 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003855 }
Bill Wendling35972a92009-01-30 21:14:50 +00003856 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003857 if (N1C && N0.getOpcode() == ISD::XOR) {
3858 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3859 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3860 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003861 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003862 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003863 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003864 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003865 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003866 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003867 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003868 }
3869 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003870 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003871 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003872
Chris Lattner8d6fc202006-05-05 05:51:50 +00003873 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3874 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003875 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003876 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003877 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003878
Chris Lattner098c01e2006-04-08 04:15:24 +00003879 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003880 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003881 SimplifyDemandedBits(SDValue(N, 0)))
3882 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003883
Evan Chengf1005572010-04-28 07:10:39 +00003884 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003885}
3886
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003887/// Handle transforms common to the three shifts, when the shift amount is a
3888/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003889SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003890 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003891 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003892 return SDValue();
3893
Gabor Greiff304a7a2008-08-28 21:40:38 +00003894 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003895 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003896
Chris Lattner7c709a52007-12-06 07:33:36 +00003897 // We want to pull some binops through shifts, so that we have (and (shift))
3898 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3899 // thing happens with address calculations, so it's important to canonicalize
3900 // it.
3901 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003902
Chris Lattner7c709a52007-12-06 07:33:36 +00003903 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003904 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003905 case ISD::OR:
3906 case ISD::XOR:
3907 HighBitSet = false; // We can only transform sra if the high bit is clear.
3908 break;
3909 case ISD::AND:
3910 HighBitSet = true; // We can only transform sra if the high bit is set.
3911 break;
3912 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003913 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003914 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003915 HighBitSet = false; // We can only transform sra if the high bit is clear.
3916 break;
3917 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003918
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003919 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003920 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003921 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003922
3923 // FIXME: disable this unless the input to the binop is a shift by a constant.
3924 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003925 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003926 // void foo(int *X, int i) { X[i & 1235] = 1; }
3927 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003928 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003929 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003930 BinOpLHSVal->getOpcode() != ISD::SRA &&
3931 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3932 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003933 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003934
Owen Anderson53aa7a92009-08-10 22:56:29 +00003935 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003936
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003937 // If this is a signed shift right, and the high bit is modified by the
3938 // logical operation, do not perform the transformation. The highBitSet
3939 // boolean indicates the value of the high bit of the constant which would
3940 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003941 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003942 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3943 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003944 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003945 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003946
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003947 if (!TLI.isDesirableToCommuteWithShift(LHS))
3948 return SDValue();
3949
Chris Lattner7c709a52007-12-06 07:33:36 +00003950 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003951 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003952 N->getValueType(0),
3953 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003954 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003955
3956 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003957 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003958 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003959 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003960
3961 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003962 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003963}
3964
Adam Nemet67483892014-03-04 23:28:31 +00003965SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3966 assert(N->getOpcode() == ISD::TRUNCATE);
3967 assert(N->getOperand(0).getOpcode() == ISD::AND);
3968
3969 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3970 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3971 SDValue N01 = N->getOperand(0).getOperand(1);
3972
Matt Arsenault985b9de2014-03-17 18:58:01 +00003973 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003974 EVT TruncVT = N->getValueType(0);
3975 SDValue N00 = N->getOperand(0).getOperand(0);
3976 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003977 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003978
3979 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3980 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3981 DAG.getConstant(TruncC, TruncVT));
3982 }
3983 }
3984
3985 return SDValue();
3986}
Adam Nemet7f928f12014-03-07 23:56:30 +00003987
3988SDValue DAGCombiner::visitRotate(SDNode *N) {
3989 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3990 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3991 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3992 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3993 if (NewOp1.getNode())
3994 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3995 N->getOperand(0), NewOp1);
3996 }
3997 return SDValue();
3998}
3999
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004000SDValue DAGCombiner::visitSHL(SDNode *N) {
4001 SDValue N0 = N->getOperand(0);
4002 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004003 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4004 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004005 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004006 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004007
Daniel Sandersa1840d22013-11-11 17:23:41 +00004008 // fold vector ops
4009 if (VT.isVector()) {
4010 SDValue FoldedVOp = SimplifyVBinOp(N);
4011 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004012
4013 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4014 // If setcc produces all-one true value then:
4015 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004016 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004017 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004018 SDValue N00 = N0->getOperand(0);
4019 SDValue N01 = N0->getOperand(1);
4020 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004021
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004022 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4023 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4024 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004025 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4026 if (C.getNode())
4027 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4028 }
4029 } else {
4030 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004031 }
4032 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004033 }
4034
Nate Begeman21158fc2005-09-01 00:19:25 +00004035 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004036 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004037 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004038 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004039 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004040 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004041 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004042 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004043 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004044 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004045 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004046 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004047 // fold (shl undef, x) -> 0
4048 if (N0.getOpcode() == ISD::UNDEF)
4049 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004050 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004051 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004052 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004053 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004054 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004055 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004056 N1.getOperand(0).getOpcode() == ISD::AND) {
4057 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4058 if (NewOp1.getNode())
4059 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004060 }
4061
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004062 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4063 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004064
4065 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004066 if (N1C && N0.getOpcode() == ISD::SHL) {
4067 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4068 uint64_t c1 = N0C1->getZExtValue();
4069 uint64_t c2 = N1C->getZExtValue();
4070 if (c1 + c2 >= OpSizeInBits)
4071 return DAG.getConstant(0, VT);
4072 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4073 DAG.getConstant(c1 + c2, N1.getValueType()));
4074 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004075 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004076
4077 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4078 // For this to be valid, the second form must not preserve any of the bits
4079 // that are shifted out by the inner shift in the first form. This means
4080 // the outer shift size must be >= the number of bits added by the ext.
4081 // As a corollary, we don't care what kind of ext it is.
4082 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4083 N0.getOpcode() == ISD::ANY_EXTEND ||
4084 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004085 N0.getOperand(0).getOpcode() == ISD::SHL) {
4086 SDValue N0Op0 = N0.getOperand(0);
4087 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4088 uint64_t c1 = N0Op0C1->getZExtValue();
4089 uint64_t c2 = N1C->getZExtValue();
4090 EVT InnerShiftVT = N0Op0.getValueType();
4091 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4092 if (c2 >= OpSizeInBits - InnerShiftSize) {
4093 if (c1 + c2 >= OpSizeInBits)
4094 return DAG.getConstant(0, VT);
4095 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4096 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4097 N0Op0->getOperand(0)),
4098 DAG.getConstant(c1 + c2, N1.getValueType()));
4099 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004100 }
4101 }
4102
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004103 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4104 // Only fold this if the inner zext has no other uses to avoid increasing
4105 // the total number of instructions.
4106 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004107 N0.getOperand(0).getOpcode() == ISD::SRL) {
4108 SDValue N0Op0 = N0.getOperand(0);
4109 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4110 uint64_t c1 = N0Op0C1->getZExtValue();
4111 if (c1 < VT.getScalarSizeInBits()) {
4112 uint64_t c2 = N1C->getZExtValue();
4113 if (c1 == c2) {
4114 SDValue NewOp0 = N0.getOperand(0);
4115 EVT CountVT = NewOp0.getOperand(1).getValueType();
4116 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4117 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004118 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004119 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4120 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004121 }
4122 }
4123 }
4124
Eli Friedman1877ac92011-06-09 22:14:44 +00004125 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4126 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004127 // Only fold this if the inner shift has no other uses -- if it does, folding
4128 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004129 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4130 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4131 uint64_t c1 = N0C1->getZExtValue();
4132 if (c1 < OpSizeInBits) {
4133 uint64_t c2 = N1C->getZExtValue();
4134 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4135 SDValue Shift;
4136 if (c2 > c1) {
4137 Mask = Mask.shl(c2 - c1);
4138 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4139 DAG.getConstant(c2 - c1, N1.getValueType()));
4140 } else {
4141 Mask = Mask.lshr(c1 - c2);
4142 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4143 DAG.getConstant(c1 - c2, N1.getValueType()));
4144 }
4145 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4146 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004147 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004148 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004149 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004150 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004151 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004152 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004153 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004154 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4155 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004156 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004157 HiBitsMask);
4158 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004159
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004160 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4161 // Variant of version done on multiply, except mul by a power of 2 is turned
4162 // into a shift.
4163 APInt Val;
4164 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4165 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4166 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4167 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4168 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4169 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4170 }
4171
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004172 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004173 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004174 if (NewSHL.getNode())
4175 return NewSHL;
4176 }
4177
Evan Chengf1005572010-04-28 07:10:39 +00004178 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004179}
4180
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004181SDValue DAGCombiner::visitSRA(SDNode *N) {
4182 SDValue N0 = N->getOperand(0);
4183 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004184 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4185 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004186 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004187 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004188
Daniel Sandersa1840d22013-11-11 17:23:41 +00004189 // fold vector ops
4190 if (VT.isVector()) {
4191 SDValue FoldedVOp = SimplifyVBinOp(N);
4192 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004193
4194 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004195 }
4196
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004197 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004198 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004199 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004200 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004201 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004202 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004203 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004204 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004205 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004206 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004207 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004208 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004209 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004210 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004211 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004212 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4213 // sext_inreg.
4214 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004215 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004216 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4217 if (VT.isVector())
4218 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4219 ExtVT, VT.getVectorNumElements());
4220 if ((!LegalOperations ||
4221 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004222 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004223 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004224 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004225
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004226 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004227 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004228 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004229 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004230 if (Sum >= OpSizeInBits)
4231 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004232 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004233 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004234 }
4235 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004236
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004237 // fold (sra (shl X, m), (sub result_size, n))
4238 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004239 // result_size - n != m.
4240 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004241 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004242 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004243 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004244 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4245 if (N01C) {
4246 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004247 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004248 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4249
4250 if (VT.isVector())
4251 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4252
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004253 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004254 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004255
Scott Michelcf0da6c2009-02-17 22:15:04 +00004256 // If the shift is not a no-op (in which case this should be just a sign
4257 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004258 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004259 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004260 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004261 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4262 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004263 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004264
Owen Andersonb2c80da2011-02-25 21:41:48 +00004265 SDValue Amt = DAG.getConstant(ShiftAmt,
4266 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004267 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004268 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004269 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004270 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004271 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004272 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004273 }
4274 }
4275 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004276
Duncan Sands3ed76882009-02-01 18:06:53 +00004277 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004278 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004279 N1.getOperand(0).getOpcode() == ISD::AND) {
4280 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4281 if (NewOp1.getNode())
4282 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004283 }
4284
Matt Arsenault985b9de2014-03-17 18:58:01 +00004285 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004286 // if c1 is equal to the number of bits the trunc removes
4287 if (N0.getOpcode() == ISD::TRUNCATE &&
4288 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4289 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4290 N0.getOperand(0).hasOneUse() &&
4291 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004292 N1C) {
4293 SDValue N0Op0 = N0.getOperand(0);
4294 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4295 unsigned LargeShiftVal = LargeShift->getZExtValue();
4296 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004297
Matt Arsenault985b9de2014-03-17 18:58:01 +00004298 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4299 SDValue Amt =
4300 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4301 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4302 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4303 N0Op0.getOperand(0), Amt);
4304 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4305 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004306 }
4307 }
4308
Scott Michelcf0da6c2009-02-17 22:15:04 +00004309 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004310 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4311 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004312
4313
Nate Begeman21158fc2005-09-01 00:19:25 +00004314 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004315 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004316 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004317
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004318 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004319 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004320 if (NewSRA.getNode())
4321 return NewSRA;
4322 }
4323
Evan Chengf1005572010-04-28 07:10:39 +00004324 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004325}
4326
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004327SDValue DAGCombiner::visitSRL(SDNode *N) {
4328 SDValue N0 = N->getOperand(0);
4329 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004330 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4331 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004332 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004333 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004334
Daniel Sandersa1840d22013-11-11 17:23:41 +00004335 // fold vector ops
4336 if (VT.isVector()) {
4337 SDValue FoldedVOp = SimplifyVBinOp(N);
4338 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004339
4340 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004341 }
4342
Nate Begeman21158fc2005-09-01 00:19:25 +00004343 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004344 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004345 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004346 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004347 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004348 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004349 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004350 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004351 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004352 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004353 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004354 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004355 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004356 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004357 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004358 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004359
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004360 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004361 if (N1C && N0.getOpcode() == ISD::SRL) {
4362 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4363 uint64_t c1 = N01C->getZExtValue();
4364 uint64_t c2 = N1C->getZExtValue();
4365 if (c1 + c2 >= OpSizeInBits)
4366 return DAG.getConstant(0, VT);
4367 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4368 DAG.getConstant(c1 + c2, N1.getValueType()));
4369 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004370 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004371
Dale Johannesencd538af2010-12-17 21:45:49 +00004372 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004373 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4374 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004375 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004376 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004377 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4378 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004379 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4380 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004381 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004382 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004383 if (c1 + OpSizeInBits == InnerShiftSize) {
4384 if (c1 + c2 >= InnerShiftSize)
4385 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004386 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4387 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004388 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004389 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004390 }
4391 }
4392
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004393 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004394 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4395 unsigned BitSize = N0.getScalarValueSizeInBits();
4396 if (BitSize <= 64) {
4397 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4398 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4399 DAG.getConstant(~0ULL >> ShAmt, VT));
4400 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004401 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004402
Michael Liao62ebfd82013-06-21 18:45:27 +00004403 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004404 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4405 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004406 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004407 unsigned BitSize = SmallVT.getScalarSizeInBits();
4408 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004409 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004410
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004411 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004412 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004413 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004414 N0.getOperand(0),
4415 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004416 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004417 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004418 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4419 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4420 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004421 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004422 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004423
Chris Lattner2e33fb42006-10-12 20:23:19 +00004424 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4425 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004426 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004427 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004428 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004429 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004430
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004431 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004432 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004433 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004434 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004435 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004436
Chris Lattner49932492006-04-02 06:11:11 +00004437 // If any of the input bits are KnownOne, then the input couldn't be all
4438 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004439 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004440
Chris Lattner49932492006-04-02 06:11:11 +00004441 // If all of the bits input the to ctlz node are known to be zero, then
4442 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004443 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004444 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004445
Chris Lattner49932492006-04-02 06:11:11 +00004446 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004447 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004448 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004449 // could be set on input to the CTLZ node. If this bit is set, the SRL
4450 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4451 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004452 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004453 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004454
Chris Lattner49932492006-04-02 06:11:11 +00004455 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004456 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004457 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004458 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004459 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004460
Andrew Trickef9de2a2013-05-25 02:42:55 +00004461 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004462 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004463 }
4464 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004465
Duncan Sands3ed76882009-02-01 18:06:53 +00004466 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004467 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004468 N1.getOperand(0).getOpcode() == ISD::AND) {
4469 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4470 if (NewOp1.getNode())
4471 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004473
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004474 // fold operands of srl based on knowledge that the low bits are not
4475 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004476 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4477 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004478
Evan Chengb175de62009-12-18 21:31:31 +00004479 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004480 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004481 if (NewSRL.getNode())
4482 return NewSRL;
4483 }
4484
Dan Gohman600f62b2010-06-24 14:30:44 +00004485 // Attempt to convert a srl of a load into a narrower zero-extending load.
4486 SDValue NarrowLoad = ReduceLoadWidth(N);
4487 if (NarrowLoad.getNode())
4488 return NarrowLoad;
4489
Evan Chengb175de62009-12-18 21:31:31 +00004490 // Here is a common situation. We want to optimize:
4491 //
4492 // %a = ...
4493 // %b = and i32 %a, 2
4494 // %c = srl i32 %b, 1
4495 // brcond i32 %c ...
4496 //
4497 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004498 //
Evan Chengb175de62009-12-18 21:31:31 +00004499 // %a = ...
4500 // %b = and %a, 2
4501 // %c = setcc eq %b, 0
4502 // brcond %c ...
4503 //
4504 // However when after the source operand of SRL is optimized into AND, the SRL
4505 // itself may not be optimized further. Look for it and add the BRCOND into
4506 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004507 if (N->hasOneUse()) {
4508 SDNode *Use = *N->use_begin();
4509 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004510 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004511 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4512 // Also look pass the truncate.
4513 Use = *Use->use_begin();
4514 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004515 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004516 }
4517 }
Evan Chengb175de62009-12-18 21:31:31 +00004518
Evan Chengf1005572010-04-28 07:10:39 +00004519 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004520}
4521
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004522SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4523 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004524 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004525
4526 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004527 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004528 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004529 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004530}
4531
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004532SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4533 SDValue N0 = N->getOperand(0);
4534 EVT VT = N->getValueType(0);
4535
4536 // fold (ctlz_zero_undef c1) -> c2
4537 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004538 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004539 return SDValue();
4540}
4541
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004542SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4543 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004544 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004545
Nate Begeman21158fc2005-09-01 00:19:25 +00004546 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004547 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004548 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004549 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004550}
4551
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004552SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4553 SDValue N0 = N->getOperand(0);
4554 EVT VT = N->getValueType(0);
4555
4556 // fold (cttz_zero_undef c1) -> c2
4557 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004558 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004559 return SDValue();
4560}
4561
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004562SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4563 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004564 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004565
Nate Begeman21158fc2005-09-01 00:19:25 +00004566 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004567 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004568 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004569 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004570}
4571
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004572SDValue DAGCombiner::visitSELECT(SDNode *N) {
4573 SDValue N0 = N->getOperand(0);
4574 SDValue N1 = N->getOperand(1);
4575 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004576 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4577 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4578 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004579 EVT VT = N->getValueType(0);
4580 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004581
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004582 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004583 if (N1 == N2)
4584 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004585 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004586 if (N0C && !N0C->isNullValue())
4587 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004588 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004589 if (N0C && N0C->isNullValue())
4590 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004591 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004592 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004593 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004594 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004595 // We can't do this reliably if integer based booleans have different contents
4596 // to floating point based booleans. This is because we can't tell whether we
4597 // have an integer-based boolean or a floating-point-based boolean unless we
4598 // can find the SETCC that produced it and inspect its operands. This is
4599 // fairly easy if C is the SETCC node, but it can potentially be
4600 // undiscoverable (or not reasonably discoverable). For example, it could be
4601 // in another basic block or it could require searching a complicated
4602 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004603 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004604 (VT0 == MVT::i1 || (VT0.isInteger() &&
4605 TLI.getBooleanContents(false, false) ==
4606 TLI.getBooleanContents(false, true) &&
4607 TLI.getBooleanContents(false, false) ==
4608 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004609 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004610 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004611 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004612 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004613 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004614 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004615 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004616 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004617 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004618 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4619 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004620 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004621 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004622 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004623 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004624 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004625 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004626 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004627 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004628 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004629 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004630 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004631 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004632 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004633 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004634 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004635 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004636 // fold (select X, X, Y) -> (or X, Y)
4637 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004638 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004639 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004640 // fold (select X, Y, X) -> (and X, Y)
4641 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004642 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004643 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004644
Chris Lattner6c14c352005-10-18 06:04:22 +00004645 // If we can fold this based on the true/false value, do so.
4646 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004647 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004648
Nate Begemanc760f802005-09-19 22:34:01 +00004649 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004650 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004651 if ((!LegalOperations &&
4652 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4653 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004654 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004655 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004656 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004657 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004658 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004659
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004660 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004661}
4662
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004663static
4664std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4665 SDLoc DL(N);
4666 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004667 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004668
4669 // Split the inputs.
4670 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004671 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4672 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004673
4674 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4675 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4676
4677 return std::make_pair(Lo, Hi);
4678}
4679
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004680// This function assumes all the vselect's arguments are CONCAT_VECTOR
4681// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4682static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4683 SDLoc dl(N);
4684 SDValue Cond = N->getOperand(0);
4685 SDValue LHS = N->getOperand(1);
4686 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004687 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004688 int NumElems = VT.getVectorNumElements();
4689 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4690 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691 Cond.getOpcode() == ISD::BUILD_VECTOR);
4692
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004693 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4694 // binary ones here.
4695 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4696 return SDValue();
4697
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004698 // We're sure we have an even number of elements due to the
4699 // concat_vectors we have as arguments to vselect.
4700 // Skip BV elements until we find one that's not an UNDEF
4701 // After we find an UNDEF element, keep looping until we get to half the
4702 // length of the BV and see if all the non-undef nodes are the same.
4703 ConstantSDNode *BottomHalf = nullptr;
4704 for (int i = 0; i < NumElems / 2; ++i) {
4705 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4706 continue;
4707
4708 if (BottomHalf == nullptr)
4709 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4710 else if (Cond->getOperand(i).getNode() != BottomHalf)
4711 return SDValue();
4712 }
4713
4714 // Do the same for the second half of the BuildVector
4715 ConstantSDNode *TopHalf = nullptr;
4716 for (int i = NumElems / 2; i < NumElems; ++i) {
4717 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4718 continue;
4719
4720 if (TopHalf == nullptr)
4721 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4722 else if (Cond->getOperand(i).getNode() != TopHalf)
4723 return SDValue();
4724 }
4725
4726 assert(TopHalf && BottomHalf &&
4727 "One half of the selector was all UNDEFs and the other was all the "
4728 "same value. This should have been addressed before this function.");
4729 return DAG.getNode(
4730 ISD::CONCAT_VECTORS, dl, VT,
4731 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4732 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4733}
4734
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004735SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4736 SDValue N0 = N->getOperand(0);
4737 SDValue N1 = N->getOperand(1);
4738 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004739 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004740
4741 // Canonicalize integer abs.
4742 // vselect (setg[te] X, 0), X, -X ->
4743 // vselect (setgt X, -1), X, -X ->
4744 // vselect (setl[te] X, 0), -X, X ->
4745 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4746 if (N0.getOpcode() == ISD::SETCC) {
4747 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4748 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4749 bool isAbs = false;
4750 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4751
4752 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4753 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4754 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4755 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4756 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4757 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4758 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4759
4760 if (isAbs) {
4761 EVT VT = LHS.getValueType();
4762 SDValue Shift = DAG.getNode(
4763 ISD::SRA, DL, VT, LHS,
4764 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4765 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004766 AddToWorklist(Shift.getNode());
4767 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004768 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4769 }
4770 }
4771
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004772 // If the VSELECT result requires splitting and the mask is provided by a
4773 // SETCC, then split both nodes and its operands before legalization. This
4774 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4775 // and enables future optimizations (e.g. min/max pattern matching on X86).
4776 if (N0.getOpcode() == ISD::SETCC) {
4777 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004778
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004779 // Check if any splitting is required.
4780 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4781 TargetLowering::TypeSplitVector)
4782 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004783
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004784 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004785 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4786 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4787 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004788
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004789 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4790 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004791
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004792 // Add the new VSELECT nodes to the work list in case they need to be split
4793 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004794 AddToWorklist(Lo.getNode());
4795 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004796
4797 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004798 }
4799
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004800 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4801 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4802 return N1;
4803 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4804 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4805 return N2;
4806
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004807 // The ConvertSelectToConcatVector function is assuming both the above
4808 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4809 // and addressed.
4810 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4811 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4812 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4813 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4814 if (CV.getNode())
4815 return CV;
4816 }
4817
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004818 return SDValue();
4819}
4820
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004821SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4822 SDValue N0 = N->getOperand(0);
4823 SDValue N1 = N->getOperand(1);
4824 SDValue N2 = N->getOperand(2);
4825 SDValue N3 = N->getOperand(3);
4826 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004827 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004828
Nate Begemanc760f802005-09-19 22:34:01 +00004829 // fold select_cc lhs, rhs, x, x, cc -> x
4830 if (N2 == N3)
4831 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004832
Chris Lattner8b68dec2006-09-20 06:19:26 +00004833 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004834 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004835 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004836 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004837 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004838
Stephen Lin605207f2013-06-15 04:03:33 +00004839 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4840 if (!SCCC->isNullValue())
4841 return N2; // cond always true -> true val
4842 else
4843 return N3; // cond always false -> false val
4844 }
4845
4846 // Fold to a simpler select_cc
4847 if (SCC.getOpcode() == ISD::SETCC)
4848 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4849 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4850 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004851 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004852
Chris Lattner6c14c352005-10-18 06:04:22 +00004853 // If we can fold this based on the true/false value, do so.
4854 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004855 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004856
Nate Begemanc760f802005-09-19 22:34:01 +00004857 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004858 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004859}
4860
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004861SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004862 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004863 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004864 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004865}
4866
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004867// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4868// dag node into a ConstantSDNode or a build_vector of constants.
4869// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004870// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004871// Vector extends are not folded if operations are legal; this is to
4872// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004873static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4874 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004875 bool LegalOperations) {
4876 unsigned Opcode = N->getOpcode();
4877 SDValue N0 = N->getOperand(0);
4878 EVT VT = N->getValueType(0);
4879
4880 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4881 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4882
4883 // fold (sext c1) -> c1
4884 // fold (zext c1) -> c1
4885 // fold (aext c1) -> c1
4886 if (isa<ConstantSDNode>(N0))
4887 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4888
4889 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4890 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4891 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004892 EVT SVT = VT.getScalarType();
4893 if (!(VT.isVector() &&
4894 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004895 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004896 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004897
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004898 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004899 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004900 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4901 unsigned ShAmt = VTBits - EVTBits;
4902 SmallVector<SDValue, 8> Elts;
4903 unsigned NumElts = N0->getNumOperands();
4904 SDLoc DL(N);
4905
4906 for (unsigned i=0; i != NumElts; ++i) {
4907 SDValue Op = N0->getOperand(i);
4908 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004909 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004910 continue;
4911 }
4912
4913 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4914 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4915 if (Opcode == ISD::SIGN_EXTEND)
4916 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004917 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004918 else
4919 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004920 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004921 }
4922
Craig Topper48d114b2014-04-26 18:35:24 +00004923 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004924}
4925
Evan Chenge106e2f2007-10-29 19:58:20 +00004926// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004927// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004928// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004929// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004930static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004931 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004932 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004933 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004934 bool HasCopyToRegUses = false;
4935 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004936 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4937 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004938 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004939 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004940 if (User == N)
4941 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004942 if (UI.getUse().getResNo() != N0.getResNo())
4943 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004944 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004945 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004946 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4947 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4948 // Sign bits will be lost after a zext.
4949 return false;
4950 bool Add = false;
4951 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004952 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004953 if (UseOp == N0)
4954 continue;
4955 if (!isa<ConstantSDNode>(UseOp))
4956 return false;
4957 Add = true;
4958 }
4959 if (Add)
4960 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004961 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004962 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004963 // If truncates aren't free and there are users we can't
4964 // extend, it isn't worthwhile.
4965 if (!isTruncFree)
4966 return false;
4967 // Remember if this value is live-out.
4968 if (User->getOpcode() == ISD::CopyToReg)
4969 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004970 }
4971
4972 if (HasCopyToRegUses) {
4973 bool BothLiveOut = false;
4974 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4975 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004976 SDUse &Use = UI.getUse();
4977 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4978 BothLiveOut = true;
4979 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004980 }
4981 }
4982 if (BothLiveOut)
4983 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004984 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004985 return ExtendNodes.size();
4986 }
4987 return true;
4988}
4989
Craig Toppere0b71182013-07-13 07:43:40 +00004990void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004991 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004992 ISD::NodeType ExtType) {
4993 // Extend SetCC uses if necessary.
4994 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4995 SDNode *SetCC = SetCCs[i];
4996 SmallVector<SDValue, 4> Ops;
4997
4998 for (unsigned j = 0; j != 2; ++j) {
4999 SDValue SOp = SetCC->getOperand(j);
5000 if (SOp == Trunc)
5001 Ops.push_back(ExtLoad);
5002 else
5003 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5004 }
5005
5006 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005007 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005008 }
5009}
5010
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005011SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5012 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005013 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005014
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005015 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5016 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005017 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005018
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005019 // fold (sext (sext x)) -> (sext x)
5020 // fold (sext (aext x)) -> (sext x)
5021 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005022 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005023 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005024
Chris Lattnerfce448f2007-02-26 03:13:59 +00005025 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005026 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5027 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005028 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5029 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005030 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5031 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005032 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005033 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005034 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005035 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005036 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005037 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005038
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005039 // See if the value being truncated is already sign extended. If so, just
5040 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005041 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005042 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5043 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5044 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005045 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005046
Chris Lattnerfce448f2007-02-26 03:13:59 +00005047 if (OpBits == DestBits) {
5048 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5049 // bits, it is already ready.
5050 if (NumSignBits > DestBits-MidBits)
5051 return Op;
5052 } else if (OpBits < DestBits) {
5053 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5054 // bits, just sext from i32.
5055 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005056 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005057 } else {
5058 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5059 // bits, just truncate to i32.
5060 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005061 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005062 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005063
Chris Lattnerfce448f2007-02-26 03:13:59 +00005064 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005065 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5066 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005067 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005068 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005069 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005070 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5071 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005072 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005073 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005074 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005075
Evan Chengbce7c472005-12-14 02:19:23 +00005076 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005077 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005078 // on vectors in one instruction. We only perform this transformation on
5079 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005080 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005081 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005082 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005083 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005084 bool DoXform = true;
5085 SmallVector<SDNode*, 4> SetCCs;
5086 if (!N0.hasOneUse())
5087 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5088 if (DoXform) {
5089 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005090 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005091 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005092 LN0->getBasePtr(), N0.getValueType(),
5093 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005094 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005095 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005096 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005097 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005098 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005099 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005100 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005101 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005102 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005103
5104 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5105 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005106 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5107 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005108 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005109 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005110 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005111 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005112 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005113 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005114 LN0->getBasePtr(), MemVT,
5115 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005116 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005117 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005118 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005119 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005120 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005121 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005122 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005123 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005124
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005125 // fold (sext (and/or/xor (load x), cst)) ->
5126 // (and/or/xor (sextload x), (sext cst))
5127 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5128 N0.getOpcode() == ISD::XOR) &&
5129 isa<LoadSDNode>(N0.getOperand(0)) &&
5130 N0.getOperand(1).getOpcode() == ISD::Constant &&
5131 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5132 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5133 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005134 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005135 bool DoXform = true;
5136 SmallVector<SDNode*, 4> SetCCs;
5137 if (!N0.hasOneUse())
5138 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5139 SetCCs, TLI);
5140 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005141 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005142 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005143 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005144 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005145 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5146 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005147 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005148 ExtLoad, DAG.getConstant(Mask, VT));
5149 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005150 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005151 N0.getOperand(0).getValueType(), ExtLoad);
5152 CombineTo(N, And);
5153 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005154 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005155 ISD::SIGN_EXTEND);
5156 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5157 }
5158 }
5159 }
5160
Chris Lattner65786b02007-04-11 05:32:27 +00005161 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005162 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005163 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005164 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005165 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005166 TLI.getBooleanContents(N0VT) ==
5167 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005168 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5169 // of the same size as the compared operands. Only optimize sext(setcc())
5170 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005171 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005172
5173 // We know that the # elements of the results is the same as the
5174 // # elements of the compare (and the # elements of the compare result
5175 // for that matter). Check to see that they are the same size. If so,
5176 // we know that the element size of the sext'd result matches the
5177 // element size of the compare operands.
5178 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005179 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005180 N0.getOperand(1),
5181 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005182
Dan Gohmane82c25e2010-04-30 17:19:19 +00005183 // If the desired elements are smaller or larger than the source
5184 // elements we can use a matching integer vector type and then
5185 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005186 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005187 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005188 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005189 N0.getOperand(0), N0.getOperand(1),
5190 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005191 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005192 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005193 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005194
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005195 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005196 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005197 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005198 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005199 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005200 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005201 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005202 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005203 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005204
5205 if (!VT.isVector()) {
5206 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5207 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5208 SDLoc DL(N);
5209 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5210 SDValue SetCC = DAG.getSetCC(DL,
5211 SetCCVT,
5212 N0.getOperand(0), N0.getOperand(1), CC);
5213 EVT SelectVT = getSetCCResultType(VT);
5214 return DAG.getSelect(DL, VT,
5215 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5216 NegOne, DAG.getConstant(0, VT));
5217
5218 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005219 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005220 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005221
Dan Gohman3eb10f72008-04-28 16:58:24 +00005222 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005223 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005224 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005225 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005226
Evan Chengf1005572010-04-28 07:10:39 +00005227 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005228}
5229
Rafael Espindola8f62b322012-04-09 16:06:03 +00005230// isTruncateOf - If N is a truncate of some other value, return true, record
5231// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5232// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005233// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005234static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5235 APInt &KnownZero) {
5236 APInt KnownOne;
5237 if (N->getOpcode() == ISD::TRUNCATE) {
5238 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005239 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005240 return true;
5241 }
5242
5243 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5244 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5245 return false;
5246
5247 SDValue Op0 = N->getOperand(0);
5248 SDValue Op1 = N->getOperand(1);
5249 assert(Op0.getValueType() == Op1.getValueType());
5250
5251 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5252 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005253 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005254 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005255 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005256 Op = Op0;
5257 else
5258 return false;
5259
Jay Foada0653a32014-05-14 21:14:37 +00005260 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005261
5262 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5263 return false;
5264
5265 return true;
5266}
5267
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005268SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5269 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005270 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005271
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005272 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5273 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005274 return SDValue(Res, 0);
5275
Nate Begeman21158fc2005-09-01 00:19:25 +00005276 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005277 // fold (zext (aext x)) -> (zext x)
5278 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005279 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005280 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005281
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005282 // fold (zext (truncate x)) -> (zext x) or
5283 // (zext (truncate x)) -> (truncate x)
5284 // This is valid when the truncated bits of x are already zero.
5285 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005286 SDValue Op;
5287 APInt KnownZero;
5288 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5289 APInt TruncatedBits =
5290 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5291 APInt(Op.getValueSizeInBits(), 0) :
5292 APInt::getBitsSet(Op.getValueSizeInBits(),
5293 N0.getValueSizeInBits(),
5294 std::min(Op.getValueSizeInBits(),
5295 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005296 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005297 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005298 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005299 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005300 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005301
5302 return Op;
5303 }
5304 }
5305
Evan Cheng464dc9b2007-03-22 01:54:19 +00005306 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5307 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005308 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005309 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5310 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005311 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5312 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005313 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005314 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005315 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005316 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005317 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005318 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005319 }
5320
Chris Lattnera31f0a62006-09-21 06:00:20 +00005321 // fold (zext (truncate x)) -> (and x, mask)
5322 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005323 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005324
5325 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5326 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5327 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5328 if (NarrowLoad.getNode()) {
5329 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5330 if (NarrowLoad.getNode() != N0.getNode()) {
5331 CombineTo(N0.getNode(), NarrowLoad);
5332 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005333 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005334 }
5335 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5336 }
5337
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005338 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005339 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005340 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005341 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005342 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005343 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005344 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005345 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005346 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005347 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005348 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005349
Dan Gohmanad3e5492009-04-08 00:15:30 +00005350 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5351 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005352 if (N0.getOpcode() == ISD::AND &&
5353 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005354 N0.getOperand(1).getOpcode() == ISD::Constant &&
5355 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5356 N0.getValueType()) ||
5357 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005358 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005359 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005360 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005361 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005362 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005363 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005364 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005365 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005366 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005367 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005368 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005369
Evan Chengbce7c472005-12-14 02:19:23 +00005370 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005371 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005372 // on vectors in one instruction. We only perform this transformation on
5373 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005374 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005375 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005376 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005377 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005378 bool DoXform = true;
5379 SmallVector<SDNode*, 4> SetCCs;
5380 if (!N0.hasOneUse())
5381 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5382 if (DoXform) {
5383 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005384 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005385 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005386 LN0->getBasePtr(), N0.getValueType(),
5387 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005388 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005389 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005390 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005391 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005392
Andrew Trickef9de2a2013-05-25 02:42:55 +00005393 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005394 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005395 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005396 }
Evan Chengbce7c472005-12-14 02:19:23 +00005397 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005398
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005399 // fold (zext (and/or/xor (load x), cst)) ->
5400 // (and/or/xor (zextload x), (zext cst))
5401 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5402 N0.getOpcode() == ISD::XOR) &&
5403 isa<LoadSDNode>(N0.getOperand(0)) &&
5404 N0.getOperand(1).getOpcode() == ISD::Constant &&
5405 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5406 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5407 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005408 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005409 bool DoXform = true;
5410 SmallVector<SDNode*, 4> SetCCs;
5411 if (!N0.hasOneUse())
5412 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5413 SetCCs, TLI);
5414 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005415 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005416 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005417 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005418 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005419 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5420 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005421 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005422 ExtLoad, DAG.getConstant(Mask, VT));
5423 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005424 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005425 N0.getOperand(0).getValueType(), ExtLoad);
5426 CombineTo(N, And);
5427 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005428 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005429 ISD::ZERO_EXTEND);
5430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5431 }
5432 }
5433 }
5434
Chris Lattner7dac1082005-12-14 19:05:06 +00005435 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5436 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005437 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5438 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005439 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005440 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005441 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005442 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005443 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005444 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005445 LN0->getBasePtr(), MemVT,
5446 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005447 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005448 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005449 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005450 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005451 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005452 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005453 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005454 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005455
Chris Lattner65786b02007-04-11 05:32:27 +00005456 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005457 if (!LegalOperations && VT.isVector() &&
5458 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005459 EVT N0VT = N0.getOperand(0).getValueType();
5460 if (getSetCCResultType(N0VT) == N0.getValueType())
5461 return SDValue();
5462
Evan Chengabd0ad52010-05-19 01:08:17 +00005463 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5464 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005465 EVT EltVT = VT.getVectorElementType();
5466 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5467 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005468 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005469 // We know that the # elements of the results is the same as the
5470 // # elements of the compare (and the # elements of the compare result
5471 // for that matter). Check to see that they are the same size. If so,
5472 // we know that the element size of the sext'd result matches the
5473 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005474 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5475 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005476 N0.getOperand(1),
5477 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005478 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005479 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005480
5481 // If the desired elements are smaller or larger than the source
5482 // elements we can use a matching integer vector type and then
5483 // truncate/sign extend
5484 EVT MatchingElementType =
5485 EVT::getIntegerVT(*DAG.getContext(),
5486 N0VT.getScalarType().getSizeInBits());
5487 EVT MatchingVectorType =
5488 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5489 N0VT.getVectorNumElements());
5490 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005491 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005492 N0.getOperand(1),
5493 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005494 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5495 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005496 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005497 }
5498
5499 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005500 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005501 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005502 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005503 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005504 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005505 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005506
Evan Cheng852c4862009-12-15 03:00:32 +00005507 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005508 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005509 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005510 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5511 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005512 SDValue ShAmt = N0.getOperand(1);
5513 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005514 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005515 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005516 // If the original shl may be shifting out bits, do not perform this
5517 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005518 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5519 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5520 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005521 return SDValue();
5522 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005523
Andrew Trickef9de2a2013-05-25 02:42:55 +00005524 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005525
5526 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005527 if (VT.getSizeInBits() >= 256)
5528 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005529
Chris Lattnere95d1952011-02-13 19:09:16 +00005530 return DAG.getNode(N0.getOpcode(), DL, VT,
5531 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5532 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005533 }
5534
Evan Chengf1005572010-04-28 07:10:39 +00005535 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005536}
5537
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005538SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5539 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005540 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005541
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005542 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5543 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005544 return SDValue(Res, 0);
5545
Chris Lattner812646a2006-05-05 05:58:59 +00005546 // fold (aext (aext x)) -> (aext x)
5547 // fold (aext (zext x)) -> (zext x)
5548 // fold (aext (sext x)) -> (sext x)
5549 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5550 N0.getOpcode() == ISD::ZERO_EXTEND ||
5551 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005552 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005553
Evan Cheng464dc9b2007-03-22 01:54:19 +00005554 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5555 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5556 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005557 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5558 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005559 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5560 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005561 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005562 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005563 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005564 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005565 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005566 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005567 }
5568
Chris Lattner8746e2c2006-09-20 06:29:17 +00005569 // fold (aext (truncate x))
5570 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005571 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005572 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005573 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005574 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005575 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5576 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005577 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005578
Dan Gohmanad3e5492009-04-08 00:15:30 +00005579 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5580 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005581 if (N0.getOpcode() == ISD::AND &&
5582 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005583 N0.getOperand(1).getOpcode() == ISD::Constant &&
5584 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5585 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005586 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005587 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005588 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005589 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005590 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005591 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005592 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005593 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005594 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005595 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005596 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005597
Chris Lattner812646a2006-05-05 05:58:59 +00005598 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005599 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005600 // on vectors in one instruction. We only perform this transformation on
5601 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005602 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005603 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005604 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005605 bool DoXform = true;
5606 SmallVector<SDNode*, 4> SetCCs;
5607 if (!N0.hasOneUse())
5608 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5609 if (DoXform) {
5610 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005611 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005612 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005613 LN0->getBasePtr(), N0.getValueType(),
5614 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005615 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005616 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005617 N0.getValueType(), ExtLoad);
5618 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005619 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005620 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005621 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5622 }
Chris Lattner812646a2006-05-05 05:58:59 +00005623 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005624
Chris Lattner812646a2006-05-05 05:58:59 +00005625 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5626 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5627 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005628 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005629 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005630 N0.hasOneUse()) {
5631 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005632 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005633 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005634 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5635 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5636 VT, LN0->getChain(), LN0->getBasePtr(),
5637 MemVT, LN0->getMemOperand());
5638 CombineTo(N, ExtLoad);
5639 CombineTo(N0.getNode(),
5640 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5641 N0.getValueType(), ExtLoad),
5642 ExtLoad.getValue(1));
5643 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5644 }
Chris Lattner812646a2006-05-05 05:58:59 +00005645 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005646
Chris Lattner65786b02007-04-11 05:32:27 +00005647 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005648 // For vectors:
5649 // aext(setcc) -> vsetcc
5650 // aext(setcc) -> truncate(vsetcc)
5651 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005652 // Only do this before legalize for now.
5653 if (VT.isVector() && !LegalOperations) {
5654 EVT N0VT = N0.getOperand(0).getValueType();
5655 // We know that the # elements of the results is the same as the
5656 // # elements of the compare (and the # elements of the compare result
5657 // for that matter). Check to see that they are the same size. If so,
5658 // we know that the element size of the sext'd result matches the
5659 // element size of the compare operands.
5660 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005661 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005662 N0.getOperand(1),
5663 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005664 // If the desired elements are smaller or larger than the source
5665 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005666 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005667 else {
Hao Liuc636d152014-04-22 09:57:06 +00005668 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005669 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005670 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005671 N0.getOperand(1),
5672 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005673 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005674 }
5675 }
5676
5677 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005678 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005679 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005680 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005681 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005682 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005683 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005684 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005685
Evan Chengf1005572010-04-28 07:10:39 +00005686 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005687}
5688
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005689/// See if the specified operand can be simplified with the knowledge that only
5690/// the bits specified by Mask are used. If so, return the simpler operand,
5691/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005692SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005693 switch (V.getOpcode()) {
5694 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005695 case ISD::Constant: {
5696 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005697 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005698 const APInt &CVal = CV->getAPIntValue();
5699 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005700 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005701 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005702 break;
5703 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005704 case ISD::OR:
5705 case ISD::XOR:
5706 // If the LHS or RHS don't contribute bits to the or, drop them.
5707 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5708 return V.getOperand(1);
5709 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5710 return V.getOperand(0);
5711 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005712 case ISD::SRL:
5713 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005714 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005715 break;
5716 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5717 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005718 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005719
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005720 // Watch out for shift count overflow though.
5721 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005722 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005723 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005724 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005725 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005726 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005727 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005728 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005729 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005730}
5731
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005732/// If the result of a wider load is shifted to right of N bits and then
5733/// truncated to a narrower type and where N is a multiple of number of bits of
5734/// the narrower type, transform it to a narrower load from address + N / num of
5735/// bits of new type. If the result is to be extended, also fold the extension
5736/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005737SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005738 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005739
Evan Cheng464dc9b2007-03-22 01:54:19 +00005740 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005741 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005742 EVT VT = N->getValueType(0);
5743 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005744
Dan Gohman550c9af2008-08-14 20:04:46 +00005745 // This transformation isn't valid for vector loads.
5746 if (VT.isVector())
5747 return SDValue();
5748
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005749 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005750 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005751 if (Opc == ISD::SIGN_EXTEND_INREG) {
5752 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005753 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005754 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005755 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005756 ExtType = ISD::ZEXTLOAD;
5757 N0 = SDValue(N, 0);
5758 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5759 if (!N01) return SDValue();
5760 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5761 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005762 }
Richard Osborne272e0842011-01-31 17:41:44 +00005763 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5764 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005765
Owen Anderson53aa7a92009-08-10 22:56:29 +00005766 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005767
Chris Lattner9a499e92010-12-22 08:01:44 +00005768 // Do not generate loads of non-round integer types since these can
5769 // be expensive (and would be wrong if the type is not byte sized).
5770 if (!ExtVT.isRound())
5771 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005772
Evan Cheng464dc9b2007-03-22 01:54:19 +00005773 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005774 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005775 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005776 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005777 // Is the shift amount a multiple of size of VT?
5778 if ((ShAmt & (EVTBits-1)) == 0) {
5779 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005780 // Is the load width a multiple of size of VT?
5781 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005782 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005783 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005784
Chris Lattnercafc1e62010-12-22 08:02:57 +00005785 // At this point, we must have a load or else we can't do the transform.
5786 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005787
Chandler Carruthb27041c2012-12-11 00:36:57 +00005788 // Because a SRL must be assumed to *need* to zero-extend the high bits
5789 // (as opposed to anyext the high bits), we can't combine the zextload
5790 // lowering of SRL and an sextload.
5791 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5792 return SDValue();
5793
Chris Lattnera2050552010-10-01 05:36:09 +00005794 // If the shift amount is larger than the input type then we're not
5795 // accessing any of the loaded bytes. If the load was a zextload/extload
5796 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005797 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005798 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005799 }
5800 }
5801
Dan Gohman68fb0042010-11-03 01:47:46 +00005802 // If the load is shifted left (and the result isn't shifted back right),
5803 // we can fold the truncate through the shift.
5804 unsigned ShLeftAmt = 0;
5805 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005806 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005807 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5808 ShLeftAmt = N01->getZExtValue();
5809 N0 = N0.getOperand(0);
5810 }
5811 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005812
Chris Lattner222374d2010-12-22 07:36:50 +00005813 // If we haven't found a load, we can't narrow it. Don't transform one with
5814 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005815 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5816 return SDValue();
5817
5818 // Don't change the width of a volatile load.
5819 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5820 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005821 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005822
Chris Lattner9a499e92010-12-22 08:01:44 +00005823 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005824 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005825 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005826
Bill Schmidtd006c692013-01-14 22:04:38 +00005827 // For the transform to be legal, the load must produce only two values
5828 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005829 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005830 // transformation is not equivalent, and the downstream logic to replace
5831 // uses gets things wrong.
5832 if (LN0->getNumValues() > 2)
5833 return SDValue();
5834
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005835 // If the load that we're shrinking is an extload and we're not just
5836 // discarding the extension we can't simply shrink the load. Bail.
5837 // TODO: It would be possible to merge the extensions in some cases.
5838 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5839 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5840 return SDValue();
5841
Chris Lattner222374d2010-12-22 07:36:50 +00005842 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005843
Evan Cheng4c6f9172012-06-26 01:19:33 +00005844 if (PtrType == MVT::Untyped || PtrType.isExtended())
5845 // It's not possible to generate a constant of extended or untyped type.
5846 return SDValue();
5847
Chris Lattner222374d2010-12-22 07:36:50 +00005848 // For big endian targets, we need to adjust the offset to the pointer to
5849 // load the correct bytes.
5850 if (TLI.isBigEndian()) {
5851 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5852 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5853 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005854 }
5855
Chris Lattner222374d2010-12-22 07:36:50 +00005856 uint64_t PtrOff = ShAmt / 8;
5857 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005858 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005859 PtrType, LN0->getBasePtr(),
5860 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005861 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00005862
Chris Lattner9a499e92010-12-22 08:01:44 +00005863 SDValue Load;
5864 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005865 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005866 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005867 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00005868 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005869 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005870 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005871 LN0->getPointerInfo().getWithOffset(PtrOff),
5872 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00005873 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005874
5875 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005876 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005877 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005878
5879 // Shift the result left, if we've swallowed a left shift.
5880 SDValue Result = Load;
5881 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005882 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005883 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5884 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005885 // If the shift amount is as large as the result size (but, presumably,
5886 // no larger than the source) then the useful bits of the result are
5887 // zero; we can't simply return the shortened shift, because the result
5888 // of that operation is undefined.
5889 if (ShLeftAmt >= VT.getSizeInBits())
5890 Result = DAG.getConstant(0, VT);
5891 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005892 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005893 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005894 }
5895
5896 // Return the new loaded value.
5897 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005898}
5899
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005900SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5901 SDValue N0 = N->getOperand(0);
5902 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005903 EVT VT = N->getValueType(0);
5904 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005905 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005906 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005907
Nate Begeman21158fc2005-09-01 00:19:25 +00005908 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005909 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005910 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005911
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005912 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005913 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005914 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005915
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005916 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5917 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005918 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005919 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005920 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005921
Dan Gohman345d63c2008-07-31 00:50:31 +00005922 // fold (sext_in_reg (sext x)) -> (sext x)
5923 // fold (sext_in_reg (aext x)) -> (sext x)
5924 // if x is small enough.
5925 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5926 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005927 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5928 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005929 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005930 }
5931
Chris Lattner9ad59152007-04-17 19:03:21 +00005932 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005933 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005934 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005935
Chris Lattner9ad59152007-04-17 19:03:21 +00005936 // fold operands of sext_in_reg based on knowledge that the top bits are not
5937 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005938 if (SimplifyDemandedBits(SDValue(N, 0)))
5939 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005940
Evan Cheng464dc9b2007-03-22 01:54:19 +00005941 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5942 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005943 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005944 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005945 return NarrowLoad;
5946
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005947 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005948 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005949 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5950 if (N0.getOpcode() == ISD::SRL) {
5951 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005952 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005953 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005954 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005955 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005956 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005957 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005958 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005959 }
5960 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005961
Nate Begeman02b23c62005-10-13 03:11:28 +00005962 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005963 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005964 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005965 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005966 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005967 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005968 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005969 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005970 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005971 LN0->getBasePtr(), EVT,
5972 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005973 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005974 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005975 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005976 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005977 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005978 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005979 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005980 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005981 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005982 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005983 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005984 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005985 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005986 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005987 LN0->getBasePtr(), EVT,
5988 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005989 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005990 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005991 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005992 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005993
5994 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5995 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5996 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5997 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005998 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005999 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006000 BSwap, N1);
6001 }
6002
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006003 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6004 // into a build_vector.
6005 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6006 SmallVector<SDValue, 8> Elts;
6007 unsigned NumElts = N0->getNumOperands();
6008 unsigned ShAmt = VTBits - EVTBits;
6009
6010 for (unsigned i = 0; i != NumElts; ++i) {
6011 SDValue Op = N0->getOperand(i);
6012 if (Op->getOpcode() == ISD::UNDEF) {
6013 Elts.push_back(Op);
6014 continue;
6015 }
6016
6017 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006018 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6019 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006020 Op.getValueType()));
6021 }
6022
Craig Topper48d114b2014-04-26 18:35:24 +00006023 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006024 }
6025
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006026 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006027}
6028
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006029SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6030 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006031 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006032 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006033
6034 // noop truncate
6035 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006036 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006037 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006038 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006039 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006040 // fold (truncate (truncate x)) -> (truncate x)
6041 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006042 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006043 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006044 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6045 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006046 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006047 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006048 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006049 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006050 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006051 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006052 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006053 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006054 // if the source and dest are the same type, we can drop both the extend
6055 // and the truncate.
6056 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006057 }
Evan Chengd63baea2007-03-21 20:14:05 +00006058
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006059 // Fold extract-and-trunc into a narrow extract. For example:
6060 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6061 // i32 y = TRUNCATE(i64 x)
6062 // -- becomes --
6063 // v16i8 b = BITCAST (v2i64 val)
6064 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6065 //
6066 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006067 // creates this pattern) and before operation legalization after which
6068 // we need to be more careful about the vector instructions that we generate.
6069 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006070 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006071
6072 EVT VecTy = N0.getOperand(0).getValueType();
6073 EVT ExTy = N0.getValueType();
6074 EVT TrTy = N->getValueType(0);
6075
6076 unsigned NumElem = VecTy.getVectorNumElements();
6077 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6078
6079 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6080 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6081
6082 SDValue EltNo = N0->getOperand(1);
6083 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6084 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006085 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006086 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6087
Andrew Trickef9de2a2013-05-25 02:42:55 +00006088 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006089 NVT, N0.getOperand(0));
6090
6091 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006092 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006093 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006094 }
6095 }
6096
Matt Arsenault3332b702014-07-10 18:21:04 +00006097 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6098 if (N0.getOpcode() == ISD::SELECT) {
6099 EVT SrcVT = N0.getValueType();
6100 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6101 TLI.isTruncateFree(SrcVT, VT)) {
6102 SDLoc SL(N0);
6103 SDValue Cond = N0.getOperand(0);
6104 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6105 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6106 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6107 }
6108 }
6109
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006110 // Fold a series of buildvector, bitcast, and truncate if possible.
6111 // For example fold
6112 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6113 // (2xi32 (buildvector x, y)).
6114 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6115 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6116 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6117 N0.getOperand(0).hasOneUse()) {
6118
6119 SDValue BuildVect = N0.getOperand(0);
6120 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6121 EVT TruncVecEltTy = VT.getVectorElementType();
6122
6123 // Check that the element types match.
6124 if (BuildVectEltTy == TruncVecEltTy) {
6125 // Now we only need to compute the offset of the truncated elements.
6126 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6127 unsigned TruncVecNumElts = VT.getVectorNumElements();
6128 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6129
6130 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6131 "Invalid number of elements");
6132
6133 SmallVector<SDValue, 8> Opnds;
6134 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6135 Opnds.push_back(BuildVect.getOperand(i));
6136
Craig Topper48d114b2014-04-26 18:35:24 +00006137 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006138 }
6139 }
6140
Chris Lattner5e6fe052007-10-13 06:35:54 +00006141 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006142 // only the low bits are being used.
6143 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006144 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006145 // may have different active low bits.
6146 if (!VT.isVector()) {
6147 SDValue Shorter =
6148 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6149 VT.getSizeInBits()));
6150 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006151 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006152 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006153 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006154 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006155 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6156 SDValue Reduced = ReduceLoadWidth(N);
6157 if (Reduced.getNode())
6158 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006159 // Handle the case where the load remains an extending load even
6160 // after truncation.
6161 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6162 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6163 if (!LN0->isVolatile() &&
6164 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6165 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6166 VT, LN0->getChain(), LN0->getBasePtr(),
6167 LN0->getMemoryVT(),
6168 LN0->getMemOperand());
6169 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6170 return NewLoad;
6171 }
6172 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006173 }
Michael Liao3ac82012012-10-17 23:45:54 +00006174 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6175 // where ... are all 'undef'.
6176 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6177 SmallVector<EVT, 8> VTs;
6178 SDValue V;
6179 unsigned Idx = 0;
6180 unsigned NumDefs = 0;
6181
6182 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6183 SDValue X = N0.getOperand(i);
6184 if (X.getOpcode() != ISD::UNDEF) {
6185 V = X;
6186 Idx = i;
6187 NumDefs++;
6188 }
6189 // Stop if more than one members are non-undef.
6190 if (NumDefs > 1)
6191 break;
6192 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6193 VT.getVectorElementType(),
6194 X.getValueType().getVectorNumElements()));
6195 }
6196
6197 if (NumDefs == 0)
6198 return DAG.getUNDEF(VT);
6199
6200 if (NumDefs == 1) {
6201 assert(V.getNode() && "The single defined operand is empty!");
6202 SmallVector<SDValue, 8> Opnds;
6203 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6204 if (i != Idx) {
6205 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6206 continue;
6207 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006208 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006209 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006210 Opnds.push_back(NV);
6211 }
Craig Topper48d114b2014-04-26 18:35:24 +00006212 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006213 }
6214 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006215
6216 // Simplify the operands using demanded-bits information.
6217 if (!VT.isVector() &&
6218 SimplifyDemandedBits(SDValue(N, 0)))
6219 return SDValue(N, 0);
6220
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006221 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006222}
6223
Evan Chengb980f6f2008-05-12 23:04:07 +00006224static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006225 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006226 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006227 return Elt.getNode();
6228 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006229}
6230
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006231/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006232/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006233SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006234 assert(N->getOpcode() == ISD::BUILD_PAIR);
6235
Nate Begeman624690c2009-06-05 21:37:30 +00006236 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6237 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006238 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006239 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006240 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006241 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006242
Evan Chengb980f6f2008-05-12 23:04:07 +00006243 if (ISD::isNON_EXTLoad(LD2) &&
6244 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006245 // If both are volatile this would reduce the number of volatile loads.
6246 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006247 !LD1->isVolatile() &&
6248 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006249 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006250 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006251 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006252 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006253
Duncan Sands8651e9c2008-06-13 19:07:40 +00006254 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006255 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006256 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006257 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006258 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006259 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006260
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006261 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006262}
6263
Wesley Peck527da1b2010-11-23 03:31:01 +00006264SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006265 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006266 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006267
Dan Gohmana8665142007-06-25 16:23:39 +00006268 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6269 // Only do this before legalize, since afterward the target may be depending
6270 // on the bitconvert.
6271 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006272 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006273 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006274 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006275 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006276
Owen Anderson53aa7a92009-08-10 22:56:29 +00006277 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006278 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006279 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006280 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006281 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006282 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006283
Dan Gohman921ddd62008-09-05 01:58:21 +00006284 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006285 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006286 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006287 if (Res.getNode() != N) {
6288 if (!LegalOperations ||
6289 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6290 return Res;
6291
6292 // Folding it resulted in an illegal node, and it's too late to
6293 // do that. Clean up the old node and forego the transformation.
6294 // Ideally this won't happen very often, because instcombine
6295 // and the earlier dagcombine runs (where illegal nodes are
6296 // permitted) should have folded most of them already.
Chandler Carruth18066972014-08-02 10:02:07 +00006297 deleteAndRecombine(Res.getNode());
Dan Gohman733a64d2009-08-10 23:15:10 +00006298 }
Chris Lattnera1874602005-12-23 05:30:37 +00006299 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006300
Bill Wendling4e0a6152009-01-30 22:44:24 +00006301 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006302 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006303 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006304 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006305
Chris Lattner54560f62005-12-23 05:44:41 +00006306 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006307 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006308 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006309 // Do not change the width of a volatile load.
6310 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006311 // Do not remove the cast if the types differ in endian layout.
6312 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6313 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006314 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6315 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006316 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006317 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006318 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006319 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006320
Evan Chenga4cf58a2007-05-07 21:27:48 +00006321 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006322 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006323 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006324 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006325 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006326 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006327 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006328 return Load;
6329 }
Chris Lattner54560f62005-12-23 05:44:41 +00006330 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006331
Bill Wendling4e0a6152009-01-30 22:44:24 +00006332 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6333 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006334 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006335 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6336 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006337 N0.getNode()->hasOneUse() && VT.isInteger() &&
6338 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006339 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006340 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006341 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006342
Duncan Sands13237ac2008-06-06 12:08:01 +00006343 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006344 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006345 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006346 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006347 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006348 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006349 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006350 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006351
Bill Wendling4e0a6152009-01-30 22:44:24 +00006352 // fold (bitconvert (fcopysign cst, x)) ->
6353 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6354 // Note that we don't handle (copysign x, cst) because this can always be
6355 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006356 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006357 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006358 VT.isInteger() && !VT.isVector()) {
6359 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006360 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006361 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006362 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006363 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006364 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006365
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006366 // If X has a different width than the result/lhs, sext it or truncate it.
6367 unsigned VTWidth = VT.getSizeInBits();
6368 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006369 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006370 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006371 } else if (OrigXWidth > VTWidth) {
6372 // To get the sign bit in the right place, we have to shift it right
6373 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006374 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006375 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006376 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006377 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006378 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006379 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006380 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006381
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006382 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006383 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006384 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006385 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006386
Andrew Trickef9de2a2013-05-25 02:42:55 +00006387 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006388 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006389 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006390 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006391 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006392
Andrew Trickef9de2a2013-05-25 02:42:55 +00006393 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006394 }
Chris Lattner888560d2008-01-27 17:42:27 +00006395 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006396
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006397 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006398 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006399 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6400 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006401 return CombineLD;
6402 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006403
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006404 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006405}
6406
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006407SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006408 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006409 return CombineConsecutiveLoads(N, VT);
6410}
6411
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006412/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6413/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006414SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006415ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006416 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006417
Chris Lattnere4e64b62006-04-02 02:53:43 +00006418 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006419 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006420
Duncan Sands13237ac2008-06-06 12:08:01 +00006421 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6422 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006423
Chris Lattnere4e64b62006-04-02 02:53:43 +00006424 // If this is a conversion of N elements of one type to N elements of another
6425 // type, convert each element. This handles FP<->INT cases.
6426 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006427 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6428 BV->getValueType(0).getVectorNumElements());
6429
6430 // Due to the FP element handling below calling this routine recursively,
6431 // we can end up with a scalar-to-vector node here.
6432 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006433 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6434 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006435 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006436
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006437 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006438 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006439 SDValue Op = BV->getOperand(i);
6440 // If the vector element type is not legal, the BUILD_VECTOR operands
6441 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006442 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006443 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6444 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006445 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006446 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006447 }
Craig Topper48d114b2014-04-26 18:35:24 +00006448 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006450
Chris Lattnere4e64b62006-04-02 02:53:43 +00006451 // Otherwise, we're growing or shrinking the elements. To avoid having to
6452 // handle annoying details of growing/shrinking FP values, we convert them to
6453 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006454 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006455 // Convert the input float vector to a int vector where the elements are the
6456 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006457 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006458 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006459 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006460 SrcEltVT = IntVT;
6461 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006462
Chris Lattnere4e64b62006-04-02 02:53:43 +00006463 // Now we know the input is an integer vector. If the output is a FP type,
6464 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006465 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006466 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006467 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006468 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006469
Chris Lattnere4e64b62006-04-02 02:53:43 +00006470 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006471 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006473
Chris Lattnere4e64b62006-04-02 02:53:43 +00006474 // Okay, we know the src/dst types are both integers of differing types.
6475 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006476 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006477 if (SrcBitSize < DstBitSize) {
6478 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006479
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006480 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006481 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006482 i += NumInputsPerOutput) {
6483 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006484 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006485 bool EltIsUndef = true;
6486 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6487 // Shift the previously computed bits over.
6488 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006489 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006490 if (Op.getOpcode() == ISD::UNDEF) continue;
6491 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006492
Jay Foad583abbc2010-12-07 08:25:19 +00006493 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006494 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006496
Chris Lattnere4e64b62006-04-02 02:53:43 +00006497 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006498 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006499 else
6500 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6501 }
6502
Owen Anderson117c9e82009-08-12 00:36:31 +00006503 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006504 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006505 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006506
Chris Lattnere4e64b62006-04-02 02:53:43 +00006507 // Finally, this must be the case where we are shrinking elements: each input
6508 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006509 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006510 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006511 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6512 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006513 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006514
Dan Gohmana8665142007-06-25 16:23:39 +00006515 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006516 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6517 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006518 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006519 continue;
6520 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006521
Jay Foad583abbc2010-12-07 08:25:19 +00006522 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6523 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006524
Chris Lattnere4e64b62006-04-02 02:53:43 +00006525 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006526 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006527 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006528 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006529 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006530 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006531 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006532 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006533 }
6534
6535 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006536 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006537 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6538 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006539
Craig Topper48d114b2014-04-26 18:35:24 +00006540 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006541}
6542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006543SDValue DAGCombiner::visitFADD(SDNode *N) {
6544 SDValue N0 = N->getOperand(0);
6545 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006546 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6547 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006548 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006549 const TargetOptions &Options = DAG.getTarget().Options;
Sanjay Patel159f1272014-08-27 21:42:42 +00006550
Dan Gohmana8665142007-06-25 16:23:39 +00006551 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006552 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006553 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006554 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006555 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006556
Lang Hamesa33db652012-06-14 20:37:15 +00006557 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006558 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006559 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006560
Nate Begeman418c6e42005-10-18 00:28:13 +00006561 // canonicalize constant to RHS
6562 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006563 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006564
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006565 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006566 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006567 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006568 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006569 GetNegatedExpression(N1, DAG, LegalOperations));
Sanjay Patel8170dea2014-09-08 17:32:19 +00006570
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006571 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006572 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006573 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006574 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006575 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006576
Sanjay Patel8170dea2014-09-08 17:32:19 +00006577 // If 'unsafe math' is enabled, fold lots of things.
6578 if (Options.UnsafeFPMath) {
6579 // No FP constant should be created after legalization as Instruction
6580 // Selection pass has a hard time dealing with FP constants.
6581 bool AllowNewConst = (Level < AfterLegalizeDAG);
6582
6583 // fold (fadd A, 0) -> A
6584 if (N1CFP && N1CFP->getValueAPF().isZero())
6585 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006586
Sanjay Patel8170dea2014-09-08 17:32:19 +00006587 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6588 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6589 isa<ConstantFPSDNode>(N0.getOperand(1)))
6590 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6591 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6592 N0.getOperand(1), N1));
6593
6594 // If allowed, fold (fadd (fneg x), x) -> 0.0
6595 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6596 return DAG.getConstantFP(0.0, VT);
6597
6598 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6599 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6600 return DAG.getConstantFP(0.0, VT);
6601
6602 // We can fold chains of FADD's of the same value into multiplications.
6603 // This transform is not safe in general because we are reducing the number
6604 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00006605 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6606 if (N0.getOpcode() == ISD::FMUL) {
6607 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6608 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6609
Sanjay Patel8170dea2014-09-08 17:32:19 +00006610 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6611 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6612 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6613 SDValue(CFP01, 0),
6614 DAG.getConstantFP(1.0, VT));
6615 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6616 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006617
6618 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6619 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6620 N1.getOperand(0) == N1.getOperand(1) &&
6621 N0.getOperand(0) == N1.getOperand(0)) {
6622 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6623 SDValue(CFP01, 0),
6624 DAG.getConstantFP(2.0, VT));
6625 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6626 N0.getOperand(0), NewCFP);
6627 }
Owen Andersoncc61f872012-08-30 23:35:16 +00006628 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006629
6630 if (N1.getOpcode() == ISD::FMUL) {
6631 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6632 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6633
Sanjay Patel8170dea2014-09-08 17:32:19 +00006634 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6635 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6636 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6637 SDValue(CFP11, 0),
6638 DAG.getConstantFP(1.0, VT));
6639 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6640 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00006641
Sanjay Patel8170dea2014-09-08 17:32:19 +00006642 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6643 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6644 N0.getOperand(0) == N0.getOperand(1) &&
6645 N1.getOperand(0) == N0.getOperand(0)) {
6646 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6647 SDValue(CFP11, 0),
6648 DAG.getConstantFP(2.0, VT));
6649 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6650 }
Owen Andersoncc61f872012-08-30 23:35:16 +00006651 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00006652
Sanjay Patel8170dea2014-09-08 17:32:19 +00006653 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6654 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6655 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6656 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6657 (N0.getOperand(0) == N1))
6658 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6659 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006660 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006661
6662 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6663 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6664 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6665 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6666 N1.getOperand(0) == N0)
6667 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6668 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006669 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006670
6671 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6672 if (AllowNewConst &&
6673 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00006674 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006675 N1.getOperand(0) == N1.getOperand(1) &&
6676 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006677 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00006678 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006679 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006680 } // enable-unsafe-fp-math
6681
Lang Hames39fb1d02012-06-19 22:51:23 +00006682 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006683 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherd9134482014-08-04 21:25:23 +00006684 DAG.getTarget()
6685 .getSubtargetImpl()
6686 ->getTargetLowering()
6687 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006688 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006689
6690 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Hal Finkel62ac7362014-09-19 11:42:56 +00006691 if (N0.getOpcode() == ISD::FMUL &&
6692 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006693 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006694 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006695
Michael Liaoec3850122012-09-01 04:09:16 +00006696 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006697 // Note: Commutes FADD operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00006698 if (N1.getOpcode() == ISD::FMUL &&
6699 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006700 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006701 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006702 }
6703
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006704 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006705}
6706
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006707SDValue DAGCombiner::visitFSUB(SDNode *N) {
6708 SDValue N0 = N->getOperand(0);
6709 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00006710 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6711 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006712 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006713 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006714 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006715
Dan Gohmana8665142007-06-25 16:23:39 +00006716 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006717 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006718 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006719 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006720 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006721
Nate Begeman418c6e42005-10-18 00:28:13 +00006722 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006723 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006724 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00006725
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006726 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006727 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006728 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006729 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006730
Sanjay Patelae402a32014-08-27 20:57:52 +00006731 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00006732 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00006733 // (fsub A, 0) -> A
6734 if (N1CFP && N1CFP->getValueAPF().isZero())
6735 return N0;
6736
6737 // (fsub 0, B) -> -B
6738 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00006739 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00006740 return GetNegatedExpression(N1, DAG, LegalOperations);
6741 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6742 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6743 }
6744
6745 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00006746 if (N0 == N1)
6747 return DAG.getConstantFP(0.0f, VT);
6748
Sanjay Patelae402a32014-08-27 20:57:52 +00006749 // (fsub x, (fadd x, y)) -> (fneg y)
6750 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00006751 if (N1.getOpcode() == ISD::FADD) {
6752 SDValue N10 = N1->getOperand(0);
6753 SDValue N11 = N1->getOperand(1);
6754
Sanjay Patel78614bf2014-08-28 15:53:16 +00006755 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006756 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006757
Sanjay Patel78614bf2014-08-28 15:53:16 +00006758 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006759 return GetNegatedExpression(N10, DAG, LegalOperations);
6760 }
6761 }
6762
Lang Hames39fb1d02012-06-19 22:51:23 +00006763 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006764 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Sanjay Patela828f2b2014-08-27 20:40:31 +00006765 DAG.getTarget().getSubtargetImpl()
Eric Christopherd9134482014-08-04 21:25:23 +00006766 ->getTargetLowering()
6767 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006768 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006769
6770 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Hal Finkel62ac7362014-09-19 11:42:56 +00006771 if (N0.getOpcode() == ISD::FMUL &&
6772 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006773 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006774 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006775 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006776
6777 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6778 // Note: Commutes FSUB operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00006779 if (N1.getOpcode() == ISD::FMUL &&
6780 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006781 return DAG.getNode(ISD::FMA, dl, VT,
6782 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006783 N1.getOperand(0)),
6784 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006785
Stephen Lin8e8424e2013-07-09 00:44:49 +00006786 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006787 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006788 N0.getOperand(0).getOpcode() == ISD::FMUL &&
Hal Finkel62ac7362014-09-19 11:42:56 +00006789 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6790 TLI.enableAggressiveFMAFusion(VT))) {
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006791 SDValue N00 = N0.getOperand(0).getOperand(0);
6792 SDValue N01 = N0.getOperand(0).getOperand(1);
6793 return DAG.getNode(ISD::FMA, dl, VT,
6794 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6795 DAG.getNode(ISD::FNEG, dl, VT, N1));
6796 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006797 }
6798
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006799 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006800}
6801
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006802SDValue DAGCombiner::visitFMUL(SDNode *N) {
6803 SDValue N0 = N->getOperand(0);
6804 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00006805 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6806 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006807 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006808 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006809
Dan Gohmana8665142007-06-25 16:23:39 +00006810 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006811 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00006812 // This just handles C1 * C2 for vectors. Other vector folds are below.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006813 SDValue FoldedVOp = SimplifyVBinOp(N);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00006814 if (FoldedVOp.getNode())
6815 return FoldedVOp;
6816 // Canonicalize vector constant to RHS.
6817 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6818 N1.getOpcode() != ISD::BUILD_VECTOR)
6819 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6820 if (BV0->isConstant())
6821 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
Dan Gohman80f9f072007-07-13 20:03:40 +00006822 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006823
Nate Begemanec48a1b2005-10-17 20:40:11 +00006824 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006825 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006826 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00006827
Nate Begemanec48a1b2005-10-17 20:40:11 +00006828 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006829 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006830 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00006831
Owen Andersonb5f167c2012-05-02 21:32:35 +00006832 // fold (fmul A, 1.0) -> A
6833 if (N1CFP && N1CFP->isExactlyValue(1.0))
6834 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00006835
Sanjay Patel394c3332014-09-08 20:16:42 +00006836 if (Options.UnsafeFPMath) {
6837 // fold (fmul A, 0) -> 0
6838 if (N1CFP && N1CFP->getValueAPF().isZero())
6839 return N1;
6840
6841 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00006842 if (N0.getOpcode() == ISD::FMUL) {
6843 // Fold scalars or any vector constants (not just splats).
6844 // This fold is done in general by InstCombine, but extra fmul insts
6845 // may have been generated during lowering.
6846 SDValue N01 = N0.getOperand(1);
6847 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6848 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6849 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6850 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6851 SDLoc SL(N);
6852 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6853 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6854 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00006855 }
6856
Sanjay Patel394c3332014-09-08 20:16:42 +00006857 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00006858 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6859 // during an early run of DAGCombiner can prevent folding with fmuls
6860 // inserted during lowering.
6861 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6862 SDLoc SL(N);
6863 const SDValue Two = DAG.getConstantFP(2.0, VT);
6864 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6865 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6866 }
6867 }
6868
Nate Begemanec48a1b2005-10-17 20:40:11 +00006869 // fold (fmul X, 2.0) -> (fadd X, X)
6870 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006871 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00006872
Dan Gohmanb7170912009-08-10 16:50:32 +00006873 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006874 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006875 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006876 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006877
Bill Wendling3dc5d242009-01-30 22:57:07 +00006878 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006879 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6880 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006881 // Both can be negated for free, check to see if at least one is cheaper
6882 // negated.
6883 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006884 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006885 GetNegatedExpression(N0, DAG, LegalOperations),
6886 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006887 }
6888 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006889
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006890 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006891}
6892
Owen Anderson41b06652012-05-02 22:17:40 +00006893SDValue DAGCombiner::visitFMA(SDNode *N) {
6894 SDValue N0 = N->getOperand(0);
6895 SDValue N1 = N->getOperand(1);
6896 SDValue N2 = N->getOperand(2);
6897 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6898 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6899 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006900 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006901 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00006902
6903 // Constant fold FMA.
6904 if (isa<ConstantFPSDNode>(N0) &&
6905 isa<ConstantFPSDNode>(N1) &&
6906 isa<ConstantFPSDNode>(N2)) {
6907 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6908 }
6909
Sanjay Patel78614bf2014-08-28 15:53:16 +00006910 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00006911 if (N0CFP && N0CFP->isZero())
6912 return N2;
6913 if (N1CFP && N1CFP->isZero())
6914 return N2;
6915 }
Owen Anderson41b06652012-05-02 22:17:40 +00006916 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006917 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006918 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006919 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006920
Owen Andersonc7aaf522012-05-30 18:50:39 +00006921 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006922 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006923 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006924
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006925 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006926 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006927 N2.getOpcode() == ISD::FMUL &&
6928 N0 == N2.getOperand(0) &&
6929 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6930 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6931 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6932 }
6933
6934
6935 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006936 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006937 N0.getOpcode() == ISD::FMUL && N1CFP &&
6938 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6939 return DAG.getNode(ISD::FMA, dl, VT,
6940 N0.getOperand(0),
6941 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6942 N2);
6943 }
6944
6945 // (fma x, 1, y) -> (fadd x, y)
6946 // (fma x, -1, y) -> (fadd (fneg x), y)
6947 if (N1CFP) {
6948 if (N1CFP->isExactlyValue(1.0))
6949 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6950
6951 if (N1CFP->isExactlyValue(-1.0) &&
6952 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6953 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006954 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006955 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6956 }
6957 }
6958
6959 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006960 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006961 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006962 DAG.getNode(ISD::FADD, dl, VT,
6963 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006964
6965 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00006966 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006967 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6968 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006969 DAG.getNode(ISD::FADD, dl, VT,
6970 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006971
6972
Owen Anderson41b06652012-05-02 22:17:40 +00006973 return SDValue();
6974}
6975
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006976SDValue DAGCombiner::visitFDIV(SDNode *N) {
6977 SDValue N0 = N->getOperand(0);
6978 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006979 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6980 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006981 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00006982 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006983 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006984
Dan Gohmana8665142007-06-25 16:23:39 +00006985 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006986 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006987 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006988 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006989 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006990
Nate Begeman569c4392006-01-18 22:35:16 +00006991 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006992 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006993 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006994
Sanjay Patelb67bd262014-09-21 15:19:15 +00006995 if (Options.UnsafeFPMath) {
6996 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6997 if (N1CFP) {
6998 // Compute the reciprocal 1.0 / c2.
6999 APFloat N1APF = N1CFP->getValueAPF();
7000 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7001 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7002 // Only do the transform if the reciprocal is a legal fp immediate that
7003 // isn't too nasty (eg NaN, denormal, ...).
7004 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7005 (!LegalOperations ||
7006 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7007 // backend)... we should handle this gracefully after Legalize.
7008 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7009 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7010 TLI.isFPImmLegal(Recip, VT)))
7011 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7012 DAG.getConstantFP(Recip, VT));
7013 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007014
Sanjay Patelb67bd262014-09-21 15:19:15 +00007015 // If this FDIV is part of a reciprocal square root, it may be folded
7016 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007017 if (N1.getOpcode() == ISD::FSQRT) {
7018 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7019 AddToWorklist(RV.getNode());
7020 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7021 }
7022 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7023 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7024 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7025 AddToWorklist(RV.getNode());
7026 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7027 AddToWorklist(RV.getNode());
7028 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7029 }
7030 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7031 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7032 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7033 AddToWorklist(RV.getNode());
7034 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7035 AddToWorklist(RV.getNode());
7036 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7037 }
7038 }
7039
7040 // Fold into a reciprocal estimate and multiply instead of a real divide.
7041 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7042 AddToWorklist(RV.getNode());
7043 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7044 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00007045 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007046
Bill Wendling3dc5d242009-01-30 22:57:07 +00007047 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007048 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7049 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007050 // Both can be negated for free, check to see if at least one is cheaper
7051 // negated.
7052 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007053 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007054 GetNegatedExpression(N0, DAG, LegalOperations),
7055 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007056 }
7057 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007058
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007059 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007060}
7061
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007062SDValue DAGCombiner::visitFREM(SDNode *N) {
7063 SDValue N0 = N->getOperand(0);
7064 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007065 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7066 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007067 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007068
Nate Begeman569c4392006-01-18 22:35:16 +00007069 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007070 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007071 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007072
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007073 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007074}
7075
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007076SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7077 if (DAG.getTarget().Options.UnsafeFPMath) {
7078 // Compute this as 1/(1/sqrt(X)): the reciprocal of the reciprocal sqrt.
7079 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7080 AddToWorklist(RV.getNode());
7081 RV = BuildReciprocalEstimate(RV);
7082 if (RV.getNode()) {
7083 // Unfortunately, RV is now NaN if the input was exactly 0.
7084 // Select out this case and force the answer to 0.
7085 EVT VT = RV.getValueType();
7086
7087 SDValue Zero = DAG.getConstantFP(0.0, VT);
7088 SDValue ZeroCmp =
7089 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7090 N->getOperand(0), Zero, ISD::SETEQ);
7091 AddToWorklist(ZeroCmp.getNode());
7092 AddToWorklist(RV.getNode());
7093
7094 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7095 SDLoc(N), VT, ZeroCmp, Zero, RV);
7096 return RV;
7097 }
7098 }
7099 }
7100 return SDValue();
7101}
7102
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007103SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7104 SDValue N0 = N->getOperand(0);
7105 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007106 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7107 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007108 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007109
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007110 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007111 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007112
Chris Lattner3bc40502006-03-05 05:30:57 +00007113 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007114 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007115 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7116 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007117 if (!V.isNegative()) {
7118 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007119 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007120 } else {
7121 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007122 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7123 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007124 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007125 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007126
Chris Lattner3bc40502006-03-05 05:30:57 +00007127 // copysign(fabs(x), y) -> copysign(x, y)
7128 // copysign(fneg(x), y) -> copysign(x, y)
7129 // copysign(copysign(x,z), y) -> copysign(x, y)
7130 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7131 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007132 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007133 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007134
7135 // copysign(x, abs(y)) -> abs(x)
7136 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007137 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007138
Chris Lattner3bc40502006-03-05 05:30:57 +00007139 // copysign(x, copysign(y,z)) -> copysign(x, z)
7140 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007141 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007142 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007143
Chris Lattner3bc40502006-03-05 05:30:57 +00007144 // copysign(x, fp_extend(y)) -> copysign(x, y)
7145 // copysign(x, fp_round(y)) -> copysign(x, y)
7146 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007147 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007148 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007149
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007150 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007151}
7152
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007153SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7154 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007155 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007156 EVT VT = N->getValueType(0);
7157 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007158
Nate Begeman21158fc2005-09-01 00:19:25 +00007159 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007160 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007161 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007162 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007163 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007164 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007165
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007166 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7167 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007168 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7169 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007170 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007171 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007172 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007173 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007174
Alp Tokercb402912014-01-24 17:20:08 +00007175 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007176 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007177 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7178 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7179 !VT.isVector() &&
7180 (!LegalOperations ||
7181 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7182 SDValue Ops[] =
7183 { N0.getOperand(0), N0.getOperand(1),
7184 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7185 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007186 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007187 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007188
Nadav Rotem90560762012-07-23 07:59:50 +00007189 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7190 // (select_cc x, y, 1.0, 0.0,, cc)
7191 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7192 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7193 (!LegalOperations ||
7194 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7195 SDValue Ops[] =
7196 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7197 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7198 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007199 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007200 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007201 }
7202
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007203 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007204}
7205
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007206SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7207 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007208 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007209 EVT VT = N->getValueType(0);
7210 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007211
Nate Begeman21158fc2005-09-01 00:19:25 +00007212 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007213 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007214 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007215 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007216 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007217 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007218
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007219 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7220 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007221 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7222 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007223 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007224 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007225 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007226 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007227
Alp Tokercb402912014-01-24 17:20:08 +00007228 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007229 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007230 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007231
Nadav Rotem90560762012-07-23 07:59:50 +00007232 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7233 (!LegalOperations ||
7234 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7235 SDValue Ops[] =
7236 { N0.getOperand(0), N0.getOperand(1),
7237 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7238 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007239 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007240 }
7241 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007242
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007243 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007244}
7245
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007246SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7247 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007248 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007249 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007250
Nate Begeman21158fc2005-09-01 00:19:25 +00007251 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007252 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007253 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007254
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007255 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007256}
7257
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007258SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7259 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007260 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007261 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007262
Nate Begeman21158fc2005-09-01 00:19:25 +00007263 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007264 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007265 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007266
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007267 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007268}
7269
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007270SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7271 SDValue N0 = N->getOperand(0);
7272 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007273 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007274 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007275
Nate Begeman21158fc2005-09-01 00:19:25 +00007276 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007277 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007278 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007279
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007280 // fold (fp_round (fp_extend x)) -> x
7281 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7282 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007283
Chris Lattner0feb1b02008-01-24 06:45:35 +00007284 // fold (fp_round (fp_round x)) -> (fp_round x)
7285 if (N0.getOpcode() == ISD::FP_ROUND) {
7286 // This is a value preserving truncation if both round's are.
7287 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007288 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007289 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007290 DAG.getIntPtrConstant(IsTrunc));
7291 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007292
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007293 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007294 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007295 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007296 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007297 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007298 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007299 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007300 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007301
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007302 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007303}
7304
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007305SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7306 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007307 EVT VT = N->getValueType(0);
7308 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007309 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007310
Nate Begeman21158fc2005-09-01 00:19:25 +00007311 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007312 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007313 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007314 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007315 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007317 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007318}
7319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007320SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7321 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007322 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007323 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007324
Chris Lattner5919b482007-12-29 06:55:23 +00007325 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007326 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007327 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007328 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007329
Nate Begeman21158fc2005-09-01 00:19:25 +00007330 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007331 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007332 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007333
7334 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7335 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007336 if (N0.getOpcode() == ISD::FP_ROUND
7337 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007338 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007339 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007340 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007341 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007342 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007343 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007344 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007345
Chris Lattner72733e52008-01-17 07:00:52 +00007346 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007347 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007348 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007349 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007350 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007351 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007352 LN0->getBasePtr(), N0.getValueType(),
7353 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007354 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007355 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007356 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007357 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007358 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007359 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007360 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007361
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007362 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007363}
7364
Sanjay Patelccd26762014-08-28 21:51:37 +00007365SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7366 SDValue N0 = N->getOperand(0);
7367 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7368 EVT VT = N->getValueType(0);
7369
7370 // fold (fceil c1) -> fceil(c1)
7371 if (N0CFP)
7372 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7373
7374 return SDValue();
7375}
7376
7377SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7378 SDValue N0 = N->getOperand(0);
7379 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7380 EVT VT = N->getValueType(0);
7381
7382 // fold (ftrunc c1) -> ftrunc(c1)
7383 if (N0CFP)
7384 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7385
7386 return SDValue();
7387}
7388
7389SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7390 SDValue N0 = N->getOperand(0);
7391 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7392 EVT VT = N->getValueType(0);
7393
7394 // fold (ffloor c1) -> ffloor(c1)
7395 if (N0CFP)
7396 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7397
7398 return SDValue();
7399}
7400
7401// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007402SDValue DAGCombiner::visitFNEG(SDNode *N) {
7403 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007404 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007405
Craig Topper82384612012-09-11 01:45:21 +00007406 if (VT.isVector()) {
7407 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7408 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007409 }
7410
Sanjay Patelccd26762014-08-28 21:51:37 +00007411 // Constant fold FNEG.
7412 if (isa<ConstantFPSDNode>(N0))
7413 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7414
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007415 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7416 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007417 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007418
Sanjay Patel35d31332014-08-14 15:15:28 +00007419 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007420 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00007421 if (!TLI.isFNegFree(VT) &&
7422 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00007423 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007424 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007425 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007426 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00007427 APInt SignMask;
7428 if (N0.getValueType().isVector()) {
7429 // For a vector, get a mask such as 0x80... per scalar element
7430 // and splat it.
7431 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7432 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7433 } else {
7434 // For a scalar, just generate 0x80...
7435 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7436 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007437 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00007438 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007439 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00007440 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007441 }
7442 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007443
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007444 // (fneg (fmul c, x)) -> (fmul -c, x)
7445 if (N0.getOpcode() == ISD::FMUL) {
7446 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007447 if (CFP1) {
7448 APFloat CVal = CFP1->getValueAPF();
7449 CVal.changeSign();
7450 if (Level >= AfterLegalizeDAG &&
7451 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7452 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7453 return DAG.getNode(
7454 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7455 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7456 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007457 }
7458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007459 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007460}
7461
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007462SDValue DAGCombiner::visitFABS(SDNode *N) {
7463 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007464 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007465
Craig Topper82384612012-09-11 01:45:21 +00007466 if (VT.isVector()) {
7467 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7468 if (FoldedVOp.getNode()) return FoldedVOp;
7469 }
7470
Nate Begeman21158fc2005-09-01 00:19:25 +00007471 // fold (fabs c1) -> fabs(c1)
Sanjay Patelccd26762014-08-28 21:51:37 +00007472 if (isa<ConstantFPSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007473 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007474
Nate Begeman21158fc2005-09-01 00:19:25 +00007475 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007476 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007477 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007478
Nate Begeman21158fc2005-09-01 00:19:25 +00007479 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007480 // fold (fabs (fcopysign x, y)) -> (fabs x)
7481 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007482 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007483
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007484 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007485 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007486 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007487 N0.getOpcode() == ISD::BITCAST &&
7488 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007489 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007490 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007491 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007492 APInt SignMask;
7493 if (N0.getValueType().isVector()) {
7494 // For a vector, get a mask such as 0x7f... per scalar element
7495 // and splat it.
7496 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7497 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7498 } else {
7499 // For a scalar, just generate 0x7f...
7500 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7501 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007502 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007503 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007504 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007505 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007506 }
7507 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007508
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007509 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007510}
7511
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007512SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7513 SDValue Chain = N->getOperand(0);
7514 SDValue N1 = N->getOperand(1);
7515 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007516
Dan Gohman82e80012009-11-17 00:47:23 +00007517 // If N is a constant we could fold this into a fallthrough or unconditional
7518 // branch. However that doesn't happen very often in normal code, because
7519 // Instcombine/SimplifyCFG should have handled the available opportunities.
7520 // If we did this folding here, it would be necessary to update the
7521 // MachineBasicBlock CFG, which is awkward.
7522
Nate Begeman7e7f4392006-02-01 07:19:44 +00007523 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7524 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007525 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007526 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7527 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007528 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007529 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007530 N1.getOperand(0), N1.getOperand(1), N2);
7531 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007532
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007533 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7534 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7535 (N1.getOperand(0).hasOneUse() &&
7536 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007537 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007538 if (N1.getOpcode() == ISD::TRUNCATE) {
7539 // Look pass the truncate.
7540 Trunc = N1.getNode();
7541 N1 = N1.getOperand(0);
7542 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007543
Bill Wendlingaa28be62009-03-26 06:14:09 +00007544 // Match this pattern so that we can generate simpler code:
7545 //
7546 // %a = ...
7547 // %b = and i32 %a, 2
7548 // %c = srl i32 %b, 1
7549 // brcond i32 %c ...
7550 //
7551 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007552 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007553 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007554 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007555 // %c = setcc eq %b, 0
7556 // brcond %c ...
7557 //
7558 // This applies only when the AND constant value has one bit set and the
7559 // SRL constant is equal to the log2 of the AND constant. The back-end is
7560 // smart enough to convert the result into a TEST/JMP sequence.
7561 SDValue Op0 = N1.getOperand(0);
7562 SDValue Op1 = N1.getOperand(1);
7563
7564 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007565 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007566 SDValue AndOp1 = Op0.getOperand(1);
7567
7568 if (AndOp1.getOpcode() == ISD::Constant) {
7569 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7570
7571 if (AndConst.isPowerOf2() &&
7572 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7573 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007574 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007575 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007576 Op0, DAG.getConstant(0, Op0.getValueType()),
7577 ISD::SETNE);
7578
Andrew Trickef9de2a2013-05-25 02:42:55 +00007579 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007580 MVT::Other, Chain, SetCC, N2);
7581 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7582 // will convert it back to (X & C1) >> C2.
7583 CombineTo(N, NewBRCond, false);
7584 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00007585 if (Trunc)
7586 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007587 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007588 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007589 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007590 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007591 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007592 }
7593 }
7594 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007595
7596 if (Trunc)
7597 // Restore N1 if the above transformation doesn't match.
7598 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007599 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007600
Evan Cheng228c31f2010-02-27 07:36:59 +00007601 // Transform br(xor(x, y)) -> br(x != y)
7602 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7603 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7604 SDNode *TheXor = N1.getNode();
7605 SDValue Op0 = TheXor->getOperand(0);
7606 SDValue Op1 = TheXor->getOperand(1);
7607 if (Op0.getOpcode() == Op1.getOpcode()) {
7608 // Avoid missing important xor optimizations.
7609 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007610 if (Tmp.getNode()) {
7611 if (Tmp.getNode() != TheXor) {
7612 DEBUG(dbgs() << "\nReplacing.8 ";
7613 TheXor->dump(&DAG);
7614 dbgs() << "\nWith: ";
7615 Tmp.getNode()->dump(&DAG);
7616 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007617 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007618 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00007619 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007620 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007621 MVT::Other, Chain, Tmp, N2);
7622 }
7623
Benjamin Kramer93354432013-03-30 21:28:18 +00007624 // visitXOR has changed XOR's operands or replaced the XOR completely,
7625 // bail out.
7626 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007627 }
7628 }
7629
7630 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7631 bool Equal = false;
7632 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7633 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7634 Op0.getOpcode() == ISD::XOR) {
7635 TheXor = Op0.getNode();
7636 Equal = true;
7637 }
7638
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007639 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007640 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007641 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007642 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007643 SetCCVT,
7644 Op0, Op1,
7645 Equal ? ISD::SETEQ : ISD::SETNE);
7646 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007647 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007648 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007649 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007650 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007651 MVT::Other, Chain, SetCC, N2);
7652 }
7653 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007654
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007655 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007656}
7657
Chris Lattnera49e16f2005-10-05 06:47:48 +00007658// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7659//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007660SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007661 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007662 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007663
Dan Gohman82e80012009-11-17 00:47:23 +00007664 // If N is a constant we could fold this into a fallthrough or unconditional
7665 // branch. However that doesn't happen very often in normal code, because
7666 // Instcombine/SimplifyCFG should have handled the available opportunities.
7667 // If we did this folding here, it would be necessary to update the
7668 // MachineBasicBlock CFG, which is awkward.
7669
Duncan Sands93b66092008-06-09 11:32:28 +00007670 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007671 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007672 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007673 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007674 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007675
Nate Begemanbd7df032005-10-05 21:43:42 +00007676 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007677 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007678 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007679 N->getOperand(0), Simp.getOperand(2),
7680 Simp.getOperand(0), Simp.getOperand(1),
7681 N->getOperand(4));
7682
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007683 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007684}
7685
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007686/// Return true if 'Use' is a load or a store that uses N as its base pointer
7687/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007688static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7689 SelectionDAG &DAG,
7690 const TargetLowering &TLI) {
7691 EVT VT;
7692 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7693 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7694 return false;
7695 VT = Use->getValueType(0);
7696 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7697 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7698 return false;
7699 VT = ST->getValue().getValueType();
7700 } else
7701 return false;
7702
Chandler Carruth95f83e02013-01-07 15:14:13 +00007703 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007704 if (N->getOpcode() == ISD::ADD) {
7705 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7706 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007707 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007708 AM.BaseOffs = Offset->getSExtValue();
7709 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007710 // [reg +/- reg]
7711 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007712 } else if (N->getOpcode() == ISD::SUB) {
7713 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7714 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007715 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007716 AM.BaseOffs = -Offset->getSExtValue();
7717 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007718 // [reg +/- reg]
7719 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007720 } else
7721 return false;
7722
7723 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7724}
7725
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007726/// Try turning a load/store into a pre-indexed load/store when the base
7727/// pointer is an add or subtract and it has other uses besides the load/store.
7728/// After the transformation, the new indexed load/store has effectively folded
7729/// the add/subtract in and all of its other uses are redirected to the
7730/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00007731bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007732 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007733 return false;
7734
7735 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007736 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007737 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007738 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007739 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007740 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007741 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007742 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007743 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7744 return false;
7745 Ptr = LD->getBasePtr();
7746 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007747 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007748 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007749 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007750 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7751 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7752 return false;
7753 Ptr = ST->getBasePtr();
7754 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007755 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007756 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007757 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007758
Chris Lattnereabc15c2006-11-11 00:56:29 +00007759 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7760 // out. There is no reason to make this a preinc/predec.
7761 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007762 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007763 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007764
Chris Lattnereabc15c2006-11-11 00:56:29 +00007765 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007766 SDValue BasePtr;
7767 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007768 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7769 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7770 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007771
7772 // Backends without true r+i pre-indexed forms may need to pass a
7773 // constant base with a variable offset so that constant coercion
7774 // will work with the patterns in canonical form.
7775 bool Swapped = false;
7776 if (isa<ConstantSDNode>(BasePtr)) {
7777 std::swap(BasePtr, Offset);
7778 Swapped = true;
7779 }
7780
Evan Cheng044a0a82007-05-03 23:52:19 +00007781 // Don't create a indexed load / store with zero offset.
7782 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007783 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007784 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007785
Chris Lattnera0a80032006-11-11 01:00:15 +00007786 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007787 // 1) The new base ptr is a frame index.
7788 // 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 +00007789 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007790 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007791 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007792 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007793
Chris Lattnera0a80032006-11-11 01:00:15 +00007794 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7795 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007796 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007797 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007798
Chris Lattnera0a80032006-11-11 01:00:15 +00007799 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007800 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007801 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007802 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007803 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007804 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007805
Hal Finkel25819052013-02-08 21:35:47 +00007806 // If the offset is a constant, there may be other adds of constants that
7807 // can be folded with this one. We should do this to avoid having to keep
7808 // a copy of the original base pointer.
7809 SmallVector<SDNode *, 16> OtherUses;
7810 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007811 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007812 if (Use == Ptr.getNode())
7813 continue;
7814
7815 if (Use->isPredecessorOf(N))
7816 continue;
7817
7818 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7819 OtherUses.clear();
7820 break;
7821 }
7822
7823 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7824 if (Op1.getNode() == BasePtr.getNode())
7825 std::swap(Op0, Op1);
7826 assert(Op0.getNode() == BasePtr.getNode() &&
7827 "Use of ADD/SUB but not an operand");
7828
7829 if (!isa<ConstantSDNode>(Op1)) {
7830 OtherUses.clear();
7831 break;
7832 }
7833
7834 // FIXME: In some cases, we can be smarter about this.
7835 if (Op1.getValueType() != Offset.getValueType()) {
7836 OtherUses.clear();
7837 break;
7838 }
7839
7840 OtherUses.push_back(Use);
7841 }
7842
7843 if (Swapped)
7844 std::swap(BasePtr, Offset);
7845
Evan Chenga4d187b2007-05-24 02:35:39 +00007846 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007847 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007848
7849 // Caches for hasPredecessorHelper
7850 SmallPtrSet<const SDNode *, 32> Visited;
7851 SmallVector<const SDNode *, 16> Worklist;
7852
Jim Grosbache8160032014-04-11 01:13:13 +00007853 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007854 if (Use == N)
7855 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007856 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007857 return false;
7858
Evan Chengfa832632012-01-13 01:37:24 +00007859 // If Ptr may be folded in addressing mode of other use, then it's
7860 // not profitable to do this transformation.
7861 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007862 RealUse = true;
7863 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007864
Chris Lattnereabc15c2006-11-11 00:56:29 +00007865 if (!RealUse)
7866 return false;
7867
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007868 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007869 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007870 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007871 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007872 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007873 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007874 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007875 ++PreIndexedNodes;
7876 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007877 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007878 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007879 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007880 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007881 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007882 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007883 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007884 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7885 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007886 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007887 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007888 }
7889
Chris Lattnereabc15c2006-11-11 00:56:29 +00007890 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00007891 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007892
Hal Finkel25819052013-02-08 21:35:47 +00007893 if (Swapped)
7894 std::swap(BasePtr, Offset);
7895
7896 // Replace other uses of BasePtr that can be updated to use Ptr
7897 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7898 unsigned OffsetIdx = 1;
7899 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7900 OffsetIdx = 0;
7901 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7902 BasePtr.getNode() && "Expected BasePtr operand");
7903
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007904 // We need to replace ptr0 in the following expression:
7905 // x0 * offset0 + y0 * ptr0 = t0
7906 // knowing that
7907 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007908 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007909 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7910 // indexed load/store and the expresion that needs to be re-written.
7911 //
7912 // Therefore, we have:
7913 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007914
7915 ConstantSDNode *CN =
7916 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007917 int X0, X1, Y0, Y1;
7918 APInt Offset0 = CN->getAPIntValue();
7919 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007920
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007921 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7922 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7923 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7924 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007925
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007926 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7927
7928 APInt CNV = Offset0;
7929 if (X0 < 0) CNV = -CNV;
7930 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7931 else CNV = CNV - Offset1;
7932
7933 // We can now generate the new expression.
7934 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7935 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7936
7937 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007938 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007939 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7940 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00007941 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00007942 }
7943
Chris Lattnereabc15c2006-11-11 00:56:29 +00007944 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007945 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00007946 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007947
7948 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007949}
7950
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007951/// Try to combine a load/store with a add/sub of the base pointer node into a
7952/// post-indexed load/store. The transformation folded the add/subtract into the
7953/// new indexed load/store effectively and all of its uses are redirected to the
7954/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00007955bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007956 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007957 return false;
7958
7959 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007960 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007961 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007962 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007963 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007964 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007965 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007966 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7967 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7968 return false;
7969 Ptr = LD->getBasePtr();
7970 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007971 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007972 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007973 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007974 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7975 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7976 return false;
7977 Ptr = ST->getBasePtr();
7978 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007979 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007980 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007981 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007982
Gabor Greiff304a7a2008-08-28 21:40:38 +00007983 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007984 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007985
Jim Grosbache8160032014-04-11 01:13:13 +00007986 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007987 if (Op == N ||
7988 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7989 continue;
7990
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007991 SDValue BasePtr;
7992 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007993 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7994 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007995 // Don't create a indexed load / store with zero offset.
7996 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007997 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007998 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007999
Chris Lattnereabc15c2006-11-11 00:56:29 +00008000 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00008001 // 1) All uses are load / store ops that use it as base ptr (and
8002 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00008003 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8004 // nor a successor of N. Otherwise, if Op is folded that would
8005 // create a cycle.
8006
Evan Chengcfc05132009-05-06 18:25:01 +00008007 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8008 continue;
8009
Chris Lattnereabc15c2006-11-11 00:56:29 +00008010 // Check for #1.
8011 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008012 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008013 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00008014 continue;
8015
Chris Lattnereabc15c2006-11-11 00:56:29 +00008016 // If all the uses are load / store addresses, then don't do the
8017 // transformation.
8018 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8019 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008020 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00008021 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008022 RealUse = true;
8023 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008024
Chris Lattnereabc15c2006-11-11 00:56:29 +00008025 if (!RealUse) {
8026 TryNext = true;
8027 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00008028 }
8029 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008030 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008031
Chris Lattnereabc15c2006-11-11 00:56:29 +00008032 if (TryNext)
8033 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008034
Chris Lattnereabc15c2006-11-11 00:56:29 +00008035 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00008036 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008037 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00008038 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008039 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008040 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008041 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008042 ++PostIndexedNodes;
8043 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008044 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008045 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008046 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008047 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008048 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008049 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008050 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008051 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8052 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008053 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008054 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008055 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008056
Chris Lattnereabc15c2006-11-11 00:56:29 +00008057 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008058 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008059
8060 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008061 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008062 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008063 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008064 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008065 }
8066 }
8067 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008068
Chris Lattnerffad2162006-11-11 00:39:41 +00008069 return false;
8070}
8071
Hal Finkel51e6fa22014-09-02 06:24:04 +00008072/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8073SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8074 ISD::MemIndexedMode AM = LD->getAddressingMode();
8075 assert(AM != ISD::UNINDEXED);
8076 SDValue BP = LD->getOperand(1);
8077 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008078
8079 // Some backends use TargetConstants for load offsets, but don't expect
8080 // TargetConstants in general ADD nodes. We can convert these constants into
8081 // regular Constants (if the constant is not opaque).
8082 assert((Inc.getOpcode() != ISD::TargetConstant ||
8083 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8084 "Cannot split out indexing using opaque target constants");
8085 if (Inc.getOpcode() == ISD::TargetConstant) {
8086 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8087 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8088 ConstInc->getValueType(0));
8089 }
8090
Hal Finkel51e6fa22014-09-02 06:24:04 +00008091 unsigned Opc =
8092 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8093 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8094}
8095
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008096SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008097 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008098 SDValue Chain = LD->getChain();
8099 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008100
Evan Chenga684cd22007-05-01 00:38:21 +00008101 // If load is not volatile and there are no uses of the loaded value (and
8102 // the updated indexed value in case of indexed loads), change uses of the
8103 // chain value into uses of the chain input (i.e. delete the dead load).
8104 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008105 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008106 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008107 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008108 // It's not safe to use the two value CombineTo variant here. e.g.
8109 // v1, chain2 = load chain1, loc
8110 // v2, chain3 = load chain2, loc
8111 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008112 // Now we replace use of chain2 with chain1. This makes the second load
8113 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008114 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008115 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008116 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008117 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008118 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008119 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008120 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008121
Chandler Carruth18066972014-08-02 10:02:07 +00008122 if (N->use_empty())
8123 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008124
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008125 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008126 }
Evan Chengb68343c2007-05-01 08:53:39 +00008127 } else {
8128 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008129 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008130
Hal Finkele19006e2014-09-02 16:05:23 +00008131 // If this load has an opaque TargetConstant offset, then we cannot split
8132 // the indexing into an add/sub directly (that TargetConstant may not be
8133 // valid for a different type of node, and we cannot convert an opaque
8134 // target constant into a regular constant).
8135 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8136 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00008137
8138 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00008139 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00008140 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00008141 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00008142 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00008143 Index = SplitIndexingFromLoad(LD);
8144 // Try to fold the base pointer arithmetic into subsequent loads and
8145 // stores.
8146 AddUsersToWorklist(N);
8147 } else
8148 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00008149 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008150 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008151 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008152 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008153 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008154 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008155 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00008156 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008157 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008158 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008159 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008160 }
Evan Chenga684cd22007-05-01 00:38:21 +00008161 }
8162 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008163
Chris Lattnere260ed82005-10-10 22:04:48 +00008164 // If this load is directly stored, replace the load value with the stored
8165 // value.
8166 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008167 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008168 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008169 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008170 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8171 if (PrevST->getBasePtr() == Ptr &&
8172 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008173 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008174 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008175 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008176
Evan Cheng43cd9e32010-04-01 06:04:33 +00008177 // Try to infer better alignment information than the load already has.
8178 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008179 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008180 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8181 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008182 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008183 LD->getValueType(0),
8184 Chain, Ptr, LD->getPointerInfo(),
8185 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008186 LD->isVolatile(), LD->isNonTemporal(),
8187 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008188 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8189 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008190 }
8191 }
8192
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008193 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8194 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008195#ifndef NDEBUG
8196 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8197 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8198 UseAA = false;
8199#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008200 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008201 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008202 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008203
Jim Laskey708d0db2006-10-04 16:53:27 +00008204 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008205 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008206 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008207
Jim Laskeyd07be232006-09-25 16:29:54 +00008208 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008209 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008210 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008211 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008212 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008213 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008214 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008215 BetterChain, Ptr, LD->getMemoryVT(),
8216 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008217 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008218
Jim Laskey708d0db2006-10-04 16:53:27 +00008219 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008220 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008221 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008222
Nate Begeman879d8f12009-09-15 00:18:30 +00008223 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008224 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008225
Jim Laskeydcf983c2006-10-13 23:32:28 +00008226 // Replace uses with load result and token factor. Don't add users
8227 // to work list.
8228 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008229 }
8230 }
8231
Evan Cheng357017f2006-11-03 03:06:21 +00008232 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008233 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008234 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008235
Quentin Colombetde0e0622013-10-11 18:29:42 +00008236 // Try to slice up N to more direct loads if the slices are mapped to
8237 // different register banks or pairing can take place.
8238 if (SliceUpLoad(N))
8239 return SDValue(N, 0);
8240
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008241 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008242}
8243
Quentin Colombetde0e0622013-10-11 18:29:42 +00008244namespace {
8245/// \brief Helper structure used to slice a load in smaller loads.
8246/// Basically a slice is obtained from the following sequence:
8247/// Origin = load Ty1, Base
8248/// Shift = srl Ty1 Origin, CstTy Amount
8249/// Inst = trunc Shift to Ty2
8250///
8251/// Then, it will be rewriten into:
8252/// Slice = load SliceTy, Base + SliceOffset
8253/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8254///
8255/// SliceTy is deduced from the number of bits that are actually used to
8256/// build Inst.
8257struct LoadedSlice {
8258 /// \brief Helper structure used to compute the cost of a slice.
8259 struct Cost {
8260 /// Are we optimizing for code size.
8261 bool ForCodeSize;
8262 /// Various cost.
8263 unsigned Loads;
8264 unsigned Truncates;
8265 unsigned CrossRegisterBanksCopies;
8266 unsigned ZExts;
8267 unsigned Shift;
8268
8269 Cost(bool ForCodeSize = false)
8270 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8271 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8272
8273 /// \brief Get the cost of one isolated slice.
8274 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8275 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8276 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8277 EVT TruncType = LS.Inst->getValueType(0);
8278 EVT LoadedType = LS.getLoadedType();
8279 if (TruncType != LoadedType &&
8280 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8281 ZExts = 1;
8282 }
8283
8284 /// \brief Account for slicing gain in the current cost.
8285 /// Slicing provide a few gains like removing a shift or a
8286 /// truncate. This method allows to grow the cost of the original
8287 /// load with the gain from this slice.
8288 void addSliceGain(const LoadedSlice &LS) {
8289 // Each slice saves a truncate.
8290 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8291 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8292 LS.Inst->getOperand(0).getValueType()))
8293 ++Truncates;
8294 // If there is a shift amount, this slice gets rid of it.
8295 if (LS.Shift)
8296 ++Shift;
8297 // If this slice can merge a cross register bank copy, account for it.
8298 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8299 ++CrossRegisterBanksCopies;
8300 }
8301
8302 Cost &operator+=(const Cost &RHS) {
8303 Loads += RHS.Loads;
8304 Truncates += RHS.Truncates;
8305 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8306 ZExts += RHS.ZExts;
8307 Shift += RHS.Shift;
8308 return *this;
8309 }
8310
8311 bool operator==(const Cost &RHS) const {
8312 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8313 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8314 ZExts == RHS.ZExts && Shift == RHS.Shift;
8315 }
8316
8317 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8318
8319 bool operator<(const Cost &RHS) const {
8320 // Assume cross register banks copies are as expensive as loads.
8321 // FIXME: Do we want some more target hooks?
8322 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8323 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8324 // Unless we are optimizing for code size, consider the
8325 // expensive operation first.
8326 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8327 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8328 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8329 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8330 }
8331
8332 bool operator>(const Cost &RHS) const { return RHS < *this; }
8333
8334 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8335
8336 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8337 };
8338 // The last instruction that represent the slice. This should be a
8339 // truncate instruction.
8340 SDNode *Inst;
8341 // The original load instruction.
8342 LoadSDNode *Origin;
8343 // The right shift amount in bits from the original load.
8344 unsigned Shift;
8345 // The DAG from which Origin came from.
8346 // This is used to get some contextual information about legal types, etc.
8347 SelectionDAG *DAG;
8348
Craig Topperc0196b12014-04-14 00:51:57 +00008349 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8350 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008351 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8352
8353 LoadedSlice(const LoadedSlice &LS)
8354 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8355
8356 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8357 /// \return Result is \p BitWidth and has used bits set to 1 and
8358 /// not used bits set to 0.
8359 APInt getUsedBits() const {
8360 // Reproduce the trunc(lshr) sequence:
8361 // - Start from the truncated value.
8362 // - Zero extend to the desired bit width.
8363 // - Shift left.
8364 assert(Origin && "No original load to compare against.");
8365 unsigned BitWidth = Origin->getValueSizeInBits(0);
8366 assert(Inst && "This slice is not bound to an instruction");
8367 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8368 "Extracted slice is bigger than the whole type!");
8369 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8370 UsedBits.setAllBits();
8371 UsedBits = UsedBits.zext(BitWidth);
8372 UsedBits <<= Shift;
8373 return UsedBits;
8374 }
8375
8376 /// \brief Get the size of the slice to be loaded in bytes.
8377 unsigned getLoadedSize() const {
8378 unsigned SliceSize = getUsedBits().countPopulation();
8379 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8380 return SliceSize / 8;
8381 }
8382
8383 /// \brief Get the type that will be loaded for this slice.
8384 /// Note: This may not be the final type for the slice.
8385 EVT getLoadedType() const {
8386 assert(DAG && "Missing context");
8387 LLVMContext &Ctxt = *DAG->getContext();
8388 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8389 }
8390
8391 /// \brief Get the alignment of the load used for this slice.
8392 unsigned getAlignment() const {
8393 unsigned Alignment = Origin->getAlignment();
8394 unsigned Offset = getOffsetFromBase();
8395 if (Offset != 0)
8396 Alignment = MinAlign(Alignment, Alignment + Offset);
8397 return Alignment;
8398 }
8399
8400 /// \brief Check if this slice can be rewritten with legal operations.
8401 bool isLegal() const {
8402 // An invalid slice is not legal.
8403 if (!Origin || !Inst || !DAG)
8404 return false;
8405
8406 // Offsets are for indexed load only, we do not handle that.
8407 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8408 return false;
8409
8410 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8411
8412 // Check that the type is legal.
8413 EVT SliceType = getLoadedType();
8414 if (!TLI.isTypeLegal(SliceType))
8415 return false;
8416
8417 // Check that the load is legal for this type.
8418 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8419 return false;
8420
8421 // Check that the offset can be computed.
8422 // 1. Check its type.
8423 EVT PtrType = Origin->getBasePtr().getValueType();
8424 if (PtrType == MVT::Untyped || PtrType.isExtended())
8425 return false;
8426
8427 // 2. Check that it fits in the immediate.
8428 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8429 return false;
8430
8431 // 3. Check that the computation is legal.
8432 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8433 return false;
8434
8435 // Check that the zext is legal if it needs one.
8436 EVT TruncateType = Inst->getValueType(0);
8437 if (TruncateType != SliceType &&
8438 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8439 return false;
8440
8441 return true;
8442 }
8443
8444 /// \brief Get the offset in bytes of this slice in the original chunk of
8445 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008446 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008447 uint64_t getOffsetFromBase() const {
8448 assert(DAG && "Missing context.");
8449 bool IsBigEndian =
8450 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8451 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8452 uint64_t Offset = Shift / 8;
8453 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8454 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8455 "The size of the original loaded type is not a multiple of a"
8456 " byte.");
8457 // If Offset is bigger than TySizeInBytes, it means we are loading all
8458 // zeros. This should have been optimized before in the process.
8459 assert(TySizeInBytes > Offset &&
8460 "Invalid shift amount for given loaded size");
8461 if (IsBigEndian)
8462 Offset = TySizeInBytes - Offset - getLoadedSize();
8463 return Offset;
8464 }
8465
8466 /// \brief Generate the sequence of instructions to load the slice
8467 /// represented by this object and redirect the uses of this slice to
8468 /// this new sequence of instructions.
8469 /// \pre this->Inst && this->Origin are valid Instructions and this
8470 /// object passed the legal check: LoadedSlice::isLegal returned true.
8471 /// \return The last instruction of the sequence used to load the slice.
8472 SDValue loadSlice() const {
8473 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8474 const SDValue &OldBaseAddr = Origin->getBasePtr();
8475 SDValue BaseAddr = OldBaseAddr;
8476 // Get the offset in that chunk of bytes w.r.t. the endianess.
8477 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8478 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8479 if (Offset) {
8480 // BaseAddr = BaseAddr + Offset.
8481 EVT ArithType = BaseAddr.getValueType();
8482 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8483 DAG->getConstant(Offset, ArithType));
8484 }
8485
8486 // Create the type of the loaded slice according to its size.
8487 EVT SliceType = getLoadedType();
8488
8489 // Create the load for the slice.
8490 SDValue LastInst = DAG->getLoad(
8491 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8492 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8493 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8494 // If the final type is not the same as the loaded type, this means that
8495 // we have to pad with zero. Create a zero extend for that.
8496 EVT FinalType = Inst->getValueType(0);
8497 if (SliceType != FinalType)
8498 LastInst =
8499 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8500 return LastInst;
8501 }
8502
8503 /// \brief Check if this slice can be merged with an expensive cross register
8504 /// bank copy. E.g.,
8505 /// i = load i32
8506 /// f = bitcast i32 i to float
8507 bool canMergeExpensiveCrossRegisterBankCopy() const {
8508 if (!Inst || !Inst->hasOneUse())
8509 return false;
8510 SDNode *Use = *Inst->use_begin();
8511 if (Use->getOpcode() != ISD::BITCAST)
8512 return false;
8513 assert(DAG && "Missing context");
8514 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8515 EVT ResVT = Use->getValueType(0);
8516 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8517 const TargetRegisterClass *ArgRC =
8518 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8519 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8520 return false;
8521
8522 // At this point, we know that we perform a cross-register-bank copy.
8523 // Check if it is expensive.
Eric Christopherd9134482014-08-04 21:25:23 +00008524 const TargetRegisterInfo *TRI =
8525 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00008526 // Assume bitcasts are cheap, unless both register classes do not
8527 // explicitly share a common sub class.
8528 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8529 return false;
8530
8531 // Check if it will be merged with the load.
8532 // 1. Check the alignment constraint.
8533 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8534 ResVT.getTypeForEVT(*DAG->getContext()));
8535
8536 if (RequiredAlignment > getAlignment())
8537 return false;
8538
8539 // 2. Check that the load is a legal operation for that type.
8540 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8541 return false;
8542
8543 // 3. Check that we do not have a zext in the way.
8544 if (Inst->getValueType(0) != getLoadedType())
8545 return false;
8546
8547 return true;
8548 }
8549};
8550}
8551
Quentin Colombetde0e0622013-10-11 18:29:42 +00008552/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8553/// \p UsedBits looks like 0..0 1..1 0..0.
8554static bool areUsedBitsDense(const APInt &UsedBits) {
8555 // If all the bits are one, this is dense!
8556 if (UsedBits.isAllOnesValue())
8557 return true;
8558
8559 // Get rid of the unused bits on the right.
8560 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8561 // Get rid of the unused bits on the left.
8562 if (NarrowedUsedBits.countLeadingZeros())
8563 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8564 // Check that the chunk of bits is completely used.
8565 return NarrowedUsedBits.isAllOnesValue();
8566}
8567
8568/// \brief Check whether or not \p First and \p Second are next to each other
8569/// in memory. This means that there is no hole between the bits loaded
8570/// by \p First and the bits loaded by \p Second.
8571static bool areSlicesNextToEachOther(const LoadedSlice &First,
8572 const LoadedSlice &Second) {
8573 assert(First.Origin == Second.Origin && First.Origin &&
8574 "Unable to match different memory origins.");
8575 APInt UsedBits = First.getUsedBits();
8576 assert((UsedBits & Second.getUsedBits()) == 0 &&
8577 "Slices are not supposed to overlap.");
8578 UsedBits |= Second.getUsedBits();
8579 return areUsedBitsDense(UsedBits);
8580}
8581
8582/// \brief Adjust the \p GlobalLSCost according to the target
8583/// paring capabilities and the layout of the slices.
8584/// \pre \p GlobalLSCost should account for at least as many loads as
8585/// there is in the slices in \p LoadedSlices.
8586static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8587 LoadedSlice::Cost &GlobalLSCost) {
8588 unsigned NumberOfSlices = LoadedSlices.size();
8589 // If there is less than 2 elements, no pairing is possible.
8590 if (NumberOfSlices < 2)
8591 return;
8592
8593 // Sort the slices so that elements that are likely to be next to each
8594 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008595 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8596 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8597 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8598 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8599 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008600 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8601 // First (resp. Second) is the first (resp. Second) potentially candidate
8602 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008603 const LoadedSlice *First = nullptr;
8604 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008605 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8606 // Set the beginning of the pair.
8607 First = Second) {
8608
8609 Second = &LoadedSlices[CurrSlice];
8610
8611 // If First is NULL, it means we start a new pair.
8612 // Get to the next slice.
8613 if (!First)
8614 continue;
8615
8616 EVT LoadedType = First->getLoadedType();
8617
8618 // If the types of the slices are different, we cannot pair them.
8619 if (LoadedType != Second->getLoadedType())
8620 continue;
8621
8622 // Check if the target supplies paired loads for this type.
8623 unsigned RequiredAlignment = 0;
8624 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8625 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008626 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008627 continue;
8628 }
8629 // Check if we meet the alignment requirement.
8630 if (RequiredAlignment > First->getAlignment())
8631 continue;
8632
8633 // Check that both loads are next to each other in memory.
8634 if (!areSlicesNextToEachOther(*First, *Second))
8635 continue;
8636
8637 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8638 --GlobalLSCost.Loads;
8639 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008640 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008641 }
8642}
8643
8644/// \brief Check the profitability of all involved LoadedSlice.
8645/// Currently, it is considered profitable if there is exactly two
8646/// involved slices (1) which are (2) next to each other in memory, and
8647/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8648///
8649/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8650/// the elements themselves.
8651///
8652/// FIXME: When the cost model will be mature enough, we can relax
8653/// constraints (1) and (2).
8654static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8655 const APInt &UsedBits, bool ForCodeSize) {
8656 unsigned NumberOfSlices = LoadedSlices.size();
8657 if (StressLoadSlicing)
8658 return NumberOfSlices > 1;
8659
8660 // Check (1).
8661 if (NumberOfSlices != 2)
8662 return false;
8663
8664 // Check (2).
8665 if (!areUsedBitsDense(UsedBits))
8666 return false;
8667
8668 // Check (3).
8669 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8670 // The original code has one big load.
8671 OrigCost.Loads = 1;
8672 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8673 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8674 // Accumulate the cost of all the slices.
8675 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8676 GlobalSlicingCost += SliceCost;
8677
8678 // Account as cost in the original configuration the gain obtained
8679 // with the current slices.
8680 OrigCost.addSliceGain(LS);
8681 }
8682
8683 // If the target supports paired load, adjust the cost accordingly.
8684 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8685 return OrigCost > GlobalSlicingCost;
8686}
8687
8688/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8689/// operations, split it in the various pieces being extracted.
8690///
8691/// This sort of thing is introduced by SROA.
8692/// This slicing takes care not to insert overlapping loads.
8693/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8694bool DAGCombiner::SliceUpLoad(SDNode *N) {
8695 if (Level < AfterLegalizeDAG)
8696 return false;
8697
8698 LoadSDNode *LD = cast<LoadSDNode>(N);
8699 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8700 !LD->getValueType(0).isInteger())
8701 return false;
8702
8703 // Keep track of already used bits to detect overlapping values.
8704 // In that case, we will just abort the transformation.
8705 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8706
8707 SmallVector<LoadedSlice, 4> LoadedSlices;
8708
8709 // Check if this load is used as several smaller chunks of bits.
8710 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8711 // of computation for each trunc.
8712 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8713 UI != UIEnd; ++UI) {
8714 // Skip the uses of the chain.
8715 if (UI.getUse().getResNo() != 0)
8716 continue;
8717
8718 SDNode *User = *UI;
8719 unsigned Shift = 0;
8720
8721 // Check if this is a trunc(lshr).
8722 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8723 isa<ConstantSDNode>(User->getOperand(1))) {
8724 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8725 User = *User->use_begin();
8726 }
8727
8728 // At this point, User is a Truncate, iff we encountered, trunc or
8729 // trunc(lshr).
8730 if (User->getOpcode() != ISD::TRUNCATE)
8731 return false;
8732
8733 // The width of the type must be a power of 2 and greater than 8-bits.
8734 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008735 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008736 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008737 unsigned Width = User->getValueSizeInBits(0);
8738 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8739 return 0;
8740
8741 // Build the slice for this chain of computations.
8742 LoadedSlice LS(User, LD, Shift, &DAG);
8743 APInt CurrentUsedBits = LS.getUsedBits();
8744
8745 // Check if this slice overlaps with another.
8746 if ((CurrentUsedBits & UsedBits) != 0)
8747 return false;
8748 // Update the bits used globally.
8749 UsedBits |= CurrentUsedBits;
8750
8751 // Check if the new slice would be legal.
8752 if (!LS.isLegal())
8753 return false;
8754
8755 // Record the slice.
8756 LoadedSlices.push_back(LS);
8757 }
8758
8759 // Abort slicing if it does not seem to be profitable.
8760 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8761 return false;
8762
8763 ++SlicedLoads;
8764
8765 // Rewrite each chain to use an independent load.
8766 // By construction, each chain can be represented by a unique load.
8767
8768 // Prepare the argument for the new token factor for all the slices.
8769 SmallVector<SDValue, 8> ArgChains;
8770 for (SmallVectorImpl<LoadedSlice>::const_iterator
8771 LSIt = LoadedSlices.begin(),
8772 LSItEnd = LoadedSlices.end();
8773 LSIt != LSItEnd; ++LSIt) {
8774 SDValue SliceInst = LSIt->loadSlice();
8775 CombineTo(LSIt->Inst, SliceInst, true);
8776 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8777 SliceInst = SliceInst.getOperand(0);
8778 assert(SliceInst->getOpcode() == ISD::LOAD &&
8779 "It takes more than a zext to get to the loaded slice!!");
8780 ArgChains.push_back(SliceInst.getValue(1));
8781 }
8782
8783 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008784 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008785 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8786 return true;
8787}
8788
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008789/// Check to see if V is (and load (ptr), imm), where the load is having
8790/// specific bytes cleared out. If so, return the byte size being masked out
8791/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00008792static std::pair<unsigned, unsigned>
8793CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8794 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008795
Chris Lattner4041ab62010-04-15 04:48:01 +00008796 // Check for the structure we're looking for.
8797 if (V->getOpcode() != ISD::AND ||
8798 !isa<ConstantSDNode>(V->getOperand(1)) ||
8799 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8800 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008801
Chris Lattner3245afd2010-04-15 06:10:49 +00008802 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008803 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008804 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008805
Chris Lattner3245afd2010-04-15 06:10:49 +00008806 // The store should be chained directly to the load or be an operand of a
8807 // tokenfactor.
8808 if (LD == Chain.getNode())
8809 ; // ok.
8810 else if (Chain->getOpcode() != ISD::TokenFactor)
8811 return Result; // Fail.
8812 else {
8813 bool isOk = false;
8814 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8815 if (Chain->getOperand(i).getNode() == LD) {
8816 isOk = true;
8817 break;
8818 }
8819 if (!isOk) return Result;
8820 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008821
Chris Lattner4041ab62010-04-15 04:48:01 +00008822 // This only handles simple types.
8823 if (V.getValueType() != MVT::i16 &&
8824 V.getValueType() != MVT::i32 &&
8825 V.getValueType() != MVT::i64)
8826 return Result;
8827
8828 // Check the constant mask. Invert it so that the bits being masked out are
8829 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8830 // follow the sign bit for uniformity.
8831 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008832 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008833 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008834 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008835 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8836 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008837
Chris Lattner4041ab62010-04-15 04:48:01 +00008838 // See if we have a continuous run of bits. If so, we have 0*1+0*
8839 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8840 return Result;
8841
8842 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8843 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8844 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008845
Chris Lattner4041ab62010-04-15 04:48:01 +00008846 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8847 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008848 case 1:
8849 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008850 case 4: break;
8851 default: return Result; // All one mask, or 5-byte mask.
8852 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008853
Chris Lattner4041ab62010-04-15 04:48:01 +00008854 // Verify that the first bit starts at a multiple of mask so that the access
8855 // is aligned the same as the access width.
8856 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008857
Chris Lattner4041ab62010-04-15 04:48:01 +00008858 Result.first = MaskedBytes;
8859 Result.second = NotMaskTZ/8;
8860 return Result;
8861}
8862
8863
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008864/// Check to see if IVal is something that provides a value as specified by
8865/// MaskInfo. If so, replace the specified store with a narrower store of
8866/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00008867static SDNode *
8868ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8869 SDValue IVal, StoreSDNode *St,
8870 DAGCombiner *DC) {
8871 unsigned NumBytes = MaskInfo.first;
8872 unsigned ByteShift = MaskInfo.second;
8873 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008874
Chris Lattner4041ab62010-04-15 04:48:01 +00008875 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8876 // that uses this. If not, this is not a replacement.
8877 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8878 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008879 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008880
Chris Lattner4041ab62010-04-15 04:48:01 +00008881 // Check that it is legal on the target to do this. It is legal if the new
8882 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8883 // legalization.
8884 MVT VT = MVT::getIntegerVT(NumBytes*8);
8885 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008886 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008887
Chris Lattner4041ab62010-04-15 04:48:01 +00008888 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8889 // shifted by ByteShift and truncated down to NumBytes.
8890 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008891 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008892 DAG.getConstant(ByteShift*8,
8893 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008894
8895 // Figure out the offset for the store and the alignment of the access.
8896 unsigned StOffset;
8897 unsigned NewAlign = St->getAlignment();
8898
8899 if (DAG.getTargetLoweringInfo().isLittleEndian())
8900 StOffset = ByteShift;
8901 else
8902 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008903
Chris Lattner4041ab62010-04-15 04:48:01 +00008904 SDValue Ptr = St->getBasePtr();
8905 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008906 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008907 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8908 NewAlign = MinAlign(NewAlign, StOffset);
8909 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008910
Chris Lattner4041ab62010-04-15 04:48:01 +00008911 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008912 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008913
Chris Lattner4041ab62010-04-15 04:48:01 +00008914 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008915 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008916 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008917 false, false, NewAlign).getNode();
8918}
8919
Evan Chenga9cda8a2009-05-28 00:35:15 +00008920
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008921/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8922/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8923/// narrowing the load and store if it would end up being a win for performance
8924/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00008925SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8926 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008927 if (ST->isVolatile())
8928 return SDValue();
8929
Evan Chenga9cda8a2009-05-28 00:35:15 +00008930 SDValue Chain = ST->getChain();
8931 SDValue Value = ST->getValue();
8932 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008933 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008934
8935 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008936 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008937
8938 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008939
Chris Lattner4041ab62010-04-15 04:48:01 +00008940 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8941 // is a byte mask indicating a consecutive number of bytes, check to see if
8942 // Y is known to provide just those bytes. If so, we try to replace the
8943 // load + replace + store sequence with a single (narrower) store, which makes
8944 // the load dead.
8945 if (Opc == ISD::OR) {
8946 std::pair<unsigned, unsigned> MaskedLoad;
8947 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8948 if (MaskedLoad.first)
8949 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8950 Value.getOperand(1), ST,this))
8951 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008952
Chris Lattner4041ab62010-04-15 04:48:01 +00008953 // Or is commutative, so try swapping X and Y.
8954 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8955 if (MaskedLoad.first)
8956 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8957 Value.getOperand(0), ST,this))
8958 return SDValue(NewST, 0);
8959 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008960
Evan Chenga9cda8a2009-05-28 00:35:15 +00008961 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8962 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008963 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008964
8965 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008966 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8967 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008968 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008969 if (LD->getBasePtr() != Ptr ||
8970 LD->getPointerInfo().getAddrSpace() !=
8971 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008972 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008973
8974 // Find the type to narrow it the load / op / store to.
8975 SDValue N1 = Value.getOperand(1);
8976 unsigned BitWidth = N1.getValueSizeInBits();
8977 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8978 if (Opc == ISD::AND)
8979 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008980 if (Imm == 0 || Imm.isAllOnesValue())
8981 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008982 unsigned ShAmt = Imm.countTrailingZeros();
8983 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8984 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008985 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008986 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008987 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008988 TLI.isNarrowingProfitable(VT, NewVT))) {
8989 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008990 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008991 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008992 if (NewBW >= BitWidth)
8993 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008994
8995 // If the lsb changed does not start at the type bitwidth boundary,
8996 // start at the previous one.
8997 if (ShAmt % NewBW)
8998 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008999 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9000 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009001 if ((Imm & Mask) == Imm) {
9002 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9003 if (Opc == ISD::AND)
9004 NewImm ^= APInt::getAllOnesValue(NewBW);
9005 uint64_t PtrOff = ShAmt / 8;
9006 // For big endian targets, we need to adjust the offset to the pointer to
9007 // load the correct bytes.
9008 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00009009 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00009010
9011 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00009012 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009013 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00009014 return SDValue();
9015
Andrew Trickef9de2a2013-05-25 02:42:55 +00009016 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009017 Ptr.getValueType(), Ptr,
9018 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009019 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009020 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009021 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009022 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009023 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009024 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009025 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00009026 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009027 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009028 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009029 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009030 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009031
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009032 AddToWorklist(NewPtr.getNode());
9033 AddToWorklist(NewLD.getNode());
9034 AddToWorklist(NewVal.getNode());
9035 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009036 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009037 ++OpsNarrowed;
9038 return NewST;
9039 }
9040 }
9041
Evan Cheng6673ff02009-05-28 18:41:02 +00009042 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009043}
9044
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009045/// For a given floating point load / store pair, if the load value isn't used
9046/// by any other operations, then consider transforming the pair to integer
9047/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00009048SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9049 StoreSDNode *ST = cast<StoreSDNode>(N);
9050 SDValue Chain = ST->getChain();
9051 SDValue Value = ST->getValue();
9052 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9053 Value.hasOneUse() &&
9054 Chain == SDValue(Value.getNode(), 1)) {
9055 LoadSDNode *LD = cast<LoadSDNode>(Value);
9056 EVT VT = LD->getMemoryVT();
9057 if (!VT.isFloatingPoint() ||
9058 VT != ST->getMemoryVT() ||
9059 LD->isNonTemporal() ||
9060 ST->isNonTemporal() ||
9061 LD->getPointerInfo().getAddrSpace() != 0 ||
9062 ST->getPointerInfo().getAddrSpace() != 0)
9063 return SDValue();
9064
9065 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9066 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9067 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9068 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9069 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9070 return SDValue();
9071
9072 unsigned LDAlign = LD->getAlignment();
9073 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009074 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009075 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009076 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9077 return SDValue();
9078
Andrew Trickef9de2a2013-05-25 02:42:55 +00009079 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009080 LD->getChain(), LD->getBasePtr(),
9081 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009082 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009083
Andrew Trickef9de2a2013-05-25 02:42:55 +00009084 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009085 NewLD, ST->getBasePtr(),
9086 ST->getPointerInfo(),
9087 false, false, STAlign);
9088
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009089 AddToWorklist(NewLD.getNode());
9090 AddToWorklist(NewST.getNode());
9091 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009092 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009093 ++LdStFP2Int;
9094 return NewST;
9095 }
9096
9097 return SDValue();
9098}
9099
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009100/// Helper struct to parse and store a memory address as base + index + offset.
9101/// We ignore sign extensions when it is safe to do so.
9102/// The following two expressions are not equivalent. To differentiate we need
9103/// to store whether there was a sign extension involved in the index
9104/// computation.
9105/// (load (i64 add (i64 copyfromreg %c)
9106/// (i64 signextend (add (i8 load %index)
9107/// (i8 1))))
9108/// vs
9109///
9110/// (load (i64 add (i64 copyfromreg %c)
9111/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9112/// (i32 1)))))
9113struct BaseIndexOffset {
9114 SDValue Base;
9115 SDValue Index;
9116 int64_t Offset;
9117 bool IsIndexSignExt;
9118
9119 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9120
9121 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9122 bool IsIndexSignExt) :
9123 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9124
9125 bool equalBaseIndex(const BaseIndexOffset &Other) {
9126 return Other.Base == Base && Other.Index == Index &&
9127 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009128 }
9129
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009130 /// Parses tree in Ptr for base, index, offset addresses.
9131 static BaseIndexOffset match(SDValue Ptr) {
9132 bool IsIndexSignExt = false;
9133
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009134 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9135 // instruction, then it could be just the BASE or everything else we don't
9136 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009137 if (Ptr->getOpcode() != ISD::ADD)
9138 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9139
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009140 // We know that we have at least an ADD instruction. Try to pattern match
9141 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009142 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9143 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9144 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9145 IsIndexSignExt);
9146 }
9147
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009148 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009149 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009150 // (i64 add (i64 %array_ptr)
9151 // (i64 mul (i64 %induction_var)
9152 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009153 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009154 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009155
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009156 // Look at Base + Index + Offset cases.
9157 SDValue Base = Ptr->getOperand(0);
9158 SDValue IndexOffset = Ptr->getOperand(1);
9159
9160 // Skip signextends.
9161 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9162 IndexOffset = IndexOffset->getOperand(0);
9163 IsIndexSignExt = true;
9164 }
9165
9166 // Either the case of Base + Index (no offset) or something else.
9167 if (IndexOffset->getOpcode() != ISD::ADD)
9168 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9169
9170 // Now we have the case of Base + Index + offset.
9171 SDValue Index = IndexOffset->getOperand(0);
9172 SDValue Offset = IndexOffset->getOperand(1);
9173
9174 if (!isa<ConstantSDNode>(Offset))
9175 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9176
9177 // Ignore signextends.
9178 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9179 Index = Index->getOperand(0);
9180 IsIndexSignExt = true;
9181 } else IsIndexSignExt = false;
9182
9183 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9184 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9185 }
9186};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009187
9188/// Holds a pointer to an LSBaseSDNode as well as information on where it
9189/// is located in a sequence of memory operations connected by a chain.
9190struct MemOpLink {
9191 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9192 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9193 // Ptr to the mem node.
9194 LSBaseSDNode *MemNode;
9195 // Offset from the base ptr.
9196 int64_t OffsetFromBase;
9197 // What is the sequence number of this mem node.
9198 // Lowest mem operand in the DAG starts at zero.
9199 unsigned SequenceNum;
9200};
9201
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009202bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9203 EVT MemVT = St->getMemoryVT();
9204 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009205 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9206 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009207
9208 // Don't merge vectors into wider inputs.
9209 if (MemVT.isVector() || !MemVT.isSimple())
9210 return false;
9211
9212 // Perform an early exit check. Do not bother looking at stored values that
9213 // are not constants or loads.
9214 SDValue StoredVal = St->getValue();
9215 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9216 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9217 !IsLoadSrc)
9218 return false;
9219
9220 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +00009221 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009222 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9223 return false;
9224
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009225 // This holds the base pointer, index, and the offset in bytes from the base
9226 // pointer.
9227 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009228
9229 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009230 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009231 return false;
9232
9233 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009234 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009235 return false;
9236
Nadav Rotem307d7672012-11-29 00:00:08 +00009237 // Save the LoadSDNodes that we find in the chain.
9238 // We need to make sure that these nodes do not interfere with
9239 // any of the store nodes.
9240 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9241
9242 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009243 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009244
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009245 // Walk up the chain and look for nodes with offsets from the same
9246 // base pointer. Stop when reaching an instruction with a different kind
9247 // or instruction which has a different base pointer.
9248 unsigned Seq = 0;
9249 StoreSDNode *Index = St;
9250 while (Index) {
9251 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +00009252 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009253 break;
9254
9255 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009256 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009257
9258 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009259 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009260 break;
9261
9262 // Check that the alignment is the same.
9263 if (Index->getAlignment() != St->getAlignment())
9264 break;
9265
9266 // The memory operands must not be volatile.
9267 if (Index->isVolatile() || Index->isIndexed())
9268 break;
9269
9270 // No truncation.
9271 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9272 if (St->isTruncatingStore())
9273 break;
9274
9275 // The stored memory type must be the same.
9276 if (Index->getMemoryVT() != MemVT)
9277 break;
9278
9279 // We do not allow unaligned stores because we want to prevent overriding
9280 // stores.
9281 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9282 break;
9283
9284 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009285 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009286
Nadav Rotem307d7672012-11-29 00:00:08 +00009287 // Find the next memory operand in the chain. If the next operand in the
9288 // chain is a store then move up and continue the scan with the next
9289 // memory operand. If the next operand is a load save it and use alias
9290 // information to check if it interferes with anything.
9291 SDNode *NextInChain = Index->getChain().getNode();
9292 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009293 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009294 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009295 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009296 break;
9297 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009298 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009299 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009300 break;
9301 }
9302
Nadav Rotem307d7672012-11-29 00:00:08 +00009303 // Save the load node for later. Continue the scan.
9304 AliasLoadNodes.push_back(Ldn);
9305 NextInChain = Ldn->getChain().getNode();
9306 continue;
9307 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009308 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009309 break;
9310 }
9311 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009312 }
9313
9314 // Check if there is anything to merge.
9315 if (StoreNodes.size() < 2)
9316 return false;
9317
9318 // Sort the memory operands according to their distance from the base pointer.
9319 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009320 [](MemOpLink LHS, MemOpLink RHS) {
9321 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9322 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9323 LHS.SequenceNum > RHS.SequenceNum);
9324 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009325
9326 // Scan the memory operations on the chain and find the first non-consecutive
9327 // store memory address.
9328 unsigned LastConsecutiveStore = 0;
9329 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009330 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9331
9332 // Check that the addresses are consecutive starting from the second
9333 // element in the list of stores.
9334 if (i > 0) {
9335 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9336 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9337 break;
9338 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009339
Nadav Rotem307d7672012-11-29 00:00:08 +00009340 bool Alias = false;
9341 // Check if this store interferes with any of the loads that we found.
9342 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9343 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9344 Alias = true;
9345 break;
9346 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009347 // We found a load that alias with this store. Stop the sequence.
9348 if (Alias)
9349 break;
9350
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009351 // Mark this node as useful.
9352 LastConsecutiveStore = i;
9353 }
9354
9355 // The node with the lowest store address.
9356 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9357
9358 // Store the constants into memory as one consecutive store.
9359 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009360 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009361 unsigned LastLegalVectorType = 0;
9362 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009363 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9364 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9365 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009366
9367 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009368 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009369 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009370 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009371 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009372 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009373 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009374 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009375
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009376 // Find a legal type for the constant store.
9377 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9378 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9379 if (TLI.isTypeLegal(StoreTy))
9380 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009381 // Or check whether a truncstore is legal.
9382 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9383 TargetLowering::TypePromoteInteger) {
9384 EVT LegalizedStoredValueTy =
9385 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9386 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9387 LastLegalType = i+1;
9388 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009389
9390 // Find a legal type for the vector store.
9391 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9392 if (TLI.isTypeLegal(Ty))
9393 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009394 }
9395
Bob Wilson3365b802012-12-20 01:36:20 +00009396 // We only use vectors if the constant is known to be zero and the
9397 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009398 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009399 LastLegalVectorType = 0;
9400
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009401 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009402 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009403 return false;
9404
Nadav Rotem495b1a42013-02-14 18:28:52 +00009405 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009406 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9407
9408 // Make sure we have something to merge.
9409 if (NumElem < 2)
9410 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009411
9412 unsigned EarliestNodeUsed = 0;
9413 for (unsigned i=0; i < NumElem; ++i) {
9414 // Find a chain for the new wide-store operand. Notice that some
9415 // of the store nodes that we found may not be selected for inclusion
9416 // in the wide store. The chain we use needs to be the chain of the
9417 // earliest store node which is *used* and replaced by the wide store.
9418 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9419 EarliestNodeUsed = i;
9420 }
9421
9422 // The earliest Node in the DAG.
9423 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009424 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009425
Nadav Rotemb27777f2012-10-04 22:35:15 +00009426 SDValue StoredVal;
9427 if (UseVector) {
9428 // Find a legal type for the vector store.
9429 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9430 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9431 StoredVal = DAG.getConstant(0, Ty);
9432 } else {
9433 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9434 APInt StoreInt(StoreBW, 0);
9435
9436 // Construct a single integer constant which is made of the smaller
9437 // constant inputs.
9438 bool IsLE = TLI.isLittleEndian();
9439 for (unsigned i = 0; i < NumElem ; ++i) {
9440 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9441 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9442 SDValue Val = St->getValue();
9443 StoreInt<<=ElementSizeBytes*8;
9444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9445 StoreInt|=C->getAPIntValue().zext(StoreBW);
9446 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9447 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9448 } else {
9449 assert(false && "Invalid constant element type");
9450 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009451 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009452
9453 // Create the new Load and Store operations.
9454 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9455 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009456 }
9457
Nadav Rotemb27777f2012-10-04 22:35:15 +00009458 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009459 FirstInChain->getBasePtr(),
9460 FirstInChain->getPointerInfo(),
9461 false, false,
9462 FirstInChain->getAlignment());
9463
9464 // Replace the first store with the new store
9465 CombineTo(EarliestOp, NewStore);
9466 // Erase all other stores.
9467 for (unsigned i = 0; i < NumElem ; ++i) {
9468 if (StoreNodes[i].MemNode == EarliestOp)
9469 continue;
9470 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009471 // ReplaceAllUsesWith will replace all uses that existed when it was
9472 // called, but graph optimizations may cause new ones to appear. For
9473 // example, the case in pr14333 looks like
9474 //
9475 // St's chain -> St -> another store -> X
9476 //
9477 // And the only difference from St to the other store is the chain.
9478 // When we change it's chain to be St's chain they become identical,
9479 // get CSEed and the net result is that X is now a use of St.
9480 // Since we know that St is redundant, just iterate.
9481 while (!St->use_empty())
9482 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009483 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009484 }
9485
9486 return true;
9487 }
9488
9489 // Below we handle the case of multiple consecutive stores that
9490 // come from multiple consecutive loads. We merge them into a single
9491 // wide load and a single wide store.
9492
9493 // Look for load nodes which are used by the stored values.
9494 SmallVector<MemOpLink, 8> LoadNodes;
9495
9496 // Find acceptable loads. Loads need to have the same chain (token factor),
9497 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009498 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009499 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9500 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9501 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9502 if (!Ld) break;
9503
9504 // Loads must only have one use.
9505 if (!Ld->hasNUsesOfValue(1, 0))
9506 break;
9507
9508 // Check that the alignment is the same as the stores.
9509 if (Ld->getAlignment() != St->getAlignment())
9510 break;
9511
9512 // The memory operands must not be volatile.
9513 if (Ld->isVolatile() || Ld->isIndexed())
9514 break;
9515
9516 // We do not accept ext loads.
9517 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9518 break;
9519
9520 // The stored memory type must be the same.
9521 if (Ld->getMemoryVT() != MemVT)
9522 break;
9523
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009524 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009525 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009526 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009527 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009528 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009529 break;
9530 } else {
9531 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009532 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009533 }
9534
9535 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009536 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009537 }
9538
9539 if (LoadNodes.size() < 2)
9540 return false;
9541
James Molloyce45be02014-08-02 14:51:24 +00009542 // If we have load/store pair instructions and we only have two values,
9543 // don't bother.
9544 unsigned RequiredAlignment;
9545 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9546 St->getAlignment() >= RequiredAlignment)
9547 return false;
9548
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009549 // Scan the memory operations on the chain and find the first non-consecutive
9550 // load memory address. These variables hold the index in the store node
9551 // array.
9552 unsigned LastConsecutiveLoad = 0;
9553 // This variable refers to the size and not index in the array.
9554 unsigned LastLegalVectorType = 0;
9555 unsigned LastLegalIntegerType = 0;
9556 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009557 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9558 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9559 // All loads much share the same chain.
9560 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9561 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009562
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009563 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9564 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9565 break;
9566 LastConsecutiveLoad = i;
9567
9568 // Find a legal type for the vector store.
9569 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9570 if (TLI.isTypeLegal(StoreTy))
9571 LastLegalVectorType = i + 1;
9572
9573 // Find a legal type for the integer store.
9574 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9575 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9576 if (TLI.isTypeLegal(StoreTy))
9577 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009578 // Or check whether a truncstore and extload is legal.
9579 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9580 TargetLowering::TypePromoteInteger) {
9581 EVT LegalizedStoredValueTy =
9582 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9583 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9584 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9585 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9586 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9587 LastLegalIntegerType = i+1;
9588 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009589 }
9590
9591 // Only use vector types if the vector type is larger than the integer type.
9592 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009593 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009594 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9595
9596 // We add +1 here because the LastXXX variables refer to location while
9597 // the NumElem refers to array/index size.
9598 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9599 NumElem = std::min(LastLegalType, NumElem);
9600
9601 if (NumElem < 2)
9602 return false;
9603
9604 // The earliest Node in the DAG.
9605 unsigned EarliestNodeUsed = 0;
9606 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9607 for (unsigned i=1; i<NumElem; ++i) {
9608 // Find a chain for the new wide-store operand. Notice that some
9609 // of the store nodes that we found may not be selected for inclusion
9610 // in the wide store. The chain we use needs to be the chain of the
9611 // earliest store node which is *used* and replaced by the wide store.
9612 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9613 EarliestNodeUsed = i;
9614 }
9615
9616 // Find if it is better to use vectors or integers to load and store
9617 // to memory.
9618 EVT JointMemOpVT;
9619 if (UseVectorTy) {
9620 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9621 } else {
9622 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9623 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9624 }
9625
Andrew Trickef9de2a2013-05-25 02:42:55 +00009626 SDLoc LoadDL(LoadNodes[0].MemNode);
9627 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009628
9629 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9630 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9631 FirstLoad->getChain(),
9632 FirstLoad->getBasePtr(),
9633 FirstLoad->getPointerInfo(),
9634 false, false, false,
9635 FirstLoad->getAlignment());
9636
9637 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9638 FirstInChain->getBasePtr(),
9639 FirstInChain->getPointerInfo(), false, false,
9640 FirstInChain->getAlignment());
9641
Nadav Rotemac920662012-10-03 19:30:31 +00009642 // Replace one of the loads with the new load.
9643 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9644 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9645 SDValue(NewLoad.getNode(), 1));
9646
9647 // Remove the rest of the load chains.
9648 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009649 // Replace all chain users of the old load nodes with the chain of the new
9650 // load node.
9651 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009652 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9653 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009654
Nadav Rotemac920662012-10-03 19:30:31 +00009655 // Replace the first store with the new store.
9656 CombineTo(EarliestOp, NewStore);
9657 // Erase all other stores.
9658 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009659 // Remove all Store nodes.
9660 if (StoreNodes[i].MemNode == EarliestOp)
9661 continue;
9662 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9663 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009664 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009665 }
9666
9667 return true;
9668}
9669
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009670SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009671 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009672 SDValue Chain = ST->getChain();
9673 SDValue Value = ST->getValue();
9674 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009675
Evan Chenga4cf58a2007-05-07 21:27:48 +00009676 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009677 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009678 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009679 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009680 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009681 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009682 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009683 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009684 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009685 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009686 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009687 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009688 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009689 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009690 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009691 }
Owen Andersona5192842011-04-14 17:30:49 +00009692
Chris Lattner41c80e82011-04-09 02:32:02 +00009693 // Turn 'store undef, Ptr' -> nothing.
9694 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9695 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009696
Nate Begeman8e20c762006-12-11 02:23:46 +00009697 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009698 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009699 // NOTE: If the original store is volatile, this transform must not increase
9700 // the number of stores. For example, on x86-32 an f64 can be stored in one
9701 // processor operation but an i64 (which is not legal) requires two. So the
9702 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009703 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009704 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009705 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009706 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009707 case MVT::f16: // We don't do this for these yet.
9708 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009709 case MVT::f128:
9710 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009711 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009712 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009713 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009714 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009715 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009716 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009717 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009718 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009719 }
9720 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009721 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009722 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009723 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009724 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009725 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009726 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009727 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009728 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009729 }
Owen Andersona5192842011-04-14 17:30:49 +00009730
Chris Lattner41c80e82011-04-09 02:32:02 +00009731 if (!ST->isVolatile() &&
9732 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009733 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009734 // argument passing. Since this is so common, custom legalize the
9735 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009736 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009737 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9738 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009739 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009740
Dan Gohman2af30632007-07-09 22:18:38 +00009741 unsigned Alignment = ST->getAlignment();
9742 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009743 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +00009744 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009745
Andrew Trickef9de2a2013-05-25 02:42:55 +00009746 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009747 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009748 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009749 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009750 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009751 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009752 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009753 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009754 Ptr, ST->getPointerInfo().getWithOffset(4),
9755 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009756 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009757 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009758 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009759 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009760
Chris Lattnerb7524b62006-12-12 04:16:14 +00009761 break;
Evan Cheng21836982006-12-11 17:25:19 +00009762 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009763 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009764 }
9765
Evan Cheng43cd9e32010-04-01 06:04:33 +00009766 // Try to infer better alignment information than the store already has.
9767 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009768 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9769 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009770 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009771 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009772 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +00009773 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009774 }
9775 }
9776
Evan Chengd42641c2011-02-02 01:06:55 +00009777 // Try transforming a pair floating point load / store ops to integer
9778 // load / store ops.
9779 SDValue NewST = TransformFPLoadStorePair(N);
9780 if (NewST.getNode())
9781 return NewST;
9782
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009783 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9784 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009785#ifndef NDEBUG
9786 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9787 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9788 UseAA = false;
9789#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009790 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009791 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009792 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009793
Jim Laskey708d0db2006-10-04 16:53:27 +00009794 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009795 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009796 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009797
9798 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009799 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009800 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009801 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009802 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009803 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009804 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009805 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009806
Jim Laskeyd07be232006-09-25 16:29:54 +00009807 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009808 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009809 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009810
Nate Begeman879d8f12009-09-15 00:18:30 +00009811 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009812 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +00009813
Jim Laskeydcf983c2006-10-13 23:32:28 +00009814 // Don't add users to work list.
9815 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009816 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009817 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009818
Evan Cheng33157702006-11-05 09:31:14 +00009819 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009820 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009821 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009822
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009823 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009824 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009825 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009826 // See if we can simplify the input to this truncstore with knowledge that
9827 // only the low bits are being used. For example:
9828 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009829 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009830 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009831 APInt::getLowBitsSet(
9832 Value.getValueType().getScalarType().getSizeInBits(),
9833 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009834 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00009835 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009836 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009837 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009838
Chris Lattnerf47e3062007-10-13 06:58:48 +00009839 // Otherwise, see if we can simplify the operation with
9840 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009841 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009842 APInt::getLowBitsSet(
9843 Value.getValueType().getScalarType().getSizeInBits(),
9844 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009845 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009846 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009847
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009848 // If this is a load followed by a store to the same location, then the store
9849 // is dead/noop.
9850 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009851 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009852 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009853 // There can't be any side effects between the load and store, such as
9854 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009855 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009856 // The store is dead, remove it.
9857 return Chain;
9858 }
9859 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009860
James Molloy463db9a2014-09-27 17:02:54 +00009861 // If this is a store followed by a store with the same value to the same
9862 // location, then the store is dead/noop.
9863 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9864 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9865 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9866 ST1->isUnindexed() && !ST1->isVolatile()) {
9867 // The store is dead, remove it.
9868 return Chain;
9869 }
9870 }
9871
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009872 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9873 // truncating store. We can do this even if this is already a truncstore.
9874 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009875 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009876 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009877 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009878 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009879 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009880 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009881
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009882 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009883 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009884 if (!LegalTypes) {
9885 bool EverChanged = false;
9886
9887 do {
9888 // There can be multiple store sequences on the same chain.
9889 // Keep trying to merge store sequences until we are unable to do so
9890 // or until we merge the last store on the chain.
9891 bool Changed = MergeConsecutiveStores(ST);
9892 EverChanged |= Changed;
9893 if (!Changed) break;
9894 } while (ST->getOpcode() != ISD::DELETED_NODE);
9895
9896 if (EverChanged)
9897 return SDValue(N, 0);
9898 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009899
Evan Chenga9cda8a2009-05-28 00:35:15 +00009900 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009901}
9902
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009903SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9904 SDValue InVec = N->getOperand(0);
9905 SDValue InVal = N->getOperand(1);
9906 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009907 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009908
Bob Wilson42603952010-05-19 23:42:58 +00009909 // If the inserted element is an UNDEF, just use the input vector.
9910 if (InVal.getOpcode() == ISD::UNDEF)
9911 return InVec;
9912
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009913 EVT VT = InVec.getValueType();
9914
Owen Andersonb2c80da2011-02-25 21:41:48 +00009915 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009916 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9917 return SDValue();
9918
Eli Friedmanb7910b72011-09-09 21:04:06 +00009919 // Check that we know which element is being inserted
9920 if (!isa<ConstantSDNode>(EltNo))
9921 return SDValue();
9922 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009923
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009924 // Canonicalize insert_vector_elt dag nodes.
9925 // Example:
9926 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9927 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9928 //
9929 // Do this only if the child insert_vector node has one use; also
9930 // do this only if indices are both constants and Idx1 < Idx0.
9931 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9932 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9933 unsigned OtherElt =
9934 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9935 if (Elt < OtherElt) {
9936 // Swap nodes.
9937 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9938 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009939 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009940 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9941 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9942 }
9943 }
9944
Eli Friedmanb7910b72011-09-09 21:04:06 +00009945 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9946 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9947 // vector elements.
9948 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009949 // Do not combine these two vectors if the output vector will not replace
9950 // the input vector.
9951 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009952 Ops.append(InVec.getNode()->op_begin(),
9953 InVec.getNode()->op_end());
9954 } else if (InVec.getOpcode() == ISD::UNDEF) {
9955 unsigned NElts = VT.getVectorNumElements();
9956 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9957 } else {
9958 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009959 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009960
9961 // Insert the element
9962 if (Elt < Ops.size()) {
9963 // All the operands of BUILD_VECTOR must have the same type;
9964 // we enforce that here.
9965 EVT OpVT = Ops[0].getValueType();
9966 if (InVal.getValueType() != OpVT)
9967 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9968 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9969 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9970 Ops[Elt] = InVal;
9971 }
9972
9973 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009974 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009975}
9976
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +00009977SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9978 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9979 EVT ResultVT = EVE->getValueType(0);
9980 EVT VecEltVT = InVecVT.getVectorElementType();
9981 unsigned Align = OriginalLoad->getAlignment();
9982 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9983 VecEltVT.getTypeForEVT(*DAG.getContext()));
9984
9985 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9986 return SDValue();
9987
9988 Align = NewAlign;
9989
9990 SDValue NewPtr = OriginalLoad->getBasePtr();
9991 SDValue Offset;
9992 EVT PtrType = NewPtr.getValueType();
9993 MachinePointerInfo MPI;
9994 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9995 int Elt = ConstEltNo->getZExtValue();
9996 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9997 if (TLI.isBigEndian())
9998 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9999 Offset = DAG.getConstant(PtrOff, PtrType);
10000 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10001 } else {
10002 Offset = DAG.getNode(
10003 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10004 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10005 if (TLI.isBigEndian())
10006 Offset = DAG.getNode(
10007 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10008 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10009 MPI = OriginalLoad->getPointerInfo();
10010 }
10011 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10012
10013 // The replacement we need to do here is a little tricky: we need to
10014 // replace an extractelement of a load with a load.
10015 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10016 // Note that this replacement assumes that the extractvalue is the only
10017 // use of the load; that's okay because we don't want to perform this
10018 // transformation in other cases anyway.
10019 SDValue Load;
10020 SDValue Chain;
10021 if (ResultVT.bitsGT(VecEltVT)) {
10022 // If the result type of vextract is wider than the load, then issue an
10023 // extending load instead.
10024 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10025 ? ISD::ZEXTLOAD
10026 : ISD::EXTLOAD;
10027 Load = DAG.getExtLoad(
10028 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10029 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10030 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10031 Chain = Load.getValue(1);
10032 } else {
10033 Load = DAG.getLoad(
10034 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10035 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10036 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10037 Chain = Load.getValue(1);
10038 if (ResultVT.bitsLT(VecEltVT))
10039 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10040 else
10041 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10042 }
10043 WorklistRemover DeadNodes(*this);
10044 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10045 SDValue To[] = { Load, Chain };
10046 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10047 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10048 // worklist explicitly as well.
10049 AddToWorklist(Load.getNode());
10050 AddUsersToWorklist(Load.getNode()); // Add users too
10051 // Make sure to revisit this node to clean it up; it will usually be dead.
10052 AddToWorklist(EVE);
10053 ++OpsNarrowed;
10054 return SDValue(EVE, 0);
10055}
10056
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010057SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000010058 // (vextract (scalar_to_vector val, 0) -> val
10059 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010060 EVT VT = InVec.getValueType();
10061 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010062
Duncan Sands6be291a2011-05-09 08:03:33 +000010063 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10064 // Check if the result type doesn't match the inserted element type. A
10065 // SCALAR_TO_VECTOR may truncate the inserted element and the
10066 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10067 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010068 if (InOp.getValueType() != NVT) {
10069 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010070 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010071 }
10072 return InOp;
10073 }
Evan Cheng1120279a2008-05-13 08:35:03 +000010074
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010075 SDValue EltNo = N->getOperand(1);
10076 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10077
10078 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10079 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000010080 // we may introduce new vector instructions which are not backed by TD
10081 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000010082 // without using extract_subvector. However, if we can find an underlying
10083 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010084 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000010085 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010086 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10087 int NumElem = VT.getVectorNumElements();
10088 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10089 // Find the new index to extract from.
10090 int OrigElt = SVOp->getMaskElt(Elt);
10091
10092 // Extracting an undef index is undef.
10093 if (OrigElt == -1)
10094 return DAG.getUNDEF(NVT);
10095
10096 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000010097 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010098 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000010099 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010100 } else {
Hal Finkel02807592014-03-31 11:43:19 +000010101 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010102 OrigElt -= NumElem;
10103 }
10104
Hal Finkel02807592014-03-31 11:43:19 +000010105 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10106 SDValue InOp = SVInVec.getOperand(OrigElt);
10107 if (InOp.getValueType() != NVT) {
10108 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10109 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10110 }
10111
10112 return InOp;
10113 }
10114
10115 // FIXME: We should handle recursing on other vector shuffles and
10116 // scalar_to_vector here as well.
10117
10118 if (!LegalOperations) {
10119 EVT IndexTy = TLI.getVectorIdxTy();
10120 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10121 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10122 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010123 }
10124
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010125 bool BCNumEltsChanged = false;
10126 EVT ExtVT = VT.getVectorElementType();
10127 EVT LVT = ExtVT;
10128
10129 // If the result of load has to be truncated, then it's not necessarily
10130 // profitable.
10131 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10132 return SDValue();
10133
10134 if (InVec.getOpcode() == ISD::BITCAST) {
10135 // Don't duplicate a load with other uses.
10136 if (!InVec.hasOneUse())
10137 return SDValue();
10138
10139 EVT BCVT = InVec.getOperand(0).getValueType();
10140 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10141 return SDValue();
10142 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10143 BCNumEltsChanged = true;
10144 InVec = InVec.getOperand(0);
10145 ExtVT = BCVT.getVectorElementType();
10146 }
10147
10148 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10149 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10150 ISD::isNormalLoad(InVec.getNode()) &&
10151 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10152 SDValue Index = N->getOperand(1);
10153 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10154 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10155 OrigLoad);
10156 }
10157
Evan Cheng1120279a2008-05-13 08:35:03 +000010158 // Perform only after legalization to ensure build_vector / vector_shuffle
10159 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010160 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010161
Mon P Wangca6d6de2009-01-17 00:07:25 +000010162 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10163 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10164 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000010165
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010166 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000010167 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010168
Craig Topperc0196b12014-04-14 00:51:57 +000010169 LoadSDNode *LN0 = nullptr;
10170 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000010171 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010172 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010173 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000010174 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000010175 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000010176 // Don't duplicate a load with other uses.
10177 if (!InVec.hasOneUse())
10178 return SDValue();
10179
Evan Cheng1120279a2008-05-13 08:35:03 +000010180 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000010181 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010182 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10183 // =>
10184 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000010185
Eli Friedmane96286c2011-12-26 22:49:32 +000010186 // Don't duplicate a load with other uses.
10187 if (!InVec.hasOneUse())
10188 return SDValue();
10189
Mon P Wangb5eb7202008-12-11 00:26:16 +000010190 // If the bit convert changed the number of elements, it is unsafe
10191 // to examine the mask.
10192 if (BCNumEltsChanged)
10193 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010194
10195 // Select the input vector, guarding against out of range extract vector.
10196 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010197 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010198 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10199
Eli Friedmane96286c2011-12-26 22:49:32 +000010200 if (InVec.getOpcode() == ISD::BITCAST) {
10201 // Don't duplicate a load with other uses.
10202 if (!InVec.hasOneUse())
10203 return SDValue();
10204
Evan Cheng1120279a2008-05-13 08:35:03 +000010205 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010206 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010207 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010208 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010209 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010210 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010211 }
10212 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010213
Eli Friedmane96286c2011-12-26 22:49:32 +000010214 // Make sure we found a non-volatile load and the extractelement is
10215 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010216 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010217 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010218
Eric Christopherc6418b12010-11-03 20:44:42 +000010219 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10220 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010221 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010222
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010223 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010224 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010225
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010226 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010227}
Evan Cheng0de312d2007-10-06 08:19:55 +000010228
Michael Liao6d106b72012-10-23 23:06:52 +000010229// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10230SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10231 // We perform this optimization post type-legalization because
10232 // the type-legalizer often scalarizes integer-promoted vectors.
10233 // Performing this optimization before may create bit-casts which
10234 // will be type-legalized to complex code sequences.
10235 // We perform this optimization only before the operation legalizer because we
10236 // may introduce illegal operations.
10237 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10238 return SDValue();
10239
Dan Gohmana8665142007-06-25 16:23:39 +000010240 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010241 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010242 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010243
Nadav Rotembf6568b2011-10-29 21:23:04 +000010244 // Check to see if this is a BUILD_VECTOR of a bunch of values
10245 // which come from any_extend or zero_extend nodes. If so, we can create
10246 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010247 // optimizations. We do not handle sign-extend because we can't fill the sign
10248 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010249 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010250 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010251
Craig Topper02cb0fb2012-01-17 09:09:48 +000010252 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010253 SDValue In = N->getOperand(i);
10254 // Ignore undef inputs.
10255 if (In.getOpcode() == ISD::UNDEF) continue;
10256
10257 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10258 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10259
Nadav Rotemf3103612011-10-31 20:08:25 +000010260 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010261 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010262 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010263 break;
10264 }
10265
10266 // The input is a ZeroExt or AnyExt. Check the original type.
10267 EVT InTy = In.getOperand(0).getValueType();
10268
10269 // Check that all of the widened source types are the same.
10270 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010271 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010272 SourceType = InTy;
10273 else if (InTy != SourceType) {
10274 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010275 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010276 break;
10277 }
10278
10279 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010280 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010281 }
10282
Nadav Rotemf3103612011-10-31 20:08:25 +000010283 // In order to have valid types, all of the inputs must be extended from the
10284 // same source type and all of the inputs must be any or zero extend.
10285 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010286 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010287 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010288 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10289 isPowerOf2_32(SourceType.getSizeInBits());
10290
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010291 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10292 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010293 if (!ValidTypes)
10294 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010295
Michael Liao6d106b72012-10-23 23:06:52 +000010296 bool isLE = TLI.isLittleEndian();
10297 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10298 assert(ElemRatio > 1 && "Invalid element size ratio");
10299 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10300 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010301
Michael Liao6d106b72012-10-23 23:06:52 +000010302 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10303 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010304
Michael Liao6d106b72012-10-23 23:06:52 +000010305 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010306 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010307 SDValue Cast = N->getOperand(i);
10308 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10309 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10310 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10311 SDValue In;
10312 if (Cast.getOpcode() == ISD::UNDEF)
10313 In = DAG.getUNDEF(SourceType);
10314 else
10315 In = Cast->getOperand(0);
10316 unsigned Index = isLE ? (i * ElemRatio) :
10317 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010318
Michael Liao6d106b72012-10-23 23:06:52 +000010319 assert(Index < Ops.size() && "Invalid index");
10320 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010321 }
Chris Lattner5336a592006-03-19 01:27:56 +000010322
Michael Liao6d106b72012-10-23 23:06:52 +000010323 // The type of the new BUILD_VECTOR node.
10324 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10325 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10326 "Invalid vector size");
10327 // Check if the new vector type is legal.
10328 if (!isTypeLegal(VecVT)) return SDValue();
10329
10330 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010331 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010332
10333 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010334 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010335 // Bitcast to the desired type.
10336 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10337}
10338
Michael Liao59229792012-10-24 04:14:18 +000010339SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10340 EVT VT = N->getValueType(0);
10341
10342 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010343 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010344
10345 EVT SrcVT = MVT::Other;
10346 unsigned Opcode = ISD::DELETED_NODE;
10347 unsigned NumDefs = 0;
10348
10349 for (unsigned i = 0; i != NumInScalars; ++i) {
10350 SDValue In = N->getOperand(i);
10351 unsigned Opc = In.getOpcode();
10352
10353 if (Opc == ISD::UNDEF)
10354 continue;
10355
10356 // If all scalar values are floats and converted from integers.
10357 if (Opcode == ISD::DELETED_NODE &&
10358 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10359 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010360 }
Tom Stellard567f8862013-01-02 22:13:01 +000010361
Michael Liao59229792012-10-24 04:14:18 +000010362 if (Opc != Opcode)
10363 return SDValue();
10364
10365 EVT InVT = In.getOperand(0).getValueType();
10366
10367 // If all scalar values are typed differently, bail out. It's chosen to
10368 // simplify BUILD_VECTOR of integer types.
10369 if (SrcVT == MVT::Other)
10370 SrcVT = InVT;
10371 if (SrcVT != InVT)
10372 return SDValue();
10373 NumDefs++;
10374 }
10375
10376 // If the vector has just one element defined, it's not worth to fold it into
10377 // a vectorized one.
10378 if (NumDefs < 2)
10379 return SDValue();
10380
10381 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10382 && "Should only handle conversion from integer to float.");
10383 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10384
10385 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010386
10387 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10388 return SDValue();
10389
Michael Liao59229792012-10-24 04:14:18 +000010390 SmallVector<SDValue, 8> Opnds;
10391 for (unsigned i = 0; i != NumInScalars; ++i) {
10392 SDValue In = N->getOperand(i);
10393
10394 if (In.getOpcode() == ISD::UNDEF)
10395 Opnds.push_back(DAG.getUNDEF(SrcVT));
10396 else
10397 Opnds.push_back(In.getOperand(0));
10398 }
Craig Topper48d114b2014-04-26 18:35:24 +000010399 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010400 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010401
10402 return DAG.getNode(Opcode, dl, VT, BV);
10403}
10404
Michael Liao6d106b72012-10-23 23:06:52 +000010405SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10406 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010407 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010408 EVT VT = N->getValueType(0);
10409
10410 // A vector built entirely of undefs is undef.
10411 if (ISD::allOperandsUndef(N))
10412 return DAG.getUNDEF(VT);
10413
10414 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10415 if (V.getNode())
10416 return V;
10417
Michael Liao59229792012-10-24 04:14:18 +000010418 V = reduceBuildVecConvertToConvertBuildVec(N);
10419 if (V.getNode())
10420 return V;
10421
Dan Gohmana8665142007-06-25 16:23:39 +000010422 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10423 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10424 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010425
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000010426 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10427 if (!isTypeLegal(VT))
10428 return SDValue();
10429
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010430 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000010431 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010432 return SDValue();
10433
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010434 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010435 for (unsigned i = 0; i != NumInScalars; ++i) {
10436 // Ignore undef inputs.
10437 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010438
Dan Gohmana8665142007-06-25 16:23:39 +000010439 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010440 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010441 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010442 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010443 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010444 break;
10445 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010446
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010447 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010448 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010449 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10450 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010451
Craig Topperc0196b12014-04-14 00:51:57 +000010452 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010453 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010454 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010455 VecIn2 = ExtractedFromVec;
10456 } else {
10457 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010458 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010459 break;
10460 }
10461 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010462
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010463 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010464 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010465 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010466 for (unsigned i = 0; i != NumInScalars; ++i) {
10467 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010468 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010469 continue;
10470 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010471
Rafael Espindolab93db662009-04-24 12:40:33 +000010472 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010473 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010474 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010475 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010476 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10477 if (ExtIndex > VT.getVectorNumElements())
10478 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010479
Nate Begeman5f829d82009-04-29 05:20:52 +000010480 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010481 continue;
10482 }
10483
10484 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010485 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010486 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010487 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010488
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010489 // We can't generate a shuffle node with mismatched input and output types.
10490 // Attempt to transform a single input vector to the correct type.
10491 if ((VT != VecIn1.getValueType())) {
10492 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010493 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010494 return SDValue();
10495
10496 // We only support widening of vectors which are half the size of the
10497 // output registers. For example XMM->YMM widening on X86 with AVX.
10498 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10499 return SDValue();
10500
James Molloy1e5c6112012-09-10 14:01:21 +000010501 // If the input vector type has a different base type to the output
10502 // vector type, bail out.
10503 if (VecIn1.getValueType().getVectorElementType() !=
10504 VT.getVectorElementType())
10505 return SDValue();
10506
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010507 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010508 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010509 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010510 }
10511
10512 // If VecIn2 is unused then change it to undef.
10513 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10514
Nadav Rotem841c9a82012-09-20 08:53:31 +000010515 // Check that we were able to transform all incoming values to the same
10516 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010517 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10518 VecIn1.getValueType() != VT)
10519 return SDValue();
10520
Dan Gohmana8665142007-06-25 16:23:39 +000010521 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010522 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010523 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010524 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010525 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010526 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010527
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010528 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010529}
10530
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010531SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010532 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10533 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10534 // inputs come from at most two distinct vectors, turn this into a shuffle
10535 // node.
10536
10537 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010538 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010539 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010540
Nadav Rotem01892102012-07-14 21:30:27 +000010541 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010542 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010543 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010544 return DAG.getUNDEF(VT);
10545
10546 // Optimize concat_vectors where one of the vectors is undef.
10547 if (N->getNumOperands() == 2 &&
10548 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10549 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010550 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010551
10552 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10553 if (In->getOpcode() == ISD::BITCAST &&
10554 !In->getOperand(0)->getValueType(0).isVector()) {
10555 SDValue Scalar = In->getOperand(0);
10556 EVT SclTy = Scalar->getValueType(0);
10557
10558 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10559 return SDValue();
10560
10561 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10562 VT.getSizeInBits() / SclTy.getSizeInBits());
10563 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10564 return SDValue();
10565
10566 SDLoc dl = SDLoc(N);
10567 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10568 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10569 }
10570 }
Nadav Rotem01892102012-07-14 21:30:27 +000010571
Robert Lougher7d9084f2014-02-11 15:42:46 +000010572 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10573 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10574 if (N->getNumOperands() == 2 &&
10575 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10576 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10577 EVT VT = N->getValueType(0);
10578 SDValue N0 = N->getOperand(0);
10579 SDValue N1 = N->getOperand(1);
10580 SmallVector<SDValue, 8> Opnds;
10581 unsigned BuildVecNumElts = N0.getNumOperands();
10582
Hao Liu71224b02014-07-10 03:41:50 +000010583 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10584 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10585 if (SclTy0.isFloatingPoint()) {
10586 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10587 Opnds.push_back(N0.getOperand(i));
10588 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10589 Opnds.push_back(N1.getOperand(i));
10590 } else {
10591 // If BUILD_VECTOR are from built from integer, they may have different
10592 // operand types. Get the smaller type and truncate all operands to it.
10593 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10594 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10595 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10596 N0.getOperand(i)));
10597 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10598 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10599 N1.getOperand(i)));
10600 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010601
Craig Topper48d114b2014-04-26 18:35:24 +000010602 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010603 }
10604
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010605 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10606 // nodes often generate nop CONCAT_VECTOR nodes.
10607 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10608 // place the incoming vectors at the exact same location.
10609 SDValue SingleSource = SDValue();
10610 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10611
10612 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10613 SDValue Op = N->getOperand(i);
10614
10615 if (Op.getOpcode() == ISD::UNDEF)
10616 continue;
10617
10618 // Check if this is the identity extract:
10619 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10620 return SDValue();
10621
10622 // Find the single incoming vector for the extract_subvector.
10623 if (SingleSource.getNode()) {
10624 if (Op.getOperand(0) != SingleSource)
10625 return SDValue();
10626 } else {
10627 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010628
10629 // Check the source type is the same as the type of the result.
10630 // If not, this concat may extend the vector, so we can not
10631 // optimize it away.
10632 if (SingleSource.getValueType() != N->getValueType(0))
10633 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010634 }
10635
10636 unsigned IdentityIndex = i * PartNumElem;
10637 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10638 // The extract index must be constant.
10639 if (!CS)
10640 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010641
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010642 // Check that we are reading from the identity index.
10643 if (CS->getZExtValue() != IdentityIndex)
10644 return SDValue();
10645 }
10646
10647 if (SingleSource.getNode())
10648 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010649
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010650 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010651}
10652
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010653SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10654 EVT NVT = N->getValueType(0);
10655 SDValue V = N->getOperand(0);
10656
Michael Liao7a442c802012-10-17 20:48:33 +000010657 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10658 // Combine:
10659 // (extract_subvec (concat V1, V2, ...), i)
10660 // Into:
10661 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010662 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10663 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010664 if (V->getOperand(0).getValueType() != NVT)
10665 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010666 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10667 unsigned NumElems = NVT.getVectorNumElements();
10668 assert((Idx % NumElems) == 0 &&
10669 "IDX in concat is not a multiple of the result vector length.");
10670 return V->getOperand(Idx / NumElems);
10671 }
10672
Michael Liaobb05a1d2013-03-25 23:47:35 +000010673 // Skip bitcasting
10674 if (V->getOpcode() == ISD::BITCAST)
10675 V = V.getOperand(0);
10676
10677 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010678 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010679 // Handle only simple case where vector being inserted and vector
10680 // being extracted are of same type, and are half size of larger vectors.
10681 EVT BigVT = V->getOperand(0).getValueType();
10682 EVT SmallVT = V->getOperand(1).getValueType();
10683 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10684 return SDValue();
10685
10686 // Only handle cases where both indexes are constants with the same type.
10687 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10688 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10689
10690 if (InsIdx && ExtIdx &&
10691 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10692 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10693 // Combine:
10694 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10695 // Into:
10696 // indices are equal or bit offsets are equal => V1
10697 // otherwise => (extract_subvec V1, ExtIdx)
10698 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10699 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10700 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10701 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10702 DAG.getNode(ISD::BITCAST, dl,
10703 N->getOperand(0).getValueType(),
10704 V->getOperand(0)), N->getOperand(1));
10705 }
10706 }
10707
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010708 return SDValue();
10709}
10710
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010711// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10712static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10713 EVT VT = N->getValueType(0);
10714 unsigned NumElts = VT.getVectorNumElements();
10715
10716 SDValue N0 = N->getOperand(0);
10717 SDValue N1 = N->getOperand(1);
10718 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10719
10720 SmallVector<SDValue, 4> Ops;
10721 EVT ConcatVT = N0.getOperand(0).getValueType();
10722 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10723 unsigned NumConcats = NumElts / NumElemsPerConcat;
10724
10725 // Look at every vector that's inserted. We're looking for exact
10726 // subvector-sized copies from a concatenated vector
10727 for (unsigned I = 0; I != NumConcats; ++I) {
10728 // Make sure we're dealing with a copy.
10729 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010730 bool AllUndef = true, NoUndef = true;
10731 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10732 if (SVN->getMaskElt(J) >= 0)
10733 AllUndef = false;
10734 else
10735 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010736 }
10737
Hao Liubc601962013-05-13 02:07:05 +000010738 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010739 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10740 return SDValue();
10741
10742 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10743 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10744 return SDValue();
10745
10746 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10747 if (FirstElt < N0.getNumOperands())
10748 Ops.push_back(N0.getOperand(FirstElt));
10749 else
10750 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10751
10752 } else if (AllUndef) {
10753 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10754 } else { // Mixed with general masks and undefs, can't do optimization.
10755 return SDValue();
10756 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010757 }
10758
Craig Topper48d114b2014-04-26 18:35:24 +000010759 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010760}
10761
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010762SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010763 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010764 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010765
Mon P Wang25f01062008-11-10 04:46:22 +000010766 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010767 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010768
Craig Topper5894fe42012-04-09 05:16:56 +000010769 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010770
Craig Topper279c77b2012-01-04 08:07:43 +000010771 // Canonicalize shuffle undef, undef -> undef
10772 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10773 return DAG.getUNDEF(VT);
10774
10775 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10776
10777 // Canonicalize shuffle v, v -> v, undef
10778 if (N0 == N1) {
10779 SmallVector<int, 8> NewMask;
10780 for (unsigned i = 0; i != NumElts; ++i) {
10781 int Idx = SVN->getMaskElt(i);
10782 if (Idx >= (int)NumElts) Idx -= NumElts;
10783 NewMask.push_back(Idx);
10784 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010785 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010786 &NewMask[0]);
10787 }
10788
10789 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10790 if (N0.getOpcode() == ISD::UNDEF) {
10791 SmallVector<int, 8> NewMask;
10792 for (unsigned i = 0; i != NumElts; ++i) {
10793 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010794 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010795 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010796 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010797 else
10798 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010799 }
10800 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010801 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010802 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010803 &NewMask[0]);
10804 }
10805
10806 // Remove references to rhs if it is undef
10807 if (N1.getOpcode() == ISD::UNDEF) {
10808 bool Changed = false;
10809 SmallVector<int, 8> NewMask;
10810 for (unsigned i = 0; i != NumElts; ++i) {
10811 int Idx = SVN->getMaskElt(i);
10812 if (Idx >= (int)NumElts) {
10813 Idx = -1;
10814 Changed = true;
10815 }
10816 NewMask.push_back(Idx);
10817 }
10818 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010819 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010820 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010821
Bob Wilsonf63da122010-10-28 17:06:14 +000010822 // If it is a splat, check if the argument vector is another splat or a
10823 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010824 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010825 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010826
Dan Gohmana8665142007-06-25 16:23:39 +000010827 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010828 // not the number of vector elements, look through it. Be careful not to
10829 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010830 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010831 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010832 if (ConvInput.getValueType().isVector() &&
10833 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010834 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010835 }
10836
Dan Gohmana8665142007-06-25 16:23:39 +000010837 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010838 assert(V->getNumOperands() == NumElts &&
10839 "BUILD_VECTOR has wrong number of operands");
10840 SDValue Base;
10841 bool AllSame = true;
10842 for (unsigned i = 0; i != NumElts; ++i) {
10843 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10844 Base = V->getOperand(i);
10845 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010846 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010847 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010848 // Splat of <u, u, u, u>, return <u, u, u, u>
10849 if (!Base.getNode())
10850 return N0;
10851 for (unsigned i = 0; i != NumElts; ++i) {
10852 if (V->getOperand(i) != Base) {
10853 AllSame = false;
10854 break;
10855 }
10856 }
10857 // Splat of <x, x, x, x>, return <x, x, x, x>
10858 if (AllSame)
10859 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010860 }
10861 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010862
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010863 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10864 Level < AfterLegalizeVectorOps &&
10865 (N1.getOpcode() == ISD::UNDEF ||
10866 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10867 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10868 SDValue V = partitionShuffleOfConcats(N, DAG);
10869
10870 if (V.getNode())
10871 return V;
10872 }
10873
Nadav Rotemb0783502012-04-01 19:31:22 +000010874 // If this shuffle node is simply a swizzle of another shuffle node,
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010875 // then try to simplify it.
Nadav Rotemb0783502012-04-01 19:31:22 +000010876 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10877 N1.getOpcode() == ISD::UNDEF) {
10878
Nadav Rotemb0783502012-04-01 19:31:22 +000010879 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10880
Craig Topper5894fe42012-04-09 05:16:56 +000010881 // The incoming shuffle must be of the same type as the result of the
10882 // current shuffle.
10883 assert(OtherSV->getOperand(0).getValueType() == VT &&
10884 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010885
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010886 SmallVector<int, 4> Mask;
10887 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010888 for (unsigned i = 0; i != NumElts; ++i) {
10889 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010890 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010891 // Next, this index comes from the first value, which is the incoming
10892 // shuffle. Adopt the incoming index.
10893 if (Idx >= 0)
10894 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010895 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010896 }
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000010897
10898 // Check if all indices in Mask are Undef. In case, propagate Undef.
10899 bool isUndefMask = true;
10900 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10901 isUndefMask &= Mask[i] < 0;
10902
10903 if (isUndefMask)
10904 return DAG.getUNDEF(VT);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010905
10906 bool CommuteOperands = false;
10907 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10908 // To be valid, the combine shuffle mask should only reference elements
10909 // from one of the two vectors in input to the inner shufflevector.
10910 bool IsValidMask = true;
10911 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10912 // See if the combined mask only reference undefs or elements coming
10913 // from the first shufflevector operand.
10914 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010915
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010916 if (!IsValidMask) {
10917 IsValidMask = true;
10918 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10919 // Check that all the elements come from the second shuffle operand.
10920 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10921 CommuteOperands = IsValidMask;
10922 }
10923
10924 // Early exit if the combined shuffle mask is not valid.
10925 if (!IsValidMask)
10926 return SDValue();
10927 }
10928
10929 // See if this pair of shuffles can be safely folded according to either
10930 // of the following rules:
10931 // shuffle(shuffle(x, y), undef) -> x
10932 // shuffle(shuffle(x, undef), undef) -> x
10933 // shuffle(shuffle(x, y), undef) -> y
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010934 bool IsIdentityMask = true;
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010935 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010936 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10937 // Skip Undefs.
10938 if (Mask[i] < 0)
10939 continue;
10940
10941 // The combined shuffle must map each index to itself.
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010942 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010943 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010944
10945 if (IsIdentityMask) {
10946 if (CommuteOperands)
10947 // optimize shuffle(shuffle(x, y), undef) -> y.
10948 return OtherSV->getOperand(1);
10949
10950 // optimize shuffle(shuffle(x, undef), undef) -> x
10951 // optimize shuffle(shuffle(x, y), undef) -> x
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010952 return OtherSV->getOperand(0);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010953 }
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010954
10955 // It may still be beneficial to combine the two shuffles if the
10956 // resulting shuffle is legal.
Andrea Di Biagioace8e1e2014-08-13 16:09:40 +000010957 if (TLI.isTypeLegal(VT)) {
10958 if (!CommuteOperands) {
10959 if (TLI.isShuffleMaskLegal(Mask, VT))
10960 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10961 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10962 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10963 &Mask[0]);
10964 } else {
10965 // Compute the commuted shuffle mask.
10966 for (unsigned i = 0; i != NumElts; ++i) {
10967 int idx = Mask[i];
10968 if (idx < 0)
10969 continue;
10970 else if (idx < (int)NumElts)
10971 Mask[i] = idx + NumElts;
10972 else
10973 Mask[i] = idx - NumElts;
10974 }
10975
10976 if (TLI.isShuffleMaskLegal(Mask, VT))
10977 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10978 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10979 &Mask[0]);
10980 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010981 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010982 }
10983
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000010984 // Canonicalize shuffles according to rules:
10985 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10986 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10987 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10988 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10989 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10990 TLI.isTypeLegal(VT)) {
10991 // The incoming shuffle must be of the same type as the result of the
10992 // current shuffle.
10993 assert(N1->getOperand(0).getValueType() == VT &&
10994 "Shuffle types don't match");
10995
10996 SDValue SV0 = N1->getOperand(0);
10997 SDValue SV1 = N1->getOperand(1);
10998 bool HasSameOp0 = N0 == SV0;
10999 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11000 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11001 // Commute the operands of this shuffle so that next rule
11002 // will trigger.
11003 return DAG.getCommutedVectorShuffle(*SVN);
11004 }
11005
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011006 // Try to fold according to rules:
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011007 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11008 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11009 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11010 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011011 // Don't try to fold shuffles with illegal type.
11012 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011013 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011014 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11015
11016 // The incoming shuffle must be of the same type as the result of the
11017 // current shuffle.
11018 assert(OtherSV->getOperand(0).getValueType() == VT &&
11019 "Shuffle types don't match");
11020
11021 SDValue SV0 = OtherSV->getOperand(0);
11022 SDValue SV1 = OtherSV->getOperand(1);
11023 bool HasSameOp0 = N1 == SV0;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011024 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11025 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011026 // Early exit.
11027 return SDValue();
11028
11029 SmallVector<int, 4> Mask;
11030 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11031 // operand, and SV1 as the second operand.
11032 for (unsigned i = 0; i != NumElts; ++i) {
11033 int Idx = SVN->getMaskElt(i);
11034 if (Idx < 0) {
11035 // Propagate Undef.
11036 Mask.push_back(Idx);
11037 continue;
11038 }
11039
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011040 if (Idx < (int)NumElts) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011041 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011042 if (IsSV1Undef && Idx >= (int) NumElts)
11043 Idx = -1; // Propagate Undef.
11044 } else
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011045 Idx = HasSameOp0 ? Idx - NumElts : Idx;
11046
11047 Mask.push_back(Idx);
11048 }
11049
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000011050 // Check if all indices in Mask are Undef. In case, propagate Undef.
11051 bool isUndefMask = true;
11052 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11053 isUndefMask &= Mask[i] < 0;
11054
11055 if (isUndefMask)
11056 return DAG.getUNDEF(VT);
11057
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011058 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011059 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11060 if (IsSV1Undef)
11061 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11062 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11063 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011064 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011065 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011066 }
11067
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011068 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011069}
11070
Manman Ren413a6cb2014-01-31 01:10:35 +000011071SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11072 SDValue N0 = N->getOperand(0);
11073 SDValue N2 = N->getOperand(2);
11074
11075 // If the input vector is a concatenation, and the insert replaces
11076 // one of the halves, we can optimize into a single concat_vectors.
11077 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11078 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11079 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11080 EVT VT = N->getValueType(0);
11081
11082 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11083 // (concat_vectors Z, Y)
11084 if (InsIdx == 0)
11085 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11086 N->getOperand(1), N0.getOperand(1));
11087
11088 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11089 // (concat_vectors X, Z)
11090 if (InsIdx == VT.getVectorNumElements()/2)
11091 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11092 N0.getOperand(0), N->getOperand(1));
11093 }
11094
11095 return SDValue();
11096}
11097
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011098/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11099/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000011100/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000011101/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011102SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011103 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011104 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011105 SDValue LHS = N->getOperand(0);
11106 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000011107 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000011108 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000011109 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011110 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011111 SmallVector<int, 8> Indices;
11112 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000011113 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011114 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011115 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011116 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000011117
11118 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011119 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011120 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011121 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000011122 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011123 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011124 }
11125
11126 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011127 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011128 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011129 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011130
Dan Gohmana8665142007-06-25 16:23:39 +000011131 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000011132 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011133 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000011134 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000011135 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000011136 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011137 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000011138 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000011139 }
11140 }
Bill Wendling31b50992009-01-30 23:59:18 +000011141
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011142 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011143}
11144
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011145/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011146SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000011147 assert(N->getValueType(0).isVector() &&
11148 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000011149
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011150 SDValue LHS = N->getOperand(0);
11151 SDValue RHS = N->getOperand(1);
11152 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011153 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000011154
Dan Gohmana8665142007-06-25 16:23:39 +000011155 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000011156 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011157 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000011158 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000011159 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000011160 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11161 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000011162 return SDValue();
11163
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011164 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000011165 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011166 SDValue LHSOp = LHS.getOperand(i);
11167 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000011168
Evan Cheng64d28462006-05-31 06:08:35 +000011169 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000011170 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11171 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000011172 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011173 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000011174 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011175 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000011176 break;
11177 }
Bill Wendling31b50992009-01-30 23:59:18 +000011178
Bob Wilson54081442010-12-17 23:06:49 +000011179 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000011180 EVT RVT = RHSOp.getValueType();
11181 if (RVT != VT) {
11182 // Integer BUILD_VECTOR operands may have types larger than the element
11183 // size (e.g., when the element type is not legal). Prior to type
11184 // legalization, the types may not match between the two BUILD_VECTORS.
11185 // Truncate one of the operands to make them match.
11186 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011187 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011188 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011189 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011190 VT = RVT;
11191 }
11192 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011193 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000011194 LHSOp, RHSOp);
11195 if (FoldOp.getOpcode() != ISD::UNDEF &&
11196 FoldOp.getOpcode() != ISD::Constant &&
11197 FoldOp.getOpcode() != ISD::ConstantFP)
11198 break;
11199 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011200 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000011201 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011202
Bob Wilson54081442010-12-17 23:06:49 +000011203 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000011204 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000011205 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011206
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011207 // Type legalization might introduce new shuffles in the DAG.
11208 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11209 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11210 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11211 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11212 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11213 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11214 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11215 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11216
11217 if (SVN0->getMask().equals(SVN1->getMask())) {
11218 EVT VT = N->getValueType(0);
11219 SDValue UndefVector = LHS.getOperand(1);
11220 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11221 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011222 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011223 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11224 &SVN0->getMask()[0]);
11225 }
11226 }
11227
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011228 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011229}
11230
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011231/// Visit a binary vector operation, like FABS/FNEG.
Craig Topper82384612012-09-11 01:45:21 +000011232SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011233 assert(N->getValueType(0).isVector() &&
11234 "SimplifyVUnaryOp only works on vectors!");
11235
11236 SDValue N0 = N->getOperand(0);
11237
11238 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11239 return SDValue();
11240
11241 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11242 SmallVector<SDValue, 8> Ops;
11243 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11244 SDValue Op = N0.getOperand(i);
11245 if (Op.getOpcode() != ISD::UNDEF &&
11246 Op.getOpcode() != ISD::ConstantFP)
11247 break;
11248 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011249 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011250 if (FoldOp.getOpcode() != ISD::UNDEF &&
11251 FoldOp.getOpcode() != ISD::ConstantFP)
11252 break;
11253 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011254 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011255 }
11256
11257 if (Ops.size() != N0.getNumOperands())
11258 return SDValue();
11259
Craig Topper48d114b2014-04-26 18:35:24 +000011260 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011261}
11262
Andrew Trickef9de2a2013-05-25 02:42:55 +000011263SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011264 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011265 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011266
Bill Wendling31b50992009-01-30 23:59:18 +000011267 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011268 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011269
Nate Begeman2042aa52005-10-08 00:29:44 +000011270 // If we got a simplified select_cc node back from SimplifySelectCC, then
11271 // break it down into a new SETCC node, and a new SELECT node, and then return
11272 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011273 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011274 // Check to see if we got a select_cc back (to turn into setcc/select).
11275 // Otherwise, just return whatever node we got back, like fabs.
11276 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011277 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011278 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011279 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011280 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011281 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000011282 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11283 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000011284 }
Bill Wendling31b50992009-01-30 23:59:18 +000011285
Nate Begeman2042aa52005-10-08 00:29:44 +000011286 return SCC;
11287 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011288 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011289}
11290
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011291/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11292/// being selected between, see if we can simplify the select. Callers of this
11293/// should assume that TheSelect is deleted if this returns true. As such, they
11294/// should return the appropriate thing (e.g. the node) back to the top-level of
11295/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011296bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011297 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011298
Nadav Rotema49a02a2011-02-11 19:57:47 +000011299 // Cannot simplify select with vector condition
11300 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11301
Chris Lattner6c14c352005-10-18 06:04:22 +000011302 // If this is a select from two identical things, try to pull the operation
11303 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011304 if (LHS.getOpcode() != RHS.getOpcode() ||
11305 !LHS.hasOneUse() || !RHS.hasOneUse())
11306 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011307
Chris Lattner254c4452010-09-21 15:46:59 +000011308 // If this is a load and the token chain is identical, replace the select
11309 // of two loads with a load through a select of the address to load from.
11310 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11311 // constants have been dropped into the constant pool.
11312 if (LHS.getOpcode() == ISD::LOAD) {
11313 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11314 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011315
Chris Lattner254c4452010-09-21 15:46:59 +000011316 // Token chains must be identical.
11317 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011318 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011319 LLD->isVolatile() || RLD->isVolatile() ||
11320 // If this is an EXTLOAD, the VT's must match.
11321 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011322 // If this is an EXTLOAD, the kind of extension must match.
11323 (LLD->getExtensionType() != RLD->getExtensionType() &&
11324 // The only exception is if one of the extensions is anyext.
11325 LLD->getExtensionType() != ISD::EXTLOAD &&
11326 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011327 // FIXME: this discards src value information. This is
11328 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011329 // both potential memory locations. Since we are discarding
11330 // src value info, don't do the transformation if the memory
11331 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011332 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011333 RLD->getPointerInfo().getAddrSpace() != 0 ||
11334 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11335 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011336 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011337
Chris Lattnere3267522010-09-21 15:58:55 +000011338 // Check that the select condition doesn't reach either load. If so,
11339 // folding this will induce a cycle into the DAG. If not, this is safe to
11340 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011341 SDValue Addr;
11342 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011343 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11344 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11345 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11346 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011347 // The loads must not depend on one another.
11348 if (LLD->isPredecessorOf(RLD) ||
11349 RLD->isPredecessorOf(LLD))
11350 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011351 Addr = DAG.getSelect(SDLoc(TheSelect),
11352 LLD->getBasePtr().getValueType(),
11353 TheSelect->getOperand(0), LLD->getBasePtr(),
11354 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011355 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011356 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11357 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11358
11359 if ((LLD->hasAnyUseOfValue(1) &&
11360 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011361 (RLD->hasAnyUseOfValue(1) &&
11362 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011363 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011364
Andrew Trickef9de2a2013-05-25 02:42:55 +000011365 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011366 LLD->getBasePtr().getValueType(),
11367 TheSelect->getOperand(0),
11368 TheSelect->getOperand(1),
11369 LLD->getBasePtr(), RLD->getBasePtr(),
11370 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011371 }
11372
Chris Lattnere3267522010-09-21 15:58:55 +000011373 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000011374 // It is safe to replace the two loads if they have different alignments,
11375 // but the new load must be the minimum (most restrictive) alignment of the
11376 // inputs.
Louis Gerbarg67474e32014-07-31 21:45:05 +000011377 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000011378 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011379 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11380 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011381 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000011382 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011383 LLD->getChain(), Addr, MachinePointerInfo(),
11384 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011385 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000011386 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011387 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11388 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011389 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011390 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000011391 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011392 LLD->getChain(), Addr, MachinePointerInfo(),
11393 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011394 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000011395 }
Chris Lattnere3267522010-09-21 15:58:55 +000011396
11397 // Users of the select now use the result of the load.
11398 CombineTo(TheSelect, Load);
11399
11400 // Users of the old loads now use the new load's chain. We know the
11401 // old-load value is dead now.
11402 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11403 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11404 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011405 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011406
Chris Lattner6c14c352005-10-18 06:04:22 +000011407 return false;
11408}
11409
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011410/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000011411/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011412SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011413 SDValue N2, SDValue N3,
11414 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011415 // (x ? y : y) -> y.
11416 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011417
Owen Anderson53aa7a92009-08-10 22:56:29 +000011418 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011419 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11420 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11421 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011422
11423 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011424 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011425 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011426 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011427 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011428
11429 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011430 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011431 return N2;
11432 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011433 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011434 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011435
Nate Begeman2042aa52005-10-08 00:29:44 +000011436 // Check to see if we can simplify the select into an fabs node
11437 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11438 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011439 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011440 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11441 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11442 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11443 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011444 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011445
Nate Begeman2042aa52005-10-08 00:29:44 +000011446 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11447 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11448 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11449 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011450 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011451 }
11452 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011453
Chris Lattner43d63772009-03-11 05:08:08 +000011454 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11455 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11456 // in it. This is a win when the constant is not otherwise available because
11457 // it replaces two constant pool loads with one. We only do this if the FP
11458 // type is known to be legal, because if it isn't, then we are before legalize
11459 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011460 // messing with soft float) and if the ConstantFP is not legal, because if
11461 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011462 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11463 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11464 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011465 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011466 TargetLowering::Legal &&
11467 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11468 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011469 // If both constants have multiple uses, then we won't need to do an
11470 // extra load, they are likely around in registers for other users.
11471 (TV->hasOneUse() || FV->hasOneUse())) {
11472 Constant *Elts[] = {
11473 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11474 const_cast<ConstantFP*>(TV->getConstantFPValue())
11475 };
Chris Lattner229907c2011-07-18 04:54:35 +000011476 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011477 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011478
Chris Lattner43d63772009-03-11 05:08:08 +000011479 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011480 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011481 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11482 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011483 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011484
11485 // Get the offsets to the 0 and 1 element of the array so that we can
11486 // select between them.
11487 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011488 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011489 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011490
Chris Lattner43d63772009-03-11 05:08:08 +000011491 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011492 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011493 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011494 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011495 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11496 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011497 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011498 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011499 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011500 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011501 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011502 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011503 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011504
11505 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011506 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011507
Nate Begeman2042aa52005-10-08 00:29:44 +000011508 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011509 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011510 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011511 (N1C->isNullValue() || // (a < 0) ? b : 0
11512 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011513 EVT XType = N0.getValueType();
11514 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011515 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011516 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011517 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011518 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11519 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011520 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011521 SDValue ShCt = DAG.getConstant(ShCtV,
11522 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011523 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011524 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011525 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011526
Duncan Sands11dd4242008-06-08 20:54:56 +000011527 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011528 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011529 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011530 }
Bill Wendling31b50992009-01-30 23:59:18 +000011531
11532 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011533 }
Bill Wendling31b50992009-01-30 23:59:18 +000011534
Andrew Trickef9de2a2013-05-25 02:42:55 +000011535 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011536 XType, N0,
11537 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011538 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011539 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011540
Duncan Sands11dd4242008-06-08 20:54:56 +000011541 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011542 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011543 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011544 }
Bill Wendling31b50992009-01-30 23:59:18 +000011545
11546 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011547 }
11548 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011549
Owen Anderson3231d132010-09-22 22:58:22 +000011550 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11551 // where y is has a single bit set.
11552 // A plaintext description would be, we can turn the SELECT_CC into an AND
11553 // when the condition can be materialized as an all-ones register. Any
11554 // single bit-test can be materialized as an all-ones register with
11555 // shift-left and shift-right-arith.
11556 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11557 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011558 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011559 N2C && N2C->isNullValue()) {
11560 SDValue AndLHS = N0->getOperand(0);
11561 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11562 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11563 // Shift the tested bit over the sign bit.
11564 APInt AndMask = ConstAndRHS->getAPIntValue();
11565 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011566 DAG.getConstant(AndMask.countLeadingZeros(),
11567 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011568 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011569
Owen Anderson3231d132010-09-22 22:58:22 +000011570 // Now arithmetic right shift it all the way over, so the result is either
11571 // all-ones, or zero.
11572 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011573 DAG.getConstant(AndMask.getBitWidth()-1,
11574 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011575 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011576
Owen Anderson3231d132010-09-22 22:58:22 +000011577 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11578 }
11579 }
11580
Nate Begeman6828ed92005-10-10 21:26:48 +000011581 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011582 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011583 TLI.getBooleanContents(N0.getValueType()) ==
11584 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011585
Chris Lattnera083ffc2007-04-11 06:50:51 +000011586 // If the caller doesn't want us to simplify this into a zext of a compare,
11587 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011588 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011589 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011590
Nate Begeman6828ed92005-10-10 21:26:48 +000011591 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011592 // NOTE: Don't create a SETCC if it's not legal on this target.
11593 if (!LegalOperations ||
11594 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011595 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011596 SDValue Temp, SCC;
11597 // cast from setcc result type to select result type
11598 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011599 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011600 N0, N1, CC);
11601 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011602 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011603 N2.getValueType());
11604 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011605 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011606 N2.getValueType(), SCC);
11607 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011608 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11609 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011610 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011611 }
11612
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011613 AddToWorklist(SCC.getNode());
11614 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011615
11616 if (N2C->getAPIntValue() == 1)
11617 return Temp;
11618
11619 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011620 return DAG.getNode(
11621 ISD::SHL, DL, N2.getValueType(), Temp,
11622 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11623 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011624 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011625 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011626
Nate Begeman2042aa52005-10-08 00:29:44 +000011627 // Check to see if this is the equivalent of setcc
11628 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11629 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011630 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011631 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011632 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011633 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11634 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011635 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011636 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011637 return Res;
11638 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011639
Bill Wendling31b50992009-01-30 23:59:18 +000011640 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011641 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011642 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011643 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011644 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011645 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011646 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011647 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011648 }
Bill Wendling31b50992009-01-30 23:59:18 +000011649 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011650 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011651 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011652 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011653 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011654 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011655 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011656 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011657 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011658 }
Bill Wendling31b50992009-01-30 23:59:18 +000011659 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011660 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011661 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011662 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011663 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011664 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011665 }
11666 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011667
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011668 // Check to see if this is an integer abs.
11669 // select_cc setg[te] X, 0, X, -X ->
11670 // select_cc setgt X, -1, X, -X ->
11671 // select_cc setl[te] X, 0, -X, X ->
11672 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011673 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011674 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011675 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011676 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11677 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11678 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11679 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11680 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11681 (N1C->isOne() && CC == ISD::SETLT)) &&
11682 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11683 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11684
Owen Anderson53aa7a92009-08-10 22:56:29 +000011685 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011686 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011687 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011688 N0,
11689 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011690 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011691 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011692 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011693 AddToWorklist(Shift.getNode());
11694 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011695 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011696 }
11697 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011698
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011699 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011700}
11701
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011702/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011703SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011704 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011705 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011706 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011707 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011708 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011709}
11710
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011711/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000011712/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000011713/// by a magic number.
11714/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011715SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011716 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11717 if (!C)
11718 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011719
11720 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011721 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011722 return SDValue();
11723
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011724 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011725 SDValue S =
11726 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011727
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011728 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011729 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011730 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011731}
11732
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011733/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11734/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000011735SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11736 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11737 if (!C)
11738 return SDValue();
11739
11740 // Avoid division by zero.
11741 if (!C->getAPIntValue())
11742 return SDValue();
11743
11744 std::vector<SDNode *> Built;
11745 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11746
11747 for (SDNode *N : Built)
11748 AddToWorklist(N);
11749 return S;
11750}
11751
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011752/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11753/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000011754/// number.
11755/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011756SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011757 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11758 if (!C)
11759 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011760
11761 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011762 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011763 return SDValue();
11764
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011765 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011766 SDValue S =
11767 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011768
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011769 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011770 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011771 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011772}
11773
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011774SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11775 if (Level >= AfterLegalizeDAG)
11776 return SDValue();
11777
Sanjay Patelb67bd262014-09-21 15:19:15 +000011778 // Expose the DAG combiner to the target combiner implementations.
11779 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000011780
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011781 unsigned Iterations;
11782 if (SDValue Est = TLI.getEstimate(ISD::FDIV, Op, DCI, Iterations)) {
11783 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11784 // For the reciprocal, we need to find the zero of the function:
11785 // F(X) = A X - 1 [which has a zero at X = 1/A]
11786 // =>
11787 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11788 // does not require additional intermediate precision]
11789 EVT VT = Op.getValueType();
11790 SDLoc DL(Op);
11791 SDValue FPOne = DAG.getConstantFP(1.0, VT);
11792
11793 AddToWorklist(Est.getNode());
11794
11795 // Newton iterations: Est = Est + Est (1 - Arg * Est)
11796 for (unsigned i = 0; i < Iterations; ++i) {
11797 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11798 AddToWorklist(NewEst.getNode());
11799
11800 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11801 AddToWorklist(NewEst.getNode());
11802
11803 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11804 AddToWorklist(NewEst.getNode());
11805
11806 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11807 AddToWorklist(Est.getNode());
Sanjay Patelb67bd262014-09-21 15:19:15 +000011808 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011809
11810 return Est;
11811 }
11812
11813 return SDValue();
11814}
11815
11816SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
11817 if (Level >= AfterLegalizeDAG)
11818 return SDValue();
11819
11820 // Expose the DAG combiner to the target combiner implementations.
11821 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11822 unsigned Iterations;
11823 if (SDValue Est = TLI.getEstimate(ISD::FSQRT, Op, DCI, Iterations)) {
11824 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11825 // For the reciprocal sqrt, we need to find the zero of the function:
11826 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
11827 // =>
11828 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
11829 // As a result, we precompute A/2 prior to the iteration loop.
11830 EVT VT = Op.getValueType();
11831 SDLoc DL(Op);
11832 SDValue FPThreeHalves = DAG.getConstantFP(1.5, VT);
11833
11834 AddToWorklist(Est.getNode());
11835
11836 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
11837 // this entire sequence requires only one FP constant.
11838 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, FPThreeHalves, Op);
11839 AddToWorklist(HalfArg.getNode());
11840
11841 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Op);
11842 AddToWorklist(HalfArg.getNode());
11843
11844 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
11845 for (unsigned i = 0; i < Iterations; ++i) {
11846 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
11847 AddToWorklist(NewEst.getNode());
11848
11849 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
11850 AddToWorklist(NewEst.getNode());
11851
11852 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPThreeHalves, NewEst);
11853 AddToWorklist(NewEst.getNode());
11854
11855 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11856 AddToWorklist(Est.getNode());
Sanjay Patelb67bd262014-09-21 15:19:15 +000011857 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000011858
11859 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000011860 }
11861
11862 return SDValue();
11863}
11864
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011865/// Return true if base is a frame index, which is known not to alias with
11866/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000011867static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011868 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011869 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011870 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011871
Jim Laskey0463e082006-10-07 23:37:56 +000011872 // If it's an adding a simple constant then integrate the offset.
11873 if (Base.getOpcode() == ISD::ADD) {
11874 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11875 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011876 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011877 }
11878 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011879
Nate Begeman18150d52009-09-25 06:05:26 +000011880 // Return the underlying GlobalValue, and update the Offset. Return false
11881 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11882 // by multiple nodes with different offsets.
11883 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11884 GV = G->getGlobal();
11885 Offset += G->getOffset();
11886 return false;
11887 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011888
Nate Begeman18150d52009-09-25 06:05:26 +000011889 // Return the underlying Constant value, and update the Offset. Return false
11890 // for ConstantSDNodes since the same constant pool entry may be represented
11891 // by multiple nodes with different offsets.
11892 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011893 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11894 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011895 Offset += C->getOffset();
11896 return false;
11897 }
Jim Laskey0463e082006-10-07 23:37:56 +000011898 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011899 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011900}
11901
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011902/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011903bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011904 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011905 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011906
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011907 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011908 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011909
Jim Laskey0463e082006-10-07 23:37:56 +000011910 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011911 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011912 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011913 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011914 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011915 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11916 Base1, Offset1, GV1, CV1);
11917 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11918 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011919
Nate Begeman18150d52009-09-25 06:05:26 +000011920 // If they have a same base address then check to see if they overlap.
11921 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011922 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11923 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011924
Owen Anderson272ff942010-09-20 20:39:59 +000011925 // It is possible for different frame indices to alias each other, mostly
11926 // when tail call optimization reuses return address slots for arguments.
11927 // To catch this case, look up the actual index of frame indices to compute
11928 // the real alias relationship.
11929 if (isFrameIndex1 && isFrameIndex2) {
11930 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11931 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11932 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011933 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11934 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011935 }
11936
Wesley Peck527da1b2010-11-23 03:31:01 +000011937 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011938 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011939 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11940 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011941
Nate Begeman879d8f12009-09-15 00:18:30 +000011942 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11943 // compared to the size and offset of the access, we may be able to prove they
11944 // do not alias. This check is conservative for now to catch cases created by
11945 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011946 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11947 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11948 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11949 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11950 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11951 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11952 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011953
Nate Begeman879d8f12009-09-15 00:18:30 +000011954 // There is no overlap between these relatively aligned accesses of similar
11955 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011956 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11957 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011958 return false;
11959 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011960
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011961 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11962 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011963#ifndef NDEBUG
11964 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11965 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11966 UseAA = false;
11967#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011968 if (UseAA &&
11969 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011970 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011971 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11972 Op1->getSrcValueOffset());
11973 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11974 Op0->getSrcValueOffset() - MinOffset;
11975 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11976 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011977 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011978 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11979 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000011980 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011981 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11982 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000011983 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011984 if (AAResult == AliasAnalysis::NoAlias)
11985 return false;
11986 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011987
11988 // Otherwise we have to assume they alias.
11989 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011990}
11991
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011992/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000011993/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011994void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011995 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011996 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011997 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011998
Jim Laskeyd07be232006-09-25 16:29:54 +000011999 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012000 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000012001
Jim Laskey708d0db2006-10-04 16:53:27 +000012002 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000012003 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012004 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000012005
Jim Laskey6549d222006-10-05 15:07:25 +000012006 // Look at each chain and determine if it is an alias. If so, add it to the
12007 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000012008 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000012009 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012010 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000012011 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000012012
12013 // For TokenFactor nodes, look at each operand and only continue up the
12014 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012015 // find more and revert to original chain since the xform is unlikely to be
12016 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000012017 //
12018 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012019 // chain we found before we hit a tokenfactor rather than the original
12020 // chain.
12021 if (Depth > 6 || Aliases.size() == 2) {
12022 Aliases.clear();
12023 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000012024 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012025 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012026
Nate Begeman879d8f12009-09-15 00:18:30 +000012027 // Don't bother if we've been before.
12028 if (!Visited.insert(Chain.getNode()))
12029 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012030
Jim Laskey6549d222006-10-05 15:07:25 +000012031 switch (Chain.getOpcode()) {
12032 case ISD::EntryToken:
12033 // Entry token is ideal chain operand, but handled in FindBetterChain.
12034 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012035
Jim Laskey6549d222006-10-05 15:07:25 +000012036 case ISD::LOAD:
12037 case ISD::STORE: {
12038 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012039 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12040 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012041
Jim Laskey6549d222006-10-05 15:07:25 +000012042 // If chain is alias then stop here.
12043 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012044 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000012045 Aliases.push_back(Chain);
12046 } else {
12047 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012048 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012049 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000012050 }
Jim Laskey6549d222006-10-05 15:07:25 +000012051 break;
12052 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012053
Jim Laskey6549d222006-10-05 15:07:25 +000012054 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000012055 // We have to check each of the operands of the token factor for "small"
12056 // token factors, so we queue them up. Adding the operands to the queue
12057 // (stack) in reverse order maintains the original order and increases the
12058 // likelihood that getNode will find a matching token factor (CSE.)
12059 if (Chain.getNumOperands() > 16) {
12060 Aliases.push_back(Chain);
12061 break;
12062 }
Jim Laskey6549d222006-10-05 15:07:25 +000012063 for (unsigned n = Chain.getNumOperands(); n;)
12064 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012065 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000012066 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012067
Jim Laskey6549d222006-10-05 15:07:25 +000012068 default:
12069 // For all other instructions we will just have to take what we can get.
12070 Aliases.push_back(Chain);
12071 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000012072 }
12073 }
Hal Finkel51a98382014-01-24 20:12:02 +000012074
12075 // We need to be careful here to also search for aliases through the
12076 // value operand of a store, etc. Consider the following situation:
12077 // Token1 = ...
12078 // L1 = load Token1, %52
12079 // S1 = store Token1, L1, %51
12080 // L2 = load Token1, %52+8
12081 // S2 = store Token1, L2, %51+8
12082 // Token2 = Token(S1, S2)
12083 // L3 = load Token2, %53
12084 // S3 = store Token2, L3, %52
12085 // L4 = load Token2, %53+8
12086 // S4 = store Token2, L4, %52+8
12087 // If we search for aliases of S3 (which loads address %52), and we look
12088 // only through the chain, then we'll miss the trivial dependence on L1
12089 // (which also loads from %52). We then might change all loads and
12090 // stores to use Token1 as their chain operand, which could result in
12091 // copying %53 into %52 before copying %52 into %51 (which should
12092 // happen first).
12093 //
12094 // The problem is, however, that searching for such data dependencies
12095 // can become expensive, and the cost is not directly related to the
12096 // chain depth. Instead, we'll rule out such configurations here by
12097 // insisting that we've visited all chain users (except for users
12098 // of the original chain, which is not necessary). When doing this,
12099 // we need to look through nodes we don't care about (otherwise, things
12100 // like register copies will interfere with trivial cases).
12101
12102 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000012103 for (const SDNode *N : Visited)
12104 if (N != OriginalChain.getNode())
12105 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000012106
12107 while (!Worklist.empty()) {
12108 const SDNode *M = Worklist.pop_back_val();
12109
12110 // We have already visited M, and want to make sure we've visited any uses
12111 // of M that we care about. For uses that we've not visisted, and don't
12112 // care about, queue them to the worklist.
12113
12114 for (SDNode::use_iterator UI = M->use_begin(),
12115 UIE = M->use_end(); UI != UIE; ++UI)
12116 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12117 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12118 // We've not visited this use, and we care about it (it could have an
12119 // ordering dependency with the original node).
12120 Aliases.clear();
12121 Aliases.push_back(OriginalChain);
12122 return;
12123 }
12124
12125 // We've not visited this use, but we don't care about it. Mark it as
12126 // visited and enqueue it to the worklist.
12127 Worklist.push_back(*UI);
12128 }
12129 }
Jim Laskey708d0db2006-10-04 16:53:27 +000012130}
12131
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012132/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12133/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012134SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12135 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012136
Jim Laskey708d0db2006-10-04 16:53:27 +000012137 // Accumulate all the aliases to this node.
12138 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012139
Dan Gohman4298df62011-05-17 22:20:36 +000012140 // If no operands then chain to entry token.
12141 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000012142 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000012143
12144 // If a single operand then chain to it. We don't need to revisit it.
12145 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000012146 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000012147
Jim Laskey708d0db2006-10-04 16:53:27 +000012148 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000012149 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000012150}
12151
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012152/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000012153void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000012154 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012155 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000012156 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000012157}