blob: d76b1eb39ebdff0ad2bf7f2e9ea39b499fd344ac [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
Jim Laskey6549d222006-10-05 15:07:25 +000080//------------------------------ DAGCombiner ---------------------------------//
81
Nick Lewycky02d5f772009-10-25 06:33:48 +000082 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000083 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000084 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000085 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000086 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000087 bool LegalOperations;
88 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000089 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000090
Chandler Carruth9a0051c2014-07-23 07:08:53 +000091 /// \brief Worklist of all of the nodes that need to be simplified.
92 ///
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
95 ///
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
99
100 /// \brief Mapping from an SDNode to its position on the worklist.
101 ///
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000106
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000107 /// \brief Set of nodes which have been combined (at least once).
108 ///
109 /// This is used to allow us to reliably add any operands of a DAG node
110 /// which have not yet been combined to the worklist.
111 SmallPtrSet<SDNode *, 64> CombinedNodes;
112
Jim Laskeydcb2b832006-10-16 20:52:31 +0000113 // AA - Used for DAG load/store alias analysis.
114 AliasAnalysis &AA;
115
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000116 /// AddUsersToWorklist - When an instruction is simplified, add all users of
Nate Begeman21158fc2005-09-01 00:19:25 +0000117 /// the instruction to the work lists because they might get more simplified
118 /// now.
119 ///
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000120 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000121 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000123 }
124
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000125 /// visit - call the node-specific routine that knows how to fold each
126 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000127 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000128
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000129 public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000130 /// AddToWorklist - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000131 /// back (next to be processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000132 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000133 // Skip handle nodes as they can't usefully be combined and confuse the
134 // zero-use deletion strategy.
135 if (N->getOpcode() == ISD::HANDLENODE)
136 return;
137
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000138 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000140 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000141
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000142 /// removeFromWorklist - remove all instances of N from the worklist.
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000143 ///
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
Chris Lattner375e1a72006-02-17 21:58:01 +0000176 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000177 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000178 /// propagation. 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);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000189 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000190
Evan Cheng0abb54d2010-04-24 04:43:44 +0000191 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
192 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
193 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
194 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000195 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000196 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000197 SDValue PromoteExtend(SDValue Op);
198 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000199
Craig Toppere0b71182013-07-13 07:43:40 +0000200 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000201 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000202 ISD::NodeType ExtType);
203
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000204 /// combine - call the node-specific routine that knows how to fold each
205 /// particular type of node. If that doesn't do anything, try the
206 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000207 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000208
209 // Visitation implementation - Implement dag node combining for different
210 // node types. The semantics are as follows:
211 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000212 // SDValue.getNode() == 0 - No change was made
213 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
214 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000215 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000216 SDValue visitTokenFactor(SDNode *N);
217 SDValue visitMERGE_VALUES(SDNode *N);
218 SDValue visitADD(SDNode *N);
219 SDValue visitSUB(SDNode *N);
220 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000221 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000222 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000223 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000224 SDValue visitMUL(SDNode *N);
225 SDValue visitSDIV(SDNode *N);
226 SDValue visitUDIV(SDNode *N);
227 SDValue visitSREM(SDNode *N);
228 SDValue visitUREM(SDNode *N);
229 SDValue visitMULHU(SDNode *N);
230 SDValue visitMULHS(SDNode *N);
231 SDValue visitSMUL_LOHI(SDNode *N);
232 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000233 SDValue visitSMULO(SDNode *N);
234 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitSDIVREM(SDNode *N);
236 SDValue visitUDIVREM(SDNode *N);
237 SDValue visitAND(SDNode *N);
238 SDValue visitOR(SDNode *N);
239 SDValue visitXOR(SDNode *N);
240 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000241 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000242 SDValue visitSHL(SDNode *N);
243 SDValue visitSRA(SDNode *N);
244 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000245 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000247 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000248 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000249 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000250 SDValue visitCTPOP(SDNode *N);
251 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000252 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000253 SDValue visitSELECT_CC(SDNode *N);
254 SDValue visitSETCC(SDNode *N);
255 SDValue visitSIGN_EXTEND(SDNode *N);
256 SDValue visitZERO_EXTEND(SDNode *N);
257 SDValue visitANY_EXTEND(SDNode *N);
258 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
259 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000260 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitBUILD_PAIR(SDNode *N);
262 SDValue visitFADD(SDNode *N);
263 SDValue visitFSUB(SDNode *N);
264 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000265 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000266 SDValue visitFDIV(SDNode *N);
267 SDValue visitFREM(SDNode *N);
268 SDValue visitFCOPYSIGN(SDNode *N);
269 SDValue visitSINT_TO_FP(SDNode *N);
270 SDValue visitUINT_TO_FP(SDNode *N);
271 SDValue visitFP_TO_SINT(SDNode *N);
272 SDValue visitFP_TO_UINT(SDNode *N);
273 SDValue visitFP_ROUND(SDNode *N);
274 SDValue visitFP_ROUND_INREG(SDNode *N);
275 SDValue visitFP_EXTEND(SDNode *N);
276 SDValue visitFNEG(SDNode *N);
277 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000278 SDValue visitFCEIL(SDNode *N);
279 SDValue visitFTRUNC(SDNode *N);
280 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000281 SDValue visitBRCOND(SDNode *N);
282 SDValue visitBR_CC(SDNode *N);
283 SDValue visitLOAD(SDNode *N);
284 SDValue visitSTORE(SDNode *N);
285 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
286 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
287 SDValue visitBUILD_VECTOR(SDNode *N);
288 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000289 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000290 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000291 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000292
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000293 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000294 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000295
Matt Arsenault985b9de2014-03-17 18:58:01 +0000296 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000297
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000298 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
299 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000300 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
301 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000302 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000303 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000304 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000305 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000306
307 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
308 SDValue &CC) const;
309 bool isOneUseSetCC(SDValue N) const;
310
Scott Michelcf0da6c2009-02-17 22:15:04 +0000311 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000312 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000313 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000314 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000315 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000316 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000317 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000318 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
319 bool DemandHighBits = true);
320 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000321 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
322 SDValue InnerPos, SDValue InnerNeg,
323 unsigned PosOpcode, unsigned NegOpcode,
324 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000325 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000326 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000327 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000328 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000329 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000330 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000331
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000332 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000333
Jim Laskey708d0db2006-10-04 16:53:27 +0000334 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
335 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000336 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000337 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000338
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000339 /// isAlias - Return true if there is any possibility that the two addresses
340 /// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000341 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000342
Jim Laskeyd07be232006-09-25 16:29:54 +0000343 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000344 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000345 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000346
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000347 /// Merge consecutive store operations into a wide store.
348 /// This optimization uses wide integers or vectors when possible.
349 /// \return True if some memory operations were changed.
350 bool MergeConsecutiveStores(StoreSDNode *N);
351
Adam Nemet67483892014-03-04 23:28:31 +0000352 /// \brief Try to transform a truncation where C is a constant:
353 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
354 ///
355 /// \p N needs to be a truncation and its first operand an AND. Other
356 /// requirements are checked by the function (e.g. that trunc is
357 /// single-use) and if missed an empty SDValue is returned.
358 SDValue distributeTruncateThroughAnd(SDNode *N);
359
Chris Lattner4041ab62010-04-15 04:48:01 +0000360 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000361 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000362 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
363 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
364 AttributeSet FnAttrs =
365 DAG.getMachineFunction().getFunction()->getAttributes();
366 ForCodeSize =
367 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
368 Attribute::OptimizeForSize) ||
369 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
370 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000371
Nate Begeman21158fc2005-09-01 00:19:25 +0000372 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000373 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000374
Chris Lattner4041ab62010-04-15 04:48:01 +0000375 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000376
Chris Lattner4041ab62010-04-15 04:48:01 +0000377 /// getShiftAmountTy - Returns a type large enough to hold any valid
378 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000379 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000380 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
381 if (LHSTy.isVector())
382 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000383 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
384 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000385 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000386
Chris Lattner4041ab62010-04-15 04:48:01 +0000387 /// isTypeLegal - This method returns true if we are running before type
388 /// legalization or if the specified VT is legal.
389 bool isTypeLegal(const EVT &VT) {
390 if (!LegalTypes) return true;
391 return TLI.isTypeLegal(VT);
392 }
Matt Arsenault758659232013-05-18 00:21:46 +0000393
394 /// getSetCCResultType - Convenience wrapper around
395 /// TargetLowering::getSetCCResultType
396 EVT getSetCCResultType(EVT VT) const {
397 return TLI.getSetCCResultType(*DAG.getContext(), VT);
398 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000399 };
400}
401
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000402
403namespace {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000404/// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000405/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000406class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000407 DAGCombiner &DC;
408public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000409 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000410 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000411
Craig Topper7b883b32014-03-08 06:31:39 +0000412 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000413 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000414 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000415};
416}
417
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000418//===----------------------------------------------------------------------===//
419// TargetLowering::DAGCombinerInfo implementation
420//===----------------------------------------------------------------------===//
421
422void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000423 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000424}
425
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000426void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000427 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000428}
429
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000430SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000431CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
432 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000433}
434
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000435SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000436CombineTo(SDNode *N, SDValue Res, bool AddTo) {
437 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000438}
439
440
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000441SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000442CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
443 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000444}
445
Dan Gohmane58ab792009-01-29 01:59:02 +0000446void TargetLowering::DAGCombinerInfo::
447CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
448 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
449}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000450
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000451//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000452// Helper Functions
453//===----------------------------------------------------------------------===//
454
Chandler Carruth18066972014-08-02 10:02:07 +0000455void DAGCombiner::deleteAndRecombine(SDNode *N) {
456 removeFromWorklist(N);
457
458 // If the operands of this node are only used by the node, they will now be
459 // dead. Make sure to re-visit them and recursively delete dead nodes.
460 for (const SDValue &Op : N->ops())
461 if (Op->hasOneUse())
462 AddToWorklist(Op.getNode());
463
464 DAG.DeleteNode(N);
465}
466
Chris Lattnere49c9742007-05-14 22:04:50 +0000467/// isNegatibleForFree - Return 1 if we can compute the negated form of the
468/// specified expression for the same cost as the expression itself, or 2 if we
469/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000470static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000471 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000472 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000473 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000474 // fneg is removable even if it has multiple uses.
475 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000476
Chris Lattnere49c9742007-05-14 22:04:50 +0000477 // Don't allow anything with multiple uses.
478 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000479
Chris Lattner46980832007-05-25 02:19:06 +0000480 // Don't recurse exponentially.
481 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000482
Chris Lattnere49c9742007-05-14 22:04:50 +0000483 switch (Op.getOpcode()) {
484 default: return false;
485 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000486 // Don't invert constant FP values after legalize. The negated constant
487 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000488 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000489 case ISD::FADD:
490 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000491 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000492
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000493 // After operation legalization, it might not be legal to create new FSUBs.
494 if (LegalOperations &&
495 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
496 return 0;
497
Craig Topper03f39772012-09-09 22:58:45 +0000498 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000499 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
500 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000501 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000502 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000503 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000504 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000505 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000506 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000507 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000508
Bill Wendling6fbf5492009-01-30 23:10:18 +0000509 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000510 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000511
Chris Lattnere49c9742007-05-14 22:04:50 +0000512 case ISD::FMUL:
513 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000514 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000515
Bill Wendling6fbf5492009-01-30 23:10:18 +0000516 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000517 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
518 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000519 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000520
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000521 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000522 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000523
Chris Lattnere49c9742007-05-14 22:04:50 +0000524 case ISD::FP_EXTEND:
525 case ISD::FP_ROUND:
526 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000527 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000528 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000529 }
530}
531
532/// GetNegatedExpression - If isNegatibleForFree returns true, this function
533/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000534static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000535 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000536 // fneg is removable even if it has multiple uses.
537 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000538
Chris Lattnere49c9742007-05-14 22:04:50 +0000539 // Don't allow anything with multiple uses.
540 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000541
Chris Lattner46980832007-05-25 02:19:06 +0000542 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000543 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000544 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000545 case ISD::ConstantFP: {
546 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
547 V.changeSign();
548 return DAG.getConstantFP(V, Op.getValueType());
549 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000550 case ISD::FADD:
551 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000552 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000553
Bill Wendling6fbf5492009-01-30 23:10:18 +0000554 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000555 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000556 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000557 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000558 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000559 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000560 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000561 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000562 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000563 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000564 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000565 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000566 Op.getOperand(0));
567 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000568 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000569 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000570
Bill Wendling6fbf5492009-01-30 23:10:18 +0000571 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000572 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000573 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000574 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000575
Bill Wendling6fbf5492009-01-30 23:10:18 +0000576 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000577 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000578 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579
Chris Lattnere49c9742007-05-14 22:04:50 +0000580 case ISD::FMUL:
581 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000582 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000583
Bill Wendling6fbf5492009-01-30 23:10:18 +0000584 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000585 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000586 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000587 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000588 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000589 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000590 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000591 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000592
Bill Wendling6fbf5492009-01-30 23:10:18 +0000593 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000594 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000595 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000596 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000597 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000598
Chris Lattnere49c9742007-05-14 22:04:50 +0000599 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000600 case ISD::FSIN:
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 Lattner72733e52008-01-17 07:00:52 +0000604 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000605 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000606 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000607 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000608 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000609 }
610}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000611
Nate Begeman2504fe22005-09-01 23:24:04 +0000612// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000613// that selects between the target values used for true and false, making it
614// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
615// the appropriate nodes based on the type of node we are checking. This
616// simplifies life a bit for the callers.
617bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
618 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000619 if (N.getOpcode() == ISD::SETCC) {
620 LHS = N.getOperand(0);
621 RHS = N.getOperand(1);
622 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000623 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000624 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000625
626 if (N.getOpcode() != ISD::SELECT_CC ||
627 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
628 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
629 return false;
630
631 LHS = N.getOperand(0);
632 RHS = N.getOperand(1);
633 CC = N.getOperand(4);
634 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000635}
636
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000637// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
638// one use. If this is true, it allows the users to invert the operation for
639// free when it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000640bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000641 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000642 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000643 return true;
644 return false;
645}
646
Matt Arsenault985b9de2014-03-17 18:58:01 +0000647/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
648/// elements are all the same constant or undefined.
649static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
650 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
651 if (!C)
652 return false;
653
654 APInt SplatUndef;
655 unsigned SplatBitSize;
656 bool HasAnyUndefs;
657 EVT EltVT = N->getValueType(0).getVectorElementType();
658 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
659 HasAnyUndefs) &&
660 EltVT.getSizeInBits() >= SplatBitSize);
661}
662
663// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000664static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
665 if (isa<ConstantSDNode>(N))
666 return N.getNode();
667 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
668 if(BV && BV->isConstant())
669 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000670 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000671}
672
Matt Arsenault985b9de2014-03-17 18:58:01 +0000673// \brief Returns the SDNode if it is a constant splat BuildVector or constant
674// int.
675static ConstantSDNode *isConstOrConstSplat(SDValue N) {
676 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
677 return CN;
678
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000679 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000680 BitVector UndefElements;
681 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000682
683 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000684 // FIXME: We blindly ignore splats which include undef which is overly
685 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000686 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000687 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000688 return CN;
689 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000690
691 return nullptr;
692}
693
Andrew Trickef9de2a2013-05-25 02:42:55 +0000694SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000695 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000696 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000697 if (N0.getOpcode() == Opc) {
698 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
699 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
700 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
701 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
702 if (!OpNode.getNode())
703 return SDValue();
704 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000705 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000706 if (N0.hasOneUse()) {
707 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
708 // use
709 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
710 if (!OpNode.getNode())
711 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000712 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000713 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000714 }
715 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000716 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000717
Juergen Ributzka68402822014-01-13 21:49:25 +0000718 if (N1.getOpcode() == Opc) {
719 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
720 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
721 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
722 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
723 if (!OpNode.getNode())
724 return SDValue();
725 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
726 }
727 if (N1.hasOneUse()) {
728 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
729 // use
730 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
731 if (!OpNode.getNode())
732 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000733 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000734 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
735 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000736 }
737 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000738
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000739 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000740}
741
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000742SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
743 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000744 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
745 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000746 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000747 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000748 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000749 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000750 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000751 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000752 assert((!To[i].getNode() ||
753 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000754 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000755 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000756 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000757 if (AddTo) {
758 // Push the new nodes and any users onto the worklist
759 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000760 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000761 AddToWorklist(To[i].getNode());
762 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000763 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000764 }
765 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000766
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000767 // Finally, if the node is now dead, remove it from the graph. The node
768 // may not be dead if the replacement process recursively simplified to
769 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000770 if (N->use_empty())
771 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000772 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000773}
774
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000775void DAGCombiner::
776CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000777 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000778 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000779 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000780 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000781
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000782 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000783 AddToWorklist(TLO.New.getNode());
784 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000785
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000786 // Finally, if the node is now dead, remove it from the graph. The node
787 // may not be dead if the replacement process recursively simplified to
788 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000789 if (TLO.Old.getNode()->use_empty())
790 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000791}
792
793/// SimplifyDemandedBits - Check the specified integer node value to see if
794/// it can be simplified or if things it uses can be simplified by bit
795/// propagation. If so, return true.
796bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000797 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000798 APInt KnownZero, KnownOne;
799 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
800 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000801
Dan Gohmane58ab792009-01-29 01:59:02 +0000802 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000803 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000804
Dan Gohmane58ab792009-01-29 01:59:02 +0000805 // Replace the old value with the new one.
806 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000807 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000808 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000809 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000810 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000811 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000812
Dan Gohmane58ab792009-01-29 01:59:02 +0000813 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000814 return true;
815}
816
Evan Cheng0abb54d2010-04-24 04:43:44 +0000817void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000818 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000819 EVT VT = Load->getValueType(0);
820 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000821
Evan Cheng0abb54d2010-04-24 04:43:44 +0000822 DEBUG(dbgs() << "\nReplacing.9 ";
823 Load->dump(&DAG);
824 dbgs() << "\nWith: ";
825 Trunc.getNode()->dump(&DAG);
826 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000827 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000828 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
829 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000830 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000831 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000832}
833
834SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
835 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000836 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000837 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000838 EVT MemVT = LD->getMemoryVT();
839 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000840 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000841 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000842 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000843 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000844 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000845 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000846 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000847 }
848
Evan Chenge19aa5c2010-04-19 19:29:22 +0000849 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000850 switch (Opc) {
851 default: break;
852 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000853 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000854 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000855 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000856 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000857 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000858 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000859 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000860 case ISD::Constant: {
861 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000862 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000863 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000864 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000865 }
866
867 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000868 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000869 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000870}
871
Evan Cheng0abb54d2010-04-24 04:43:44 +0000872SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000873 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
874 return SDValue();
875 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000876 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000877 bool Replace = false;
878 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000879 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000880 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000881 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000882
883 if (Replace)
884 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
885 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000886 DAG.getValueType(OldVT));
887}
888
Evan Cheng0abb54d2010-04-24 04:43:44 +0000889SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000890 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000891 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000892 bool Replace = false;
893 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000894 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000895 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000896 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000897
898 if (Replace)
899 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
900 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000901}
902
Evan Chengaf56fac2010-04-16 06:14:10 +0000903/// PromoteIntBinOp - Promote the specified integer binary operation if the
904/// target indicates it is beneficial. e.g. On x86, it's usually better to
905/// promote i16 operations to i32 since i16 instructions are longer.
906SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
907 if (!LegalOperations)
908 return SDValue();
909
910 EVT VT = Op.getValueType();
911 if (VT.isVector() || !VT.isInteger())
912 return SDValue();
913
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000914 // If operation type is 'undesirable', e.g. i16 on x86, consider
915 // promoting it.
916 unsigned Opc = Op.getOpcode();
917 if (TLI.isTypeDesirableForOp(Opc, VT))
918 return SDValue();
919
Evan Chengaf56fac2010-04-16 06:14:10 +0000920 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000921 // Consult target whether it is a good idea to promote this operation and
922 // what's the right type to promote it to.
923 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000924 assert(PVT != VT && "Don't know what type to promote to!");
925
Evan Cheng0abb54d2010-04-24 04:43:44 +0000926 bool Replace0 = false;
927 SDValue N0 = Op.getOperand(0);
928 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000929 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000930 return SDValue();
931
Evan Cheng0abb54d2010-04-24 04:43:44 +0000932 bool Replace1 = false;
933 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000934 SDValue NN1;
935 if (N0 == N1)
936 NN1 = NN0;
937 else {
938 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000939 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000940 return SDValue();
941 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000942
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000943 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000944 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000945 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000946
947 if (Replace0)
948 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
949 if (Replace1)
950 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000951
Evan Chenge8136902010-04-27 19:48:13 +0000952 DEBUG(dbgs() << "\nPromoting ";
953 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000954 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000955 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000956 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000957 }
958 return SDValue();
959}
960
961/// PromoteIntShiftOp - Promote the specified integer shift operation if the
962/// target indicates it is beneficial. e.g. On x86, it's usually better to
963/// promote i16 operations to i32 since i16 instructions are longer.
964SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
965 if (!LegalOperations)
966 return SDValue();
967
968 EVT VT = Op.getValueType();
969 if (VT.isVector() || !VT.isInteger())
970 return SDValue();
971
972 // If operation type is 'undesirable', e.g. i16 on x86, consider
973 // promoting it.
974 unsigned Opc = Op.getOpcode();
975 if (TLI.isTypeDesirableForOp(Opc, VT))
976 return SDValue();
977
978 EVT PVT = VT;
979 // Consult target whether it is a good idea to promote this operation and
980 // what's the right type to promote it to.
981 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
982 assert(PVT != VT && "Don't know what type to promote to!");
983
Evan Cheng0abb54d2010-04-24 04:43:44 +0000984 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000985 SDValue N0 = Op.getOperand(0);
986 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000987 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000988 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000989 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000990 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000991 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000992 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000993 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000994
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000995 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000996 if (Replace)
997 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000998
Evan Chenge8136902010-04-27 19:48:13 +0000999 DEBUG(dbgs() << "\nPromoting ";
1000 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001001 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001002 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001003 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001004 }
1005 return SDValue();
1006}
1007
Evan Chenge19aa5c2010-04-19 19:29:22 +00001008SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1009 if (!LegalOperations)
1010 return SDValue();
1011
1012 EVT VT = Op.getValueType();
1013 if (VT.isVector() || !VT.isInteger())
1014 return SDValue();
1015
1016 // If operation type is 'undesirable', e.g. i16 on x86, consider
1017 // promoting it.
1018 unsigned Opc = Op.getOpcode();
1019 if (TLI.isTypeDesirableForOp(Opc, VT))
1020 return SDValue();
1021
1022 EVT PVT = VT;
1023 // Consult target whether it is a good idea to promote this operation and
1024 // what's the right type to promote it to.
1025 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1026 assert(PVT != VT && "Don't know what type to promote to!");
1027 // fold (aext (aext x)) -> (aext x)
1028 // fold (aext (zext x)) -> (zext x)
1029 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001030 DEBUG(dbgs() << "\nPromoting ";
1031 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001032 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001033 }
1034 return SDValue();
1035}
1036
1037bool DAGCombiner::PromoteLoad(SDValue Op) {
1038 if (!LegalOperations)
1039 return false;
1040
1041 EVT VT = Op.getValueType();
1042 if (VT.isVector() || !VT.isInteger())
1043 return false;
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 false;
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
Andrew Trickef9de2a2013-05-25 02:42:55 +00001057 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001058 SDNode *N = Op.getNode();
1059 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001060 EVT MemVT = LD->getMemoryVT();
1061 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001062 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001063 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001064 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001065 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001066 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001067 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001068 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1069
Evan Cheng0abb54d2010-04-24 04:43:44 +00001070 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001071 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001072 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001073 Result.getNode()->dump(&DAG);
1074 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001075 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001076 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1077 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001078 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001079 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001080 return true;
1081 }
1082 return false;
1083}
1084
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001085/// \brief Recursively delete a node which has no uses and any operands for
1086/// which it is the only use.
1087///
1088/// Note that this both deletes the nodes and removes them from the worklist.
1089/// It also adds any nodes who have had a user deleted to the worklist as they
1090/// may now have only one use and subject to other combines.
1091bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1092 if (!N->use_empty())
1093 return false;
1094
1095 SmallSetVector<SDNode *, 16> Nodes;
1096 Nodes.insert(N);
1097 do {
1098 N = Nodes.pop_back_val();
1099 if (!N)
1100 continue;
1101
1102 if (N->use_empty()) {
1103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1104 Nodes.insert(N->getOperand(i).getNode());
1105
1106 removeFromWorklist(N);
1107 DAG.DeleteNode(N);
1108 } else {
1109 AddToWorklist(N);
1110 }
1111 } while (!Nodes.empty());
1112 return true;
1113}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001114
Chris Lattnere49c9742007-05-14 22:04:50 +00001115//===----------------------------------------------------------------------===//
1116// Main DAG Combiner implementation
1117//===----------------------------------------------------------------------===//
1118
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001119void DAGCombiner::Run(CombineLevel AtLevel) {
1120 // set the instance variables, so that the various visit routines may use it.
1121 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001122 LegalOperations = Level >= AfterLegalizeVectorOps;
1123 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001124
Evan Cheng5e7658c2008-08-29 22:21:44 +00001125 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001126 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1127 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001128 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001129
Evan Cheng5e7658c2008-08-29 22:21:44 +00001130 // Create a dummy node (which is not added to allnodes), that adds a reference
1131 // to the root node, preventing it from being deleted, and tracking any
1132 // changes of the root.
1133 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001134
James Molloy67b6b112012-02-16 09:17:04 +00001135 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001136 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001137 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001138 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001139 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001140 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001141 N = Worklist.pop_back_val();
1142 } while (!N);
1143
1144 bool GoodWorklistEntry = WorklistMap.erase(N);
1145 (void)GoodWorklistEntry;
1146 assert(GoodWorklistEntry &&
1147 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001148
Evan Cheng5e7658c2008-08-29 22:21:44 +00001149 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1150 // N is deleted from the DAG, since they too may now be dead or may have a
1151 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001152 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001153 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001154
1155 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001156
Chandler Carruth411fb402014-07-26 05:49:40 +00001157 // If this combine is running after legalizing the DAG, re-legalize any
1158 // nodes pulled off the worklist.
1159 if (Level == AfterLegalizeDAG) {
1160 SmallSetVector<SDNode *, 16> UpdatedNodes;
1161 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1162
1163 for (SDNode *LN : UpdatedNodes) {
1164 AddToWorklist(LN);
1165 AddUsersToWorklist(LN);
1166 }
1167 if (!NIsValid)
1168 continue;
1169 }
1170
Chandler Carruthb1432742014-07-28 17:55:07 +00001171 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1172
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001173 // Add any operands of the new node which have not yet been combined to the
1174 // worklist as well. Because the worklist uniques things already, this
1175 // won't repeatedly process the same operand.
1176 CombinedNodes.insert(N);
1177 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1179 AddToWorklist(N->getOperand(i).getNode());
1180
Evan Cheng5e7658c2008-08-29 22:21:44 +00001181 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001182
Craig Topperc0196b12014-04-14 00:51:57 +00001183 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001184 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001185
Evan Cheng5e7658c2008-08-29 22:21:44 +00001186 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001187
Evan Cheng5e7658c2008-08-29 22:21:44 +00001188 // If we get back the same node we passed in, rather than a new node or
1189 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001190 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001191 // mechanics for us, we have no work to do in this case.
1192 if (RV.getNode() == N)
1193 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001194
Evan Cheng5e7658c2008-08-29 22:21:44 +00001195 assert(N->getOpcode() != ISD::DELETED_NODE &&
1196 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1197 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001198
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001199 DEBUG(dbgs() << " ... into: ";
1200 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001201
Devang Patelefec7712011-05-23 22:04:42 +00001202 // Transfer debug value.
1203 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001204 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001205 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001206 else {
1207 assert(N->getValueType(0) == RV.getValueType() &&
1208 N->getNumValues() == 1 && "Type mismatch");
1209 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001210 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001211 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001212
Evan Cheng5e7658c2008-08-29 22:21:44 +00001213 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001214 AddToWorklist(RV.getNode());
1215 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001216
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001217 // Finally, if the node is now dead, remove it from the graph. The node
1218 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001219 // something else needing this node. This will also take care of adding any
1220 // operands which have lost a user to the worklist.
1221 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001222 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001223
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001224 // If the root changed (e.g. it was a dead load, update the root).
1225 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001226 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001227}
1228
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001229SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001230 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001231 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001232 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001233 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001234 case ISD::ADD: return visitADD(N);
1235 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001236 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001237 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001238 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001239 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001240 case ISD::MUL: return visitMUL(N);
1241 case ISD::SDIV: return visitSDIV(N);
1242 case ISD::UDIV: return visitUDIV(N);
1243 case ISD::SREM: return visitSREM(N);
1244 case ISD::UREM: return visitUREM(N);
1245 case ISD::MULHU: return visitMULHU(N);
1246 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001247 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1248 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001249 case ISD::SMULO: return visitSMULO(N);
1250 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001251 case ISD::SDIVREM: return visitSDIVREM(N);
1252 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001253 case ISD::AND: return visitAND(N);
1254 case ISD::OR: return visitOR(N);
1255 case ISD::XOR: return visitXOR(N);
1256 case ISD::SHL: return visitSHL(N);
1257 case ISD::SRA: return visitSRA(N);
1258 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001259 case ISD::ROTR:
1260 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001261 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001262 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001263 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001264 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001265 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001266 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001267 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001268 case ISD::SELECT_CC: return visitSELECT_CC(N);
1269 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001270 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1271 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001272 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001273 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1274 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001275 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001276 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001277 case ISD::FADD: return visitFADD(N);
1278 case ISD::FSUB: return visitFSUB(N);
1279 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001280 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001281 case ISD::FDIV: return visitFDIV(N);
1282 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001283 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001284 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1285 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1286 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1287 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1288 case ISD::FP_ROUND: return visitFP_ROUND(N);
1289 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1290 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1291 case ISD::FNEG: return visitFNEG(N);
1292 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001293 case ISD::FFLOOR: return visitFFLOOR(N);
1294 case ISD::FCEIL: return visitFCEIL(N);
1295 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001296 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001297 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001298 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001299 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001300 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001301 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001302 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1303 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001304 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001305 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001306 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001307 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001308 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001309}
1310
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001311SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001312 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001313
1314 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001315 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001316 assert(N->getOpcode() != ISD::DELETED_NODE &&
1317 "Node was deleted but visit returned NULL!");
1318
1319 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1320 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1321
1322 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001323 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001324 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001325
1326 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1327 }
1328 }
1329
Evan Chengf1005572010-04-28 07:10:39 +00001330 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001331 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001332 switch (N->getOpcode()) {
1333 default: break;
1334 case ISD::ADD:
1335 case ISD::SUB:
1336 case ISD::MUL:
1337 case ISD::AND:
1338 case ISD::OR:
1339 case ISD::XOR:
1340 RV = PromoteIntBinOp(SDValue(N, 0));
1341 break;
1342 case ISD::SHL:
1343 case ISD::SRA:
1344 case ISD::SRL:
1345 RV = PromoteIntShiftOp(SDValue(N, 0));
1346 break;
1347 case ISD::SIGN_EXTEND:
1348 case ISD::ZERO_EXTEND:
1349 case ISD::ANY_EXTEND:
1350 RV = PromoteExtend(SDValue(N, 0));
1351 break;
1352 case ISD::LOAD:
1353 if (PromoteLoad(SDValue(N, 0)))
1354 RV = SDValue(N, 0);
1355 break;
1356 }
1357 }
1358
Scott Michelcf0da6c2009-02-17 22:15:04 +00001359 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001360 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001361 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001362 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001363 SDValue N0 = N->getOperand(0);
1364 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001365
Evan Cheng31604a62008-03-22 01:55:50 +00001366 // Constant operands are canonicalized to RHS.
1367 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001368 SDValue Ops[] = {N1, N0};
1369 SDNode *CSENode;
1370 if (const BinaryWithFlagsSDNode *BinNode =
1371 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1372 CSENode = DAG.getNodeIfExists(
1373 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1374 BinNode->hasNoSignedWrap(), BinNode->isExact());
1375 } else {
1376 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1377 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001378 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001379 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001380 }
1381 }
1382
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001383 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001384}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001385
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001386/// getInputChainForNode - Given a node, return its input chain if it has one,
1387/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001388static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001389 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001390 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001391 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001392 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001393 return N->getOperand(NumOps-1);
1394 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001395 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001396 return N->getOperand(i);
1397 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001398 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001399}
1400
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001401SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001402 // If N has two operands, where one has an input chain equal to the other,
1403 // the 'other' chain is redundant.
1404 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001405 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001406 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001407 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001408 return N->getOperand(1);
1409 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001410
Chris Lattner48fb92f2007-05-16 06:37:59 +00001411 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001412 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001413 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001414 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001415
Jim Laskey708d0db2006-10-04 16:53:27 +00001416 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001417 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001418
Jim Laskey0463e082006-10-07 23:37:56 +00001419 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001420 // encountered.
1421 for (unsigned i = 0; i < TFs.size(); ++i) {
1422 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001423
Jim Laskey708d0db2006-10-04 16:53:27 +00001424 // Check each of the operands.
1425 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001426 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001427
Jim Laskey708d0db2006-10-04 16:53:27 +00001428 switch (Op.getOpcode()) {
1429 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001430 // Entry tokens don't need to be added to the list. They are
1431 // rededundant.
1432 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001433 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001434
Jim Laskey708d0db2006-10-04 16:53:27 +00001435 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001436 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001437 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001438 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001439 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001440 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001441 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001442 Changed = true;
1443 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001444 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001445 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001446
Jim Laskey708d0db2006-10-04 16:53:27 +00001447 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001448 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001449 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001450 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001451 else
1452 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001453 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001454 }
1455 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001456 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001457
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001458 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001459
1460 // If we've change things around then replace token factor.
1461 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001462 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001463 // The entry token is the only possible outcome.
1464 Result = DAG.getEntryNode();
1465 } else {
1466 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001467 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001468 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001469
Jim Laskeydcf983c2006-10-13 23:32:28 +00001470 // Don't add users to work list.
1471 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001473
Jim Laskey708d0db2006-10-04 16:53:27 +00001474 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001475}
1476
Chris Lattneree322b42008-02-13 07:25:05 +00001477/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001478SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001479 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001480 // Replacing results may cause a different MERGE_VALUES to suddenly
1481 // be CSE'd with N, and carry its uses with it. Iterate until no
1482 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001483 // First add the users of this node to the work list so that they
1484 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001485 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001486 do {
1487 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001488 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001489 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001490 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001491 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001492}
1493
Evan Cheng92011002007-01-19 17:51:44 +00001494static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001495SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001496 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001497 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001498 SDValue N00 = N0.getOperand(0);
1499 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001500 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001501
Gabor Greiff304a7a2008-08-28 21:40:38 +00001502 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001503 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001504 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001505 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1506 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001507 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001508 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001509 N00.getOperand(1), N01));
1510 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001511 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001512
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001513 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001514}
1515
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001516SDValue DAGCombiner::visitADD(SDNode *N) {
1517 SDValue N0 = N->getOperand(0);
1518 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001519 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1520 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001521 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001522
1523 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001524 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001525 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001526 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001527
1528 // fold (add x, 0) -> x, vector edition
1529 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1530 return N0;
1531 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1532 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001533 }
Bill Wendling0864a752008-12-10 22:36:00 +00001534
Dan Gohman06563a82007-07-03 14:03:57 +00001535 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001536 if (N0.getOpcode() == ISD::UNDEF)
1537 return N0;
1538 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001539 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001540 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001541 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001542 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001543 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001544 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001545 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001546 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001547 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001548 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001549 // fold (add Sym, c) -> Sym+c
1550 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001551 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001552 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001553 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001554 GA->getOffset() +
1555 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001556 // fold ((c1-A)+c2) -> (c1+c2)-A
1557 if (N1C && N0.getOpcode() == ISD::SUB)
1558 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001559 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001560 DAG.getConstant(N1C->getAPIntValue()+
1561 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001562 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001563 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001564 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001565 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001566 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001567 // fold ((0-A) + B) -> B-A
1568 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1569 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001570 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001571 // fold (A + (0-B)) -> A-B
1572 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1573 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001574 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001575 // fold (A+(B-A)) -> B
1576 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001577 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001578 // fold ((B-A)+A) -> B
1579 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1580 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001581 // fold (A+(B-(A+C))) to (B-C)
1582 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001583 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001584 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001585 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001586 // fold (A+(B-(C+A))) to (B-C)
1587 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001588 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001589 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001590 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001591 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001592 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1593 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001594 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001595 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001596 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001597
Dale Johannesen8c766702008-12-02 01:30:54 +00001598 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1599 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1600 SDValue N00 = N0.getOperand(0);
1601 SDValue N01 = N0.getOperand(1);
1602 SDValue N10 = N1.getOperand(0);
1603 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001604
1605 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001606 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1607 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1608 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001609 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001610
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001611 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1612 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001613
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001614 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001615 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001616 APInt LHSZero, LHSOne;
1617 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001618 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001619
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001620 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001621 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001622
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001623 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1624 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001625 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1626 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1627 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1628 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001629 }
1630 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001631
Evan Cheng92011002007-01-19 17:51:44 +00001632 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001633 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001634 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001635 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001636 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001637 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001638 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001639 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001640 }
1641
Dan Gohman954f4902010-01-19 23:30:49 +00001642 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1643 if (N1.getOpcode() == ISD::SHL &&
1644 N1.getOperand(0).getOpcode() == ISD::SUB)
1645 if (ConstantSDNode *C =
1646 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1647 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001648 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1649 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001650 N1.getOperand(0).getOperand(1),
1651 N1.getOperand(1)));
1652 if (N0.getOpcode() == ISD::SHL &&
1653 N0.getOperand(0).getOpcode() == ISD::SUB)
1654 if (ConstantSDNode *C =
1655 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1656 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001657 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1658 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001659 N0.getOperand(0).getOperand(1),
1660 N0.getOperand(1)));
1661
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001662 if (N1.getOpcode() == ISD::AND) {
1663 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001664 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001665 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1666 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001667
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001668 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1669 // and similar xforms where the inner op is either ~0 or 0.
1670 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001671 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001672 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1673 }
1674 }
1675
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001676 // add (sext i1), X -> sub X, (zext i1)
1677 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1678 N0.getOperand(0).getValueType() == MVT::i1 &&
1679 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001680 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001681 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1682 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1683 }
1684
Evan Chengf1005572010-04-28 07:10:39 +00001685 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001686}
1687
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001688SDValue DAGCombiner::visitADDC(SDNode *N) {
1689 SDValue N0 = N->getOperand(0);
1690 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001691 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1692 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001693 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001694
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001695 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001696 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001697 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001698 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001699 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001700
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001701 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001702 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001703 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001704
Chris Lattner47206662007-03-04 20:40:38 +00001705 // fold (addc x, 0) -> x + no carry out
1706 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001707 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001708 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001709
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001710 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001711 APInt LHSZero, LHSOne;
1712 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001713 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001714
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001715 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001716 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001717
Chris Lattner47206662007-03-04 20:40:38 +00001718 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1719 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001720 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001721 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001722 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001723 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001724 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001725
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001726 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001727}
1728
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001729SDValue DAGCombiner::visitADDE(SDNode *N) {
1730 SDValue N0 = N->getOperand(0);
1731 SDValue N1 = N->getOperand(1);
1732 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001733 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1734 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001735
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001736 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001737 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001738 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001739 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001740
Chris Lattner47206662007-03-04 20:40:38 +00001741 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001742 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001743 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001744
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001745 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001746}
1747
Eric Christophere5ca1e02011-02-16 04:50:12 +00001748// Since it may not be valid to emit a fold to zero for vector initializers
1749// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001750static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001751 SelectionDAG &DAG,
1752 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001753 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001754 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001755 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1756 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001757 return SDValue();
1758}
1759
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001760SDValue DAGCombiner::visitSUB(SDNode *N) {
1761 SDValue N0 = N->getOperand(0);
1762 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001765 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001766 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001767 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001768
Dan Gohmana8665142007-06-25 16:23:39 +00001769 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001770 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001771 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001772 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001773
1774 // fold (sub x, 0) -> x, vector edition
1775 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1776 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001777 }
Bill Wendling0864a752008-12-10 22:36:00 +00001778
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001779 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001780 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001781 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001782 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001783 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001784 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001785 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001786 // fold (sub x, c) -> (add x, -c)
1787 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001788 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001789 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001790 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1791 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001792 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001793 // fold A-(A-B) -> B
1794 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1795 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001796 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001797 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001798 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001799 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001800 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001801 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001802 // fold C2-(A+C1) -> (C2-C1)-A
1803 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001804 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1805 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001806 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001807 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001808 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001809 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001810 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001811 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1812 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001813 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001814 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001815 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001816 // fold ((A+(C+B))-B) -> A+C
1817 if (N0.getOpcode() == ISD::ADD &&
1818 N0.getOperand(1).getOpcode() == ISD::ADD &&
1819 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001820 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001821 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001822 // fold ((A-(B-C))-C) -> A-B
1823 if (N0.getOpcode() == ISD::SUB &&
1824 N0.getOperand(1).getOpcode() == ISD::SUB &&
1825 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001826 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001827 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001828
Dan Gohman06563a82007-07-03 14:03:57 +00001829 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001830 if (N0.getOpcode() == ISD::UNDEF)
1831 return N0;
1832 if (N1.getOpcode() == ISD::UNDEF)
1833 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001834
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001835 // If the relocation model supports it, consider symbol offsets.
1836 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001837 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001838 // fold (sub Sym, c) -> Sym-c
1839 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001840 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001841 GA->getOffset() -
1842 (uint64_t)N1C->getSExtValue());
1843 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1844 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1845 if (GA->getGlobal() == GB->getGlobal())
1846 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1847 VT);
1848 }
1849
Evan Chengf1005572010-04-28 07:10:39 +00001850 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001851}
1852
Craig Topper43a1bd62012-01-07 09:06:39 +00001853SDValue DAGCombiner::visitSUBC(SDNode *N) {
1854 SDValue N0 = N->getOperand(0);
1855 SDValue N1 = N->getOperand(1);
1856 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1857 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1858 EVT VT = N0.getValueType();
1859
1860 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001861 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001862 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1863 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001864 MVT::Glue));
1865
1866 // fold (subc x, x) -> 0 + no borrow
1867 if (N0 == N1)
1868 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001869 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001870 MVT::Glue));
1871
1872 // fold (subc x, 0) -> x + no borrow
1873 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001874 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001875 MVT::Glue));
1876
1877 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1878 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001879 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1880 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001881 MVT::Glue));
1882
1883 return SDValue();
1884}
1885
1886SDValue DAGCombiner::visitSUBE(SDNode *N) {
1887 SDValue N0 = N->getOperand(0);
1888 SDValue N1 = N->getOperand(1);
1889 SDValue CarryIn = N->getOperand(2);
1890
1891 // fold (sube x, y, false) -> (subc x, y)
1892 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001893 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001894
1895 return SDValue();
1896}
1897
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001898SDValue DAGCombiner::visitMUL(SDNode *N) {
1899 SDValue N0 = N->getOperand(0);
1900 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001901 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001902
Dan Gohman06563a82007-07-03 14:03:57 +00001903 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001904 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001905 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001906
1907 bool N0IsConst = false;
1908 bool N1IsConst = false;
1909 APInt ConstValue0, ConstValue1;
1910 // fold vector ops
1911 if (VT.isVector()) {
1912 SDValue FoldedVOp = SimplifyVBinOp(N);
1913 if (FoldedVOp.getNode()) return FoldedVOp;
1914
1915 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1916 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1917 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001918 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001919 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1920 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001921 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001922 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1923 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001924 }
1925
Nate Begeman21158fc2005-09-01 00:19:25 +00001926 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001927 if (N0IsConst && N1IsConst)
1928 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1929
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001930 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001931 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001932 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001933 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001934 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001935 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001936 // We require a splat of the entire scalar bit width for non-contiguous
1937 // bit patterns.
1938 bool IsFullSplat =
1939 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001940 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001941 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001942 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001943 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001944 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001945 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001946 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001947 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001948 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001949 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001950 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001951 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001952 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001953 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001954 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001955 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001956 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001957 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001958 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001959 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001960 DAG.getConstant(Log2Val,
1961 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001962 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001963
1964 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001965 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001966 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001967 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1968 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001969 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001970 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001971 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001972 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001973 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001974 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001975
Chris Lattner324871e2006-03-01 03:44:24 +00001976 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1977 // use.
1978 {
Craig Topperc0196b12014-04-14 00:51:57 +00001979 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001980 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001981 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001982 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1983 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001984 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001985 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001986 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001987 isa<ConstantSDNode>(N1.getOperand(1)) &&
1988 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001989 Sh = N1; Y = N0;
1990 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001991
Gabor Greiff304a7a2008-08-28 21:40:38 +00001992 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001993 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001994 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001995 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001996 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001997 }
1998 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001999
Chris Lattnerf29f5202006-03-04 23:33:26 +00002000 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002001 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2002 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2003 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002004 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2005 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002006 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002007 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002008 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002009
Nate Begeman22e251a2006-02-03 06:46:56 +00002010 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002011 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002012 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002013 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002014
Evan Chengf1005572010-04-28 07:10:39 +00002015 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002016}
2017
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002018SDValue DAGCombiner::visitSDIV(SDNode *N) {
2019 SDValue N0 = N->getOperand(0);
2020 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002021 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2022 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002023 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002024
Dan Gohmana8665142007-06-25 16:23:39 +00002025 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002026 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002027 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002028 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002029 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002030
Nate Begeman21158fc2005-09-01 00:19:25 +00002031 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002032 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002033 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002034 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002035 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002036 return N0;
2037 // fold (sdiv X, -1) -> 0-X
2038 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002039 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002040 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002041 // If we know the sign bits of both operands are zero, strength reduce to a
2042 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002043 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002044 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002045 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002046 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002047 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002048
Nate Begeman57b35672006-02-17 07:26:20 +00002049 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002050 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2051 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002052 // If dividing by powers of two is cheap, then don't perform the following
2053 // fold.
2054 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002055 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002056
Chad Rosier17020f92014-07-23 14:57:52 +00002057 // Target-specific implementation of sdiv x, pow2.
2058 SDValue Res = BuildSDIVPow2(N);
2059 if (Res.getNode())
2060 return Res;
2061
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002062 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002063
Chris Lattner471627c2006-02-16 08:02:36 +00002064 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002065 SDValue SGN =
2066 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2067 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2068 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002069 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002070
Chris Lattner471627c2006-02-16 08:02:36 +00002071 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002072 SDValue SRL =
2073 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2074 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2075 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002076 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002077 AddToWorklist(SRL.getNode());
2078 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002079 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002080 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002081
Nate Begeman4dd38312005-10-21 00:02:42 +00002082 // If we're dividing by a positive value, we're done. Otherwise, we must
2083 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002084 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002085 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002086
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002087 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002088 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002089 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002090
Nate Begemanc6f067a2005-10-20 02:15:44 +00002091 // if integer divide is expensive and we satisfy the requirements, emit an
2092 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002093 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002094 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002095 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002096 }
Dan Gohmana8665142007-06-25 16:23:39 +00002097
Dan Gohman06563a82007-07-03 14:03:57 +00002098 // undef / X -> 0
2099 if (N0.getOpcode() == ISD::UNDEF)
2100 return DAG.getConstant(0, VT);
2101 // X / undef -> undef
2102 if (N1.getOpcode() == ISD::UNDEF)
2103 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002104
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002105 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002106}
2107
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002108SDValue DAGCombiner::visitUDIV(SDNode *N) {
2109 SDValue N0 = N->getOperand(0);
2110 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002111 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2112 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002113 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002114
Dan Gohmana8665142007-06-25 16:23:39 +00002115 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002116 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002117 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002118 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002119 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002120
Nate Begeman21158fc2005-09-01 00:19:25 +00002121 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002122 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002123 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002124 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002125 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002126 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002127 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002128 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002129 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002130 if (N1.getOpcode() == ISD::SHL) {
2131 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002132 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002133 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002134 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002135 N1.getOperand(1),
2136 DAG.getConstant(SHC->getAPIntValue()
2137 .logBase2(),
2138 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002139 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002140 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002141 }
2142 }
2143 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002144 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002145 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002146 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002147 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002148 }
Dan Gohmana8665142007-06-25 16:23:39 +00002149
Dan Gohman06563a82007-07-03 14:03:57 +00002150 // undef / X -> 0
2151 if (N0.getOpcode() == ISD::UNDEF)
2152 return DAG.getConstant(0, VT);
2153 // X / undef -> undef
2154 if (N1.getOpcode() == ISD::UNDEF)
2155 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002156
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002157 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002158}
2159
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002160SDValue DAGCombiner::visitSREM(SDNode *N) {
2161 SDValue N0 = N->getOperand(0);
2162 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002163 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2164 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002165 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002166
Nate Begeman21158fc2005-09-01 00:19:25 +00002167 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002168 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002169 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002170 // If we know the sign bits of both operands are zero, strength reduce to a
2171 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002172 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002173 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002174 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002175 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002176
Dan Gohman9a693412007-11-26 23:46:11 +00002177 // If X/C can be simplified by the division-by-constant logic, lower
2178 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002179 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002180 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002181 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002182 SDValue OptimizedDiv = combine(Div.getNode());
2183 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002184 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002185 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002186 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002187 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002188 return Sub;
2189 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002190 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002191
Dan Gohman06563a82007-07-03 14:03:57 +00002192 // undef % X -> 0
2193 if (N0.getOpcode() == ISD::UNDEF)
2194 return DAG.getConstant(0, VT);
2195 // X % undef -> undef
2196 if (N1.getOpcode() == ISD::UNDEF)
2197 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002198
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002199 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002200}
2201
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002202SDValue DAGCombiner::visitUREM(SDNode *N) {
2203 SDValue N0 = N->getOperand(0);
2204 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002205 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2206 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002207 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002208
Nate Begeman21158fc2005-09-01 00:19:25 +00002209 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002210 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002211 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002212 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002213 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002214 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002215 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002216 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2217 if (N1.getOpcode() == ISD::SHL) {
2218 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002219 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002220 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002221 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002222 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002223 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002224 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002225 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002226 }
2227 }
2228 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002229
Dan Gohman9a693412007-11-26 23:46:11 +00002230 // If X/C can be simplified by the division-by-constant logic, lower
2231 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002232 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002233 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002234 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002235 SDValue OptimizedDiv = combine(Div.getNode());
2236 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002237 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002238 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002239 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002240 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002241 return Sub;
2242 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002243 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002244
Dan Gohman06563a82007-07-03 14:03:57 +00002245 // undef % X -> 0
2246 if (N0.getOpcode() == ISD::UNDEF)
2247 return DAG.getConstant(0, VT);
2248 // X % undef -> undef
2249 if (N1.getOpcode() == ISD::UNDEF)
2250 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002251
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002252 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002253}
2254
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002255SDValue DAGCombiner::visitMULHS(SDNode *N) {
2256 SDValue N0 = N->getOperand(0);
2257 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002258 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002259 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002260 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002261
Nate Begeman21158fc2005-09-01 00:19:25 +00002262 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002263 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002264 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002265 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002266 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002267 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002268 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002269 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002270 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002271 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002272 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002273
Chris Lattner10bd29f2010-12-13 08:39:01 +00002274 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2275 // plus a shift.
2276 if (VT.isSimple() && !VT.isVector()) {
2277 MVT Simple = VT.getSimpleVT();
2278 unsigned SimpleSize = Simple.getSizeInBits();
2279 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2280 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2281 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2282 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2283 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002284 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002285 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002286 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2287 }
2288 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002289
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002290 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002291}
2292
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002293SDValue DAGCombiner::visitMULHU(SDNode *N) {
2294 SDValue N0 = N->getOperand(0);
2295 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002296 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002297 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002298 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002299
Nate Begeman21158fc2005-09-01 00:19:25 +00002300 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002301 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002302 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002303 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002304 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002305 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002306 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002307 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002308 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002309
Chris Lattner10bd29f2010-12-13 08:39:01 +00002310 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2311 // plus a shift.
2312 if (VT.isSimple() && !VT.isVector()) {
2313 MVT Simple = VT.getSimpleVT();
2314 unsigned SimpleSize = Simple.getSizeInBits();
2315 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2316 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2317 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2318 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2319 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2320 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002321 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002322 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2323 }
2324 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002325
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002326 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002327}
2328
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002329/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2330/// compute two values. LoOp and HiOp give the opcodes for the two computations
2331/// that are being performed. Return true if a simplification was made.
2332///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002333SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002334 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002335 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002336 bool HiExists = N->hasAnyUseOfValue(1);
2337 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002338 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002339 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002340 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002341 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002342 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002343 }
2344
2345 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002346 bool LoExists = N->hasAnyUseOfValue(0);
2347 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002348 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002349 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002350 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002351 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002352 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002353 }
2354
Evan Chengece4c682007-11-08 09:25:29 +00002355 // If both halves are used, return as it is.
2356 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002357 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002358
2359 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002360 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002361 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002362 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002363 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002364 SDValue LoOpt = combine(Lo.getNode());
2365 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002366 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002367 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002368 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002369 }
2370
Evan Chengece4c682007-11-08 09:25:29 +00002371 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002372 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002373 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002374 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002375 SDValue HiOpt = combine(Hi.getNode());
2376 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002377 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002378 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002379 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002380 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002381
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002382 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002383}
2384
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002385SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2386 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002387 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002388
Chris Lattner15090e12010-12-15 06:04:19 +00002389 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002390 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002391
2392 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2393 // plus a shift.
2394 if (VT.isSimple() && !VT.isVector()) {
2395 MVT Simple = VT.getSimpleVT();
2396 unsigned SimpleSize = Simple.getSizeInBits();
2397 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2398 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2399 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2400 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2401 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2402 // Compute the high part as N1.
2403 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002404 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002405 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2406 // Compute the low part as N0.
2407 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2408 return CombineTo(N, Lo, Hi);
2409 }
2410 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002411
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002412 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002413}
2414
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002415SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2416 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002417 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002418
Chris Lattner15090e12010-12-15 06:04:19 +00002419 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002420 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002421
Chris Lattner15090e12010-12-15 06:04:19 +00002422 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2423 // plus a shift.
2424 if (VT.isSimple() && !VT.isVector()) {
2425 MVT Simple = VT.getSimpleVT();
2426 unsigned SimpleSize = Simple.getSizeInBits();
2427 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2428 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2429 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2430 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2431 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2432 // Compute the high part as N1.
2433 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002434 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002435 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2436 // Compute the low part as N0.
2437 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2438 return CombineTo(N, Lo, Hi);
2439 }
2440 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002441
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002442 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002443}
2444
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002445SDValue DAGCombiner::visitSMULO(SDNode *N) {
2446 // (smulo x, 2) -> (saddo x, x)
2447 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2448 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002449 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002450 N->getOperand(0), N->getOperand(0));
2451
2452 return SDValue();
2453}
2454
2455SDValue DAGCombiner::visitUMULO(SDNode *N) {
2456 // (umulo x, 2) -> (uaddo x, x)
2457 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2458 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002459 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002460 N->getOperand(0), N->getOperand(0));
2461
2462 return SDValue();
2463}
2464
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002465SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2466 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
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
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002472SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2473 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002474 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002475
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002476 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002477}
2478
Chris Lattner8d6fc202006-05-05 05:51:50 +00002479/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2480/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002481SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2482 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002483 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002484 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002485
Dan Gohmandd5286d2010-01-14 03:08:49 +00002486 // Bail early if none of these transforms apply.
2487 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2488
Chris Lattner002ee912006-05-05 06:31:05 +00002489 // For each of OP in AND/OR/XOR:
2490 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2491 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2492 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002493 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002494 //
2495 // do not sink logical op inside of a vector extend, since it may combine
2496 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002497 EVT Op0VT = N0.getOperand(0).getValueType();
2498 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002499 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002500 // Avoid infinite looping with PromoteIntBinOp.
2501 (N0.getOpcode() == ISD::ANY_EXTEND &&
2502 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002503 (N0.getOpcode() == ISD::TRUNCATE &&
2504 (!TLI.isZExtFree(VT, Op0VT) ||
2505 !TLI.isTruncateFree(Op0VT, VT)) &&
2506 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002507 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002508 Op0VT == N1.getOperand(0).getValueType() &&
2509 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002510 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002511 N0.getOperand(0).getValueType(),
2512 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002513 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002514 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002515 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002516
Chris Lattner5ac42932006-05-05 06:10:43 +00002517 // For each of OP in SHL/SRL/SRA/AND...
2518 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2519 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2520 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002521 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002522 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002523 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002524 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002525 N0.getOperand(0).getValueType(),
2526 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002527 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002528 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002529 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002530 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002531
Nadav Rotemb0783502012-04-01 19:31:22 +00002532 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2533 // Only perform this optimization after type legalization and before
2534 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2535 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2536 // we don't want to undo this promotion.
2537 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2538 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002539 if ((N0.getOpcode() == ISD::BITCAST ||
2540 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2541 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002542 SDValue In0 = N0.getOperand(0);
2543 SDValue In1 = N1.getOperand(0);
2544 EVT In0Ty = In0.getValueType();
2545 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002546 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002547 // If both incoming values are integers, and the original types are the
2548 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002549 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002550 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2551 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002552 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002553 return BC;
2554 }
2555 }
2556
2557 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2558 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2559 // If both shuffles use the same mask, and both shuffle within a single
2560 // vector, then it is worthwhile to move the swizzle after the operation.
2561 // The type-legalizer generates this pattern when loading illegal
2562 // vector types from memory. In many cases this allows additional shuffle
2563 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002564 // There are other cases where moving the shuffle after the xor/and/or
2565 // is profitable even if shuffles don't perform a swizzle.
2566 // If both shuffles use the same mask, and both shuffles have the same first
2567 // or second operand, then it might still be profitable to move the shuffle
2568 // after the xor/and/or operation.
2569 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002570 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2571 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002572
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002573 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002574 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002575
Nadav Rotemb0783502012-04-01 19:31:22 +00002576 // Check that both shuffles use the same mask. The masks are known to be of
2577 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002578 // Check also that shuffles have only one use to avoid introducing extra
2579 // instructions.
2580 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2581 SVN0->getMask().equals(SVN1->getMask())) {
2582 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002583
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002584 // Don't try to fold this node if it requires introducing a
2585 // build vector of all zeros that might be illegal at this stage.
2586 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2587 if (!LegalTypes)
2588 ShOp = DAG.getConstant(0, VT);
2589 else
2590 ShOp = SDValue();
2591 }
2592
2593 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2594 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2595 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2596 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2597 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2598 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002599 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002600 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2601 &SVN0->getMask()[0]);
2602 }
2603
2604 // Don't try to fold this node if it requires introducing a
2605 // build vector of all zeros that might be illegal at this stage.
2606 ShOp = N0->getOperand(0);
2607 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2608 if (!LegalTypes)
2609 ShOp = DAG.getConstant(0, VT);
2610 else
2611 ShOp = SDValue();
2612 }
2613
2614 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2615 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2616 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2617 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2618 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2619 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002620 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002621 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2622 &SVN0->getMask()[0]);
2623 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002624 }
2625 }
Craig Topper9c3da312012-04-09 07:19:09 +00002626
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002627 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002628}
2629
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002630SDValue DAGCombiner::visitAND(SDNode *N) {
2631 SDValue N0 = N->getOperand(0);
2632 SDValue N1 = N->getOperand(1);
2633 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002634 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2635 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002636 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002637 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002638
Dan Gohmana8665142007-06-25 16:23:39 +00002639 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002640 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002641 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002642 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002643
2644 // fold (and x, 0) -> 0, vector edition
2645 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2646 return N0;
2647 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2648 return N1;
2649
2650 // fold (and x, -1) -> x, vector edition
2651 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2652 return N1;
2653 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2654 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002655 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002656
Dan Gohman06563a82007-07-03 14:03:57 +00002657 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002658 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002659 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002660 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002661 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002662 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002663 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002664 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002665 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002666 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002667 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002668 return N0;
2669 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002670 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002671 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002672 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002673 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002674 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002675 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002676 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002677 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002678 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002679 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002680 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002681 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002682 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2683 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002684 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002685 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002686 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002687 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002688 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002689 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002690
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002691 // Replace uses of the AND with uses of the Zero extend node.
2692 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002693
Chris Lattner49beaf42006-02-02 07:17:31 +00002694 // We actually want to replace all uses of the any_extend with the
2695 // zero_extend, to avoid duplicating things. This will later cause this
2696 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002697 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002698 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002699 }
2700 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002701 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002702 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2703 // already be zero by virtue of the width of the base type of the load.
2704 //
2705 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2706 // more cases.
2707 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2708 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2709 N0.getOpcode() == ISD::LOAD) {
2710 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2711 N0 : N0.getOperand(0) );
2712
2713 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2714 // This can be a pure constant or a vector splat, in which case we treat the
2715 // vector as a scalar and use the splat value.
2716 APInt Constant = APInt::getNullValue(1);
2717 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2718 Constant = C->getAPIntValue();
2719 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2720 APInt SplatValue, SplatUndef;
2721 unsigned SplatBitSize;
2722 bool HasAnyUndefs;
2723 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2724 SplatBitSize, HasAnyUndefs);
2725 if (IsSplat) {
2726 // Undef bits can contribute to a possible optimisation if set, so
2727 // set them.
2728 SplatValue |= SplatUndef;
2729
2730 // The splat value may be something like "0x00FFFFFF", which means 0 for
2731 // the first vector value and FF for the rest, repeating. We need a mask
2732 // that will apply equally to all members of the vector, so AND all the
2733 // lanes of the constant together.
2734 EVT VT = Vector->getValueType(0);
2735 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002736
2737 // If the splat value has been compressed to a bitlength lower
2738 // than the size of the vector lane, we need to re-expand it to
2739 // the lane size.
2740 if (BitWidth > SplatBitSize)
2741 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2742 SplatBitSize < BitWidth;
2743 SplatBitSize = SplatBitSize * 2)
2744 SplatValue |= SplatValue.shl(SplatBitSize);
2745
James Molloy862fe492012-02-20 12:02:38 +00002746 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002747 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002748 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2749 }
2750 }
2751
2752 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2753 // actually legal and isn't going to get expanded, else this is a false
2754 // optimisation.
2755 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2756 Load->getMemoryVT());
2757
2758 // Resize the constant to the same size as the original memory access before
2759 // extension. If it is still the AllOnesValue then this AND is completely
2760 // unneeded.
2761 Constant =
2762 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2763
2764 bool B;
2765 switch (Load->getExtensionType()) {
2766 default: B = false; break;
2767 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2768 case ISD::ZEXTLOAD:
2769 case ISD::NON_EXTLOAD: B = true; break;
2770 }
2771
2772 if (B && Constant.isAllOnesValue()) {
2773 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2774 // preserve semantics once we get rid of the AND.
2775 SDValue NewLoad(Load, 0);
2776 if (Load->getExtensionType() == ISD::EXTLOAD) {
2777 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002778 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002779 Load->getChain(), Load->getBasePtr(),
2780 Load->getOffset(), Load->getMemoryVT(),
2781 Load->getMemOperand());
2782 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002783 if (Load->getNumValues() == 3) {
2784 // PRE/POST_INC loads have 3 values.
2785 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2786 NewLoad.getValue(2) };
2787 CombineTo(Load, To, 3, true);
2788 } else {
2789 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2790 }
James Molloy862fe492012-02-20 12:02:38 +00002791 }
2792
2793 // Fold the AND away, taking care not to fold to the old load node if we
2794 // replaced it.
2795 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2796
2797 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2798 }
2799 }
Nate Begeman049b7482005-09-09 19:49:52 +00002800 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2801 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2802 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2803 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002804
Tom Stellard7783b0a2014-06-12 16:04:47 +00002805 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002806 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002807 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002808 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002809 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002810 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002811 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002812 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002813 }
Bill Wendling86171912009-01-30 20:43:18 +00002814 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002815 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002816 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002817 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002818 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002819 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002820 }
Bill Wendling86171912009-01-30 20:43:18 +00002821 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002822 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002823 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002824 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002825 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002826 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002827 }
2828 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002829 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2830 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2831 Op0 == Op1 && LL.getValueType().isInteger() &&
2832 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2833 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2834 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2835 cast<ConstantSDNode>(RR)->isNullValue()))) {
2836 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2837 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002838 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002839 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2840 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2841 }
Nate Begeman049b7482005-09-09 19:49:52 +00002842 // canonicalize equivalent to ll == rl
2843 if (LL == RR && LR == RL) {
2844 Op1 = ISD::getSetCCSwappedOperands(Op1);
2845 std::swap(RL, RR);
2846 }
2847 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002848 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002849 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002850 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002851 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002852 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2853 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002854 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002855 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002856 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002857 }
2858 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002859
Bill Wendling86171912009-01-30 20:43:18 +00002860 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002861 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002862 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002863 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002864 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002865
Nate Begemandc7bba92006-02-03 22:24:05 +00002866 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2867 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002868 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002869 SimplifyDemandedBits(SDValue(N, 0)))
2870 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002871
Nate Begeman02b23c62005-10-13 03:11:28 +00002872 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002873 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002874 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002875 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002876 // If we zero all the possible extended bits, then we can turn this into
2877 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002878 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002879 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002880 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002881 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002882 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002883 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002884 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002885 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002886 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002887 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002888 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002889 }
2890 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002891 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002892 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002893 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002894 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002895 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002896 // If we zero all the possible extended bits, then we can turn this into
2897 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002898 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002899 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002900 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002901 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002902 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002903 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002904 LN0->getChain(), LN0->getBasePtr(),
2905 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002906 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002907 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002908 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002909 }
2910 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002911
Chris Lattnerf0032b32006-02-28 06:49:37 +00002912 // fold (and (load x), 255) -> (zextload x, i8)
2913 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002914 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2915 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2916 (N0.getOpcode() == ISD::ANY_EXTEND &&
2917 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2918 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2919 LoadSDNode *LN0 = HasAnyExt
2920 ? cast<LoadSDNode>(N0.getOperand(0))
2921 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002922 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002923 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002924 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002925 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2926 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2927 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002928
Evan Cheng166a4e62010-01-06 19:38:29 +00002929 if (ExtVT == LoadedVT &&
2930 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002931 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002932
2933 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002934 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002935 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2936 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002937 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002938 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2940 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002941
Chris Lattner88de3842010-01-07 21:53:27 +00002942 // Do not change the width of a volatile load.
2943 // Do not generate loads of non-round integer types since these can
2944 // be expensive (and would be wrong if the type is not byte sized).
2945 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2946 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2947 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002948
Chris Lattner88de3842010-01-07 21:53:27 +00002949 unsigned Alignment = LN0->getAlignment();
2950 SDValue NewPtr = LN0->getBasePtr();
2951
2952 // For big endian targets, we need to add an offset to the pointer
2953 // to load the correct bytes. For little endian systems, we merely
2954 // need to read fewer bytes from the same pointer.
2955 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002956 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2957 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2958 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002959 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002960 NewPtr, DAG.getConstant(PtrOff, PtrType));
2961 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002962 }
Chris Lattner88de3842010-01-07 21:53:27 +00002963
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002964 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002965
Chris Lattner88de3842010-01-07 21:53:27 +00002966 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2967 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002968 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002969 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002970 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002971 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00002972 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002973 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002974 CombineTo(LN0, Load, Load.getValue(1));
2975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002976 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002977 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002978 }
2979 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002980
Evan Chenge6a3b032012-07-17 18:54:11 +00002981 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2982 VT.getSizeInBits() <= 64) {
2983 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2984 APInt ADDC = ADDI->getAPIntValue();
2985 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2986 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2987 // immediate for an add, but it is legal if its top c2 bits are set,
2988 // transform the ADD so the immediate doesn't need to be materialized
2989 // in a register.
2990 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2991 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2992 SRLI->getZExtValue());
2993 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2994 ADDC |= Mask;
2995 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2996 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002997 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002998 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2999 CombineTo(N0.getNode(), NewAdd);
3000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3001 }
3002 }
3003 }
3004 }
3005 }
3006 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003007
Tim Northover819bfb52013-08-27 13:46:45 +00003008 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3009 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3010 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3011 N0.getOperand(1), false);
3012 if (BSwap.getNode())
3013 return BSwap;
3014 }
3015
Evan Chengf1005572010-04-28 07:10:39 +00003016 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003017}
3018
Evan Cheng4c0bd962011-06-21 06:01:08 +00003019/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3020///
3021SDValue 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
3125/// isBSwapHWordElement - Return true if the specified node is an element
3126/// that makes up a 32-bit packed halfword byteswap. i.e.
3127/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003128static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003129 if (!N.getNode()->hasOneUse())
3130 return false;
3131
3132 unsigned Opc = N.getOpcode();
3133 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3134 return false;
3135
3136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3137 if (!N1C)
3138 return false;
3139
3140 unsigned Num;
3141 switch (N1C->getZExtValue()) {
3142 default:
3143 return false;
3144 case 0xFF: Num = 0; break;
3145 case 0xFF00: Num = 1; break;
3146 case 0xFF0000: Num = 2; break;
3147 case 0xFF000000: Num = 3; break;
3148 }
3149
3150 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3151 SDValue N0 = N.getOperand(0);
3152 if (Opc == ISD::AND) {
3153 if (Num == 0 || Num == 2) {
3154 // (x >> 8) & 0xff
3155 // (x >> 8) & 0xff0000
3156 if (N0.getOpcode() != ISD::SRL)
3157 return false;
3158 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3159 if (!C || C->getZExtValue() != 8)
3160 return false;
3161 } else {
3162 // (x << 8) & 0xff00
3163 // (x << 8) & 0xff000000
3164 if (N0.getOpcode() != ISD::SHL)
3165 return false;
3166 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3167 if (!C || C->getZExtValue() != 8)
3168 return false;
3169 }
3170 } else if (Opc == ISD::SHL) {
3171 // (x & 0xff) << 8
3172 // (x & 0xff0000) << 8
3173 if (Num != 0 && Num != 2)
3174 return false;
3175 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3176 if (!C || C->getZExtValue() != 8)
3177 return false;
3178 } else { // Opc == ISD::SRL
3179 // (x & 0xff00) >> 8
3180 // (x & 0xff000000) >> 8
3181 if (Num != 1 && Num != 3)
3182 return false;
3183 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3184 if (!C || C->getZExtValue() != 8)
3185 return false;
3186 }
3187
3188 if (Parts[Num])
3189 return false;
3190
3191 Parts[Num] = N0.getOperand(0).getNode();
3192 return true;
3193}
3194
3195/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3196/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3197/// => (rotl (bswap x), 16)
3198SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3199 if (!LegalOperations)
3200 return SDValue();
3201
3202 EVT VT = N->getValueType(0);
3203 if (VT != MVT::i32)
3204 return SDValue();
3205 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3206 return SDValue();
3207
Craig Topperc0196b12014-04-14 00:51:57 +00003208 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003209 // Look for either
3210 // (or (or (and), (and)), (or (and), (and)))
3211 // (or (or (or (and), (and)), (and)), (and))
3212 if (N0.getOpcode() != ISD::OR)
3213 return SDValue();
3214 SDValue N00 = N0.getOperand(0);
3215 SDValue N01 = N0.getOperand(1);
3216
Evan Chengbf0baa92012-12-13 01:34:32 +00003217 if (N1.getOpcode() == ISD::OR &&
3218 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003219 // (or (or (and), (and)), (or (and), (and)))
3220 SDValue N000 = N00.getOperand(0);
3221 if (!isBSwapHWordElement(N000, Parts))
3222 return SDValue();
3223
3224 SDValue N001 = N00.getOperand(1);
3225 if (!isBSwapHWordElement(N001, Parts))
3226 return SDValue();
3227 SDValue N010 = N01.getOperand(0);
3228 if (!isBSwapHWordElement(N010, Parts))
3229 return SDValue();
3230 SDValue N011 = N01.getOperand(1);
3231 if (!isBSwapHWordElement(N011, Parts))
3232 return SDValue();
3233 } else {
3234 // (or (or (or (and), (and)), (and)), (and))
3235 if (!isBSwapHWordElement(N1, Parts))
3236 return SDValue();
3237 if (!isBSwapHWordElement(N01, Parts))
3238 return SDValue();
3239 if (N00.getOpcode() != ISD::OR)
3240 return SDValue();
3241 SDValue N000 = N00.getOperand(0);
3242 if (!isBSwapHWordElement(N000, Parts))
3243 return SDValue();
3244 SDValue N001 = N00.getOperand(1);
3245 if (!isBSwapHWordElement(N001, Parts))
3246 return SDValue();
3247 }
3248
3249 // Make sure the parts are all coming from the same node.
3250 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3251 return SDValue();
3252
Andrew Trickef9de2a2013-05-25 02:42:55 +00003253 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003254 SDValue(Parts[0],0));
3255
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003256 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003257 // do (x << 16) | (x >> 16).
3258 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3259 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003260 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003261 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003262 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3263 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3264 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3265 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003266}
3267
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003268SDValue DAGCombiner::visitOR(SDNode *N) {
3269 SDValue N0 = N->getOperand(0);
3270 SDValue N1 = N->getOperand(1);
3271 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003272 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3273 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003274 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003275
Dan Gohmana8665142007-06-25 16:23:39 +00003276 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003277 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003278 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003279 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003280
3281 // fold (or x, 0) -> x, vector edition
3282 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3283 return N1;
3284 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3285 return N0;
3286
3287 // fold (or x, -1) -> -1, vector edition
3288 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3289 return N0;
3290 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3291 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003292
3293 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3294 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3295 // Do this only if the resulting shuffle is legal.
3296 if (isa<ShuffleVectorSDNode>(N0) &&
3297 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003298 // Avoid folding a node with illegal type.
3299 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003300 N0->getOperand(1) == N1->getOperand(1) &&
3301 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3302 bool CanFold = true;
3303 unsigned NumElts = VT.getVectorNumElements();
3304 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3305 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3306 // We construct two shuffle masks:
3307 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3308 // and N1 as the second operand.
3309 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3310 // and N0 as the second operand.
3311 // We do this because OR is commutable and therefore there might be
3312 // two ways to fold this node into a shuffle.
3313 SmallVector<int,4> Mask1;
3314 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003315
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003316 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3317 int M0 = SV0->getMaskElt(i);
3318 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003319
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003320 // Both shuffle indexes are undef. Propagate Undef.
3321 if (M0 < 0 && M1 < 0) {
3322 Mask1.push_back(M0);
3323 Mask2.push_back(M0);
3324 continue;
3325 }
3326
3327 if (M0 < 0 || M1 < 0 ||
3328 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3329 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3330 CanFold = false;
3331 break;
3332 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003333
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003334 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3335 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3336 }
3337
3338 if (CanFold) {
3339 // Fold this sequence only if the resulting shuffle is 'legal'.
3340 if (TLI.isShuffleMaskLegal(Mask1, VT))
3341 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3342 N1->getOperand(0), &Mask1[0]);
3343 if (TLI.isShuffleMaskLegal(Mask2, VT))
3344 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3345 N0->getOperand(0), &Mask2[0]);
3346 }
3347 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003348 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003349
Dan Gohman06563a82007-07-03 14:03:57 +00003350 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003351 if (!LegalOperations &&
3352 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003353 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3354 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3355 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003356 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003357 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003358 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003359 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003360 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003361 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003362 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003363 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003364 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003365 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003366 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003367 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003368 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003369 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003370 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003371
3372 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3373 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003374 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003375 return BSwap;
3376 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003377 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003378 return BSwap;
3379
Nate Begeman22e251a2006-02-03 06:46:56 +00003380 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003381 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003382 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003383 return ROR;
3384 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003385 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003386 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003387 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003388 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003389 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3390 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3391 if (!COR.getNode())
3392 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003393 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3394 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003395 N0.getOperand(0), N1), COR);
3396 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003397 }
Nate Begeman049b7482005-09-09 19:49:52 +00003398 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3399 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3400 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3401 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003402
Nate Begeman049b7482005-09-09 19:49:52 +00003403 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003404 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003405 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3406 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003407 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003408 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003409 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003410 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003411 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003412 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003413 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003414 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3415 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003416 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003417 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003418 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003419 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003420 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003421 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003422 }
3423 }
3424 // canonicalize equivalent to ll == rl
3425 if (LL == RR && LR == RL) {
3426 Op1 = ISD::getSetCCSwappedOperands(Op1);
3427 std::swap(RL, RR);
3428 }
3429 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003430 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003431 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003432 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003433 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003434 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3435 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003436 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003437 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003438 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003439 }
3440 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003441
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003442 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003443 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003444 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003445 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003446 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003447
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003448 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003449 if (N0.getOpcode() == ISD::AND &&
3450 N1.getOpcode() == ISD::AND &&
3451 N0.getOperand(1).getOpcode() == ISD::Constant &&
3452 N1.getOperand(1).getOpcode() == ISD::Constant &&
3453 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003454 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003455 // We can only do this xform if we know that bits from X that are set in C2
3456 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003457 const APInt &LHSMask =
3458 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3459 const APInt &RHSMask =
3460 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003461
Dan Gohman309d3d52007-06-22 14:59:07 +00003462 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3463 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003464 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003465 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003466 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003467 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003468 }
3469 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003470
Chris Lattner97614c82006-09-14 20:50:57 +00003471 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003472 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003473 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003474
Dan Gohman600f62b2010-06-24 14:30:44 +00003475 // Simplify the operands using demanded-bits information.
3476 if (!VT.isVector() &&
3477 SimplifyDemandedBits(SDValue(N, 0)))
3478 return SDValue(N, 0);
3479
Evan Chengf1005572010-04-28 07:10:39 +00003480 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003481}
3482
Chris Lattner97614c82006-09-14 20:50:57 +00003483/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003484static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003485 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003486 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003487 Mask = Op.getOperand(1);
3488 Op = Op.getOperand(0);
3489 } else {
3490 return false;
3491 }
3492 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003493
Chris Lattner97614c82006-09-14 20:50:57 +00003494 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3495 Shift = Op;
3496 return true;
3497 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003498
Scott Michelcf0da6c2009-02-17 22:15:04 +00003499 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003500}
3501
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003502// Return true if we can prove that, whenever Neg and Pos are both in the
3503// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003504// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3505//
3506// (or (shift1 X, Neg), (shift2 X, Pos))
3507//
Adam Nemetc6553a82014-03-07 23:56:24 +00003508// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3509// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3510// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003511static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003512 // If OpSize is a power of 2 then:
3513 //
3514 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3515 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3516 //
3517 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3518 // for the stronger condition:
3519 //
3520 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3521 //
3522 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3523 // we can just replace Neg with Neg' for the rest of the function.
3524 //
3525 // In other cases we check for the even stronger condition:
3526 //
3527 // Neg == OpSize - Pos [B]
3528 //
3529 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3530 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003531 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003532 // We could actually use [A] whenever OpSize is a power of 2, but the
3533 // only extra cases that it would match are those uninteresting ones
3534 // where Neg and Pos are never in range at the same time. E.g. for
3535 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3536 // as well as (sub 32, Pos), but:
3537 //
3538 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3539 //
3540 // always invokes undefined behavior for 32-bit X.
3541 //
3542 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003543 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003544 if (Neg.getOpcode() == ISD::AND &&
3545 isPowerOf2_64(OpSize) &&
3546 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3547 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3548 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003549 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003550 }
3551
Richard Sandiford0f264db2014-01-09 10:49:40 +00003552 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3553 if (Neg.getOpcode() != ISD::SUB)
3554 return 0;
3555 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3556 if (!NegC)
3557 return 0;
3558 SDValue NegOp1 = Neg.getOperand(1);
3559
Adam Nemet5117f5d2014-03-07 23:56:28 +00003560 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3561 // Pos'. The truncation is redundant for the purpose of the equality.
3562 if (MaskLoBits &&
3563 Pos.getOpcode() == ISD::AND &&
3564 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3565 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3566 Pos = Pos.getOperand(0);
3567
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003568 // The condition we need is now:
3569 //
3570 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3571 //
3572 // If NegOp1 == Pos then we need:
3573 //
3574 // OpSize & Mask == NegC & Mask
3575 //
3576 // (because "x & Mask" is a truncation and distributes through subtraction).
3577 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003578 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003579 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003580 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3581 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003582 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003583 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3584 //
3585 // which, again because "x & Mask" is a truncation, becomes:
3586 //
3587 // NegC & Mask == (OpSize - PosC) & Mask
3588 // OpSize & Mask == (NegC + PosC) & Mask
3589 else if (Pos.getOpcode() == ISD::ADD &&
3590 Pos.getOperand(0) == NegOp1 &&
3591 Pos.getOperand(1).getOpcode() == ISD::Constant)
3592 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3593 NegC->getAPIntValue());
3594 else
3595 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003596
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003597 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003598 if (MaskLoBits)
3599 // Opsize & Mask is 0 since Mask is Opsize - 1.
3600 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003601 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003602}
3603
Richard Sandiford95c864d2014-01-08 15:40:47 +00003604// A subroutine of MatchRotate used once we have found an OR of two opposite
3605// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3606// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3607// former being preferred if supported. InnerPos and InnerNeg are Pos and
3608// Neg with outer conversions stripped away.
3609SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3610 SDValue Neg, SDValue InnerPos,
3611 SDValue InnerNeg, unsigned PosOpcode,
3612 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003613 // fold (or (shl x, (*ext y)),
3614 // (srl x, (*ext (sub 32, y)))) ->
3615 // (rotl x, y) or (rotr x, (sub 32, y))
3616 //
3617 // fold (or (shl x, (*ext (sub 32, y))),
3618 // (srl x, (*ext y))) ->
3619 // (rotr x, y) or (rotl x, (sub 32, y))
3620 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003621 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003622 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3623 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3624 HasPos ? Pos : Neg).getNode();
3625 }
3626
Craig Topperc0196b12014-04-14 00:51:57 +00003627 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003628}
3629
Chris Lattner97614c82006-09-14 20:50:57 +00003630// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3631// idioms for rotate, and if the target supports rotation instructions, generate
3632// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003633SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003634 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003635 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003636 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003637
3638 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003639 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3640 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003641 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003642
Chris Lattner97614c82006-09-14 20:50:57 +00003643 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003644 SDValue LHSShift; // The shift.
3645 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003646 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003647 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003648
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003649 SDValue RHSShift; // The shift.
3650 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003651 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003652 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003653
Chris Lattner97614c82006-09-14 20:50:57 +00003654 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003655 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003656
3657 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003658 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003659
Chris Lattner97614c82006-09-14 20:50:57 +00003660 // Canonicalize shl to left side in a shl/srl pair.
3661 if (RHSShift.getOpcode() == ISD::SHL) {
3662 std::swap(LHS, RHS);
3663 std::swap(LHSShift, RHSShift);
3664 std::swap(LHSMask , RHSMask );
3665 }
3666
Duncan Sands13237ac2008-06-06 12:08:01 +00003667 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003668 SDValue LHSShiftArg = LHSShift.getOperand(0);
3669 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003670 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003671 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003672
3673 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3674 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003675 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3676 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003677 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3678 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003679 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003680 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003681
Craig Topper65161fa2012-09-29 06:54:22 +00003682 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3683 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003684
Chris Lattner97614c82006-09-14 20:50:57 +00003685 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003686 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003687 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003688
Gabor Greiff304a7a2008-08-28 21:40:38 +00003689 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003690 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3691 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003692 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003693 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003694 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3695 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003696 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003697
Bill Wendling35972a92009-01-30 21:14:50 +00003698 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003699 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003700
Gabor Greiff304a7a2008-08-28 21:40:38 +00003701 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003702 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003703
Chris Lattner97614c82006-09-14 20:50:57 +00003704 // If there is a mask here, and we have a variable shift, we can't be sure
3705 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003706 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003707 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003708
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003709 // If the shift amount is sign/zext/any-extended just peel it off.
3710 SDValue LExtOp0 = LHSShiftAmt;
3711 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003712 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3713 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3714 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3715 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3716 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3717 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3718 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3719 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003720 LExtOp0 = LHSShiftAmt.getOperand(0);
3721 RExtOp0 = RHSShiftAmt.getOperand(0);
3722 }
3723
Richard Sandiford95c864d2014-01-08 15:40:47 +00003724 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3725 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3726 if (TryL)
3727 return TryL;
3728
3729 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3730 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3731 if (TryR)
3732 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003733
Craig Topperc0196b12014-04-14 00:51:57 +00003734 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003735}
3736
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003737SDValue DAGCombiner::visitXOR(SDNode *N) {
3738 SDValue N0 = N->getOperand(0);
3739 SDValue N1 = N->getOperand(1);
3740 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003741 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3742 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003743 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003744
Dan Gohmana8665142007-06-25 16:23:39 +00003745 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003746 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003747 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003748 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003749
3750 // fold (xor x, 0) -> x, vector edition
3751 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3752 return N1;
3753 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3754 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003755 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003756
Evan Chengdf1690d2008-03-25 20:08:07 +00003757 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3758 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3759 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003760 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003761 if (N0.getOpcode() == ISD::UNDEF)
3762 return N0;
3763 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003764 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003765 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003766 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003767 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003768 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003769 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003770 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003771 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003772 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003773 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003774 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003775 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003776 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003777 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003778
Nate Begeman21158fc2005-09-01 00:19:25 +00003779 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003780 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003781 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003782 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3783 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003784
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003785 if (!LegalOperations ||
3786 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003787 switch (N0.getOpcode()) {
3788 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003789 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003790 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003791 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003792 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003793 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003794 N0.getOperand(3), NotCC);
3795 }
3796 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003797 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003798
Chris Lattner58c227b2007-09-10 21:39:07 +00003799 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003800 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003801 N0.getNode()->hasOneUse() &&
3802 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003803 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003804 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003805 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003806 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003807 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003808 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003809
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003810 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003811 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003812 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003813 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003814 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3815 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003816 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3817 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003818 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003819 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003820 }
3821 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003822 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003823 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003824 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003825 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003826 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3827 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003828 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3829 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003830 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003831 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003832 }
3833 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003834 // fold (xor (and x, y), y) -> (and (not x), y)
3835 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003836 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003837 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003838 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003839 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003840 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003841 }
Bill Wendling35972a92009-01-30 21:14:50 +00003842 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003843 if (N1C && N0.getOpcode() == ISD::XOR) {
3844 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3845 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3846 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003847 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003848 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003849 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003850 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003851 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003852 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003853 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003854 }
3855 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003856 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003857 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003858
Chris Lattner8d6fc202006-05-05 05:51:50 +00003859 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3860 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003861 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003862 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003863 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003864
Chris Lattner098c01e2006-04-08 04:15:24 +00003865 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003866 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003867 SimplifyDemandedBits(SDValue(N, 0)))
3868 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003869
Evan Chengf1005572010-04-28 07:10:39 +00003870 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003871}
3872
Chris Lattner7c709a52007-12-06 07:33:36 +00003873/// visitShiftByConstant - Handle transforms common to the three shifts, when
3874/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003875SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003876 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003877 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003878 return SDValue();
3879
Gabor Greiff304a7a2008-08-28 21:40:38 +00003880 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003881 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003882
Chris Lattner7c709a52007-12-06 07:33:36 +00003883 // We want to pull some binops through shifts, so that we have (and (shift))
3884 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3885 // thing happens with address calculations, so it's important to canonicalize
3886 // it.
3887 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003888
Chris Lattner7c709a52007-12-06 07:33:36 +00003889 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003890 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003891 case ISD::OR:
3892 case ISD::XOR:
3893 HighBitSet = false; // We can only transform sra if the high bit is clear.
3894 break;
3895 case ISD::AND:
3896 HighBitSet = true; // We can only transform sra if the high bit is set.
3897 break;
3898 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003899 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003900 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003901 HighBitSet = false; // We can only transform sra if the high bit is clear.
3902 break;
3903 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003904
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003905 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003906 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003907 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003908
3909 // FIXME: disable this unless the input to the binop is a shift by a constant.
3910 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003911 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003912 // void foo(int *X, int i) { X[i & 1235] = 1; }
3913 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003914 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003915 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003916 BinOpLHSVal->getOpcode() != ISD::SRA &&
3917 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3918 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003919 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003920
Owen Anderson53aa7a92009-08-10 22:56:29 +00003921 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003922
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003923 // If this is a signed shift right, and the high bit is modified by the
3924 // logical operation, do not perform the transformation. The highBitSet
3925 // boolean indicates the value of the high bit of the constant which would
3926 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003927 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003928 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3929 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003930 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003931 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003932
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003933 if (!TLI.isDesirableToCommuteWithShift(LHS))
3934 return SDValue();
3935
Chris Lattner7c709a52007-12-06 07:33:36 +00003936 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003937 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003938 N->getValueType(0),
3939 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003940 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003941
3942 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003943 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003944 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003945 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003946
3947 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003948 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003949}
3950
Adam Nemet67483892014-03-04 23:28:31 +00003951SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3952 assert(N->getOpcode() == ISD::TRUNCATE);
3953 assert(N->getOperand(0).getOpcode() == ISD::AND);
3954
3955 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3956 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3957 SDValue N01 = N->getOperand(0).getOperand(1);
3958
Matt Arsenault985b9de2014-03-17 18:58:01 +00003959 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003960 EVT TruncVT = N->getValueType(0);
3961 SDValue N00 = N->getOperand(0).getOperand(0);
3962 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003963 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003964
3965 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3966 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3967 DAG.getConstant(TruncC, TruncVT));
3968 }
3969 }
3970
3971 return SDValue();
3972}
Adam Nemet7f928f12014-03-07 23:56:30 +00003973
3974SDValue DAGCombiner::visitRotate(SDNode *N) {
3975 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3976 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3977 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3978 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3979 if (NewOp1.getNode())
3980 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3981 N->getOperand(0), NewOp1);
3982 }
3983 return SDValue();
3984}
3985
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003986SDValue DAGCombiner::visitSHL(SDNode *N) {
3987 SDValue N0 = N->getOperand(0);
3988 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003989 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3990 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003991 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003992 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003993
Daniel Sandersa1840d22013-11-11 17:23:41 +00003994 // fold vector ops
3995 if (VT.isVector()) {
3996 SDValue FoldedVOp = SimplifyVBinOp(N);
3997 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003998
3999 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4000 // If setcc produces all-one true value then:
4001 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004002 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004003 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004004 SDValue N00 = N0->getOperand(0);
4005 SDValue N01 = N0->getOperand(1);
4006 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004007
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004008 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4009 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4010 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004011 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4012 if (C.getNode())
4013 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4014 }
4015 } else {
4016 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004017 }
4018 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004019 }
4020
Nate Begeman21158fc2005-09-01 00:19:25 +00004021 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004022 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004023 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004024 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004025 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004026 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004027 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004028 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004029 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004030 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004031 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004032 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004033 // fold (shl undef, x) -> 0
4034 if (N0.getOpcode() == ISD::UNDEF)
4035 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004036 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004037 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004038 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004039 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004040 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004041 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004042 N1.getOperand(0).getOpcode() == ISD::AND) {
4043 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4044 if (NewOp1.getNode())
4045 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004046 }
4047
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004048 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4049 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004050
4051 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004052 if (N1C && N0.getOpcode() == ISD::SHL) {
4053 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4054 uint64_t c1 = N0C1->getZExtValue();
4055 uint64_t c2 = N1C->getZExtValue();
4056 if (c1 + c2 >= OpSizeInBits)
4057 return DAG.getConstant(0, VT);
4058 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4059 DAG.getConstant(c1 + c2, N1.getValueType()));
4060 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004061 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004062
4063 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4064 // For this to be valid, the second form must not preserve any of the bits
4065 // that are shifted out by the inner shift in the first form. This means
4066 // the outer shift size must be >= the number of bits added by the ext.
4067 // As a corollary, we don't care what kind of ext it is.
4068 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4069 N0.getOpcode() == ISD::ANY_EXTEND ||
4070 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004071 N0.getOperand(0).getOpcode() == ISD::SHL) {
4072 SDValue N0Op0 = N0.getOperand(0);
4073 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4074 uint64_t c1 = N0Op0C1->getZExtValue();
4075 uint64_t c2 = N1C->getZExtValue();
4076 EVT InnerShiftVT = N0Op0.getValueType();
4077 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4078 if (c2 >= OpSizeInBits - InnerShiftSize) {
4079 if (c1 + c2 >= OpSizeInBits)
4080 return DAG.getConstant(0, VT);
4081 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4082 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4083 N0Op0->getOperand(0)),
4084 DAG.getConstant(c1 + c2, N1.getValueType()));
4085 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004086 }
4087 }
4088
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004089 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4090 // Only fold this if the inner zext has no other uses to avoid increasing
4091 // the total number of instructions.
4092 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004093 N0.getOperand(0).getOpcode() == ISD::SRL) {
4094 SDValue N0Op0 = N0.getOperand(0);
4095 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4096 uint64_t c1 = N0Op0C1->getZExtValue();
4097 if (c1 < VT.getScalarSizeInBits()) {
4098 uint64_t c2 = N1C->getZExtValue();
4099 if (c1 == c2) {
4100 SDValue NewOp0 = N0.getOperand(0);
4101 EVT CountVT = NewOp0.getOperand(1).getValueType();
4102 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4103 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004104 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004105 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4106 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004107 }
4108 }
4109 }
4110
Eli Friedman1877ac92011-06-09 22:14:44 +00004111 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4112 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004113 // Only fold this if the inner shift has no other uses -- if it does, folding
4114 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004115 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4116 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4117 uint64_t c1 = N0C1->getZExtValue();
4118 if (c1 < OpSizeInBits) {
4119 uint64_t c2 = N1C->getZExtValue();
4120 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4121 SDValue Shift;
4122 if (c2 > c1) {
4123 Mask = Mask.shl(c2 - c1);
4124 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4125 DAG.getConstant(c2 - c1, N1.getValueType()));
4126 } else {
4127 Mask = Mask.lshr(c1 - c2);
4128 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4129 DAG.getConstant(c1 - c2, N1.getValueType()));
4130 }
4131 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4132 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004133 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004134 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004135 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004136 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004137 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004138 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004139 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004140 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4141 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004142 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004143 HiBitsMask);
4144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004145
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004146 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004147 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004148 if (NewSHL.getNode())
4149 return NewSHL;
4150 }
4151
Evan Chengf1005572010-04-28 07:10:39 +00004152 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004153}
4154
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004155SDValue DAGCombiner::visitSRA(SDNode *N) {
4156 SDValue N0 = N->getOperand(0);
4157 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004158 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4159 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004160 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004161 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004162
Daniel Sandersa1840d22013-11-11 17:23:41 +00004163 // fold vector ops
4164 if (VT.isVector()) {
4165 SDValue FoldedVOp = SimplifyVBinOp(N);
4166 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004167
4168 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004169 }
4170
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004171 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004172 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004173 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004174 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004175 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004176 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004177 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004178 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004179 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004180 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004181 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004182 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004183 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004184 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004185 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004186 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4187 // sext_inreg.
4188 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004189 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004190 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4191 if (VT.isVector())
4192 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4193 ExtVT, VT.getVectorNumElements());
4194 if ((!LegalOperations ||
4195 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004196 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004197 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004198 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004199
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004200 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004201 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004202 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004203 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004204 if (Sum >= OpSizeInBits)
4205 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004206 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004207 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004208 }
4209 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004210
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004211 // fold (sra (shl X, m), (sub result_size, n))
4212 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004213 // result_size - n != m.
4214 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004215 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004216 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004217 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004218 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4219 if (N01C) {
4220 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004221 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004222 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4223
4224 if (VT.isVector())
4225 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4226
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004227 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004228 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004229
Scott Michelcf0da6c2009-02-17 22:15:04 +00004230 // If the shift is not a no-op (in which case this should be just a sign
4231 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004232 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004233 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004234 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004235 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4236 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004237 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004238
Owen Andersonb2c80da2011-02-25 21:41:48 +00004239 SDValue Amt = DAG.getConstant(ShiftAmt,
4240 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004241 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004242 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004243 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004244 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004245 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004246 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004247 }
4248 }
4249 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004250
Duncan Sands3ed76882009-02-01 18:06:53 +00004251 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004252 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004253 N1.getOperand(0).getOpcode() == ISD::AND) {
4254 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4255 if (NewOp1.getNode())
4256 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004257 }
4258
Matt Arsenault985b9de2014-03-17 18:58:01 +00004259 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004260 // if c1 is equal to the number of bits the trunc removes
4261 if (N0.getOpcode() == ISD::TRUNCATE &&
4262 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4263 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4264 N0.getOperand(0).hasOneUse() &&
4265 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004266 N1C) {
4267 SDValue N0Op0 = N0.getOperand(0);
4268 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4269 unsigned LargeShiftVal = LargeShift->getZExtValue();
4270 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004271
Matt Arsenault985b9de2014-03-17 18:58:01 +00004272 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4273 SDValue Amt =
4274 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4275 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4276 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4277 N0Op0.getOperand(0), Amt);
4278 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4279 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004280 }
4281 }
4282
Scott Michelcf0da6c2009-02-17 22:15:04 +00004283 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004284 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4285 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004286
4287
Nate Begeman21158fc2005-09-01 00:19:25 +00004288 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004289 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004290 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004291
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004292 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004293 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004294 if (NewSRA.getNode())
4295 return NewSRA;
4296 }
4297
Evan Chengf1005572010-04-28 07:10:39 +00004298 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004299}
4300
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004301SDValue DAGCombiner::visitSRL(SDNode *N) {
4302 SDValue N0 = N->getOperand(0);
4303 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004304 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4305 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004306 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004307 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004308
Daniel Sandersa1840d22013-11-11 17:23:41 +00004309 // fold vector ops
4310 if (VT.isVector()) {
4311 SDValue FoldedVOp = SimplifyVBinOp(N);
4312 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004313
4314 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004315 }
4316
Nate Begeman21158fc2005-09-01 00:19:25 +00004317 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004318 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004319 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004320 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004321 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004322 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004323 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004324 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004325 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004326 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004327 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004328 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004329 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004330 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004331 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004332 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004333
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004334 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004335 if (N1C && N0.getOpcode() == ISD::SRL) {
4336 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4337 uint64_t c1 = N01C->getZExtValue();
4338 uint64_t c2 = N1C->getZExtValue();
4339 if (c1 + c2 >= OpSizeInBits)
4340 return DAG.getConstant(0, VT);
4341 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4342 DAG.getConstant(c1 + c2, N1.getValueType()));
4343 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004344 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004345
Dale Johannesencd538af2010-12-17 21:45:49 +00004346 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004347 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4348 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004349 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004350 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004351 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4352 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004353 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4354 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004355 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004356 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004357 if (c1 + OpSizeInBits == InnerShiftSize) {
4358 if (c1 + c2 >= InnerShiftSize)
4359 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004360 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4361 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004362 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004363 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004364 }
4365 }
4366
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004367 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004368 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4369 unsigned BitSize = N0.getScalarValueSizeInBits();
4370 if (BitSize <= 64) {
4371 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4372 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4373 DAG.getConstant(~0ULL >> ShAmt, VT));
4374 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004375 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004376
Michael Liao62ebfd82013-06-21 18:45:27 +00004377 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004378 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4379 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004380 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004381 unsigned BitSize = SmallVT.getScalarSizeInBits();
4382 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004383 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004384
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004385 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004386 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004387 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004388 N0.getOperand(0),
4389 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004390 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004391 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004392 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4393 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4394 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004395 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004396 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004397
Chris Lattner2e33fb42006-10-12 20:23:19 +00004398 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4399 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004400 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004401 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004402 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004403 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004404
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004405 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004406 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004407 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004408 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004409 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004410
Chris Lattner49932492006-04-02 06:11:11 +00004411 // If any of the input bits are KnownOne, then the input couldn't be all
4412 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004413 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004414
Chris Lattner49932492006-04-02 06:11:11 +00004415 // If all of the bits input the to ctlz node are known to be zero, then
4416 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004417 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004418 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004419
Chris Lattner49932492006-04-02 06:11:11 +00004420 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004421 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004422 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004423 // could be set on input to the CTLZ node. If this bit is set, the SRL
4424 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4425 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004426 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004427 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004428
Chris Lattner49932492006-04-02 06:11:11 +00004429 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004430 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004431 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004432 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004433 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004434
Andrew Trickef9de2a2013-05-25 02:42:55 +00004435 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004436 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004437 }
4438 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004439
Duncan Sands3ed76882009-02-01 18:06:53 +00004440 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004441 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004442 N1.getOperand(0).getOpcode() == ISD::AND) {
4443 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4444 if (NewOp1.getNode())
4445 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004446 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004447
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004448 // fold operands of srl based on knowledge that the low bits are not
4449 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004450 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4451 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004452
Evan Chengb175de62009-12-18 21:31:31 +00004453 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004454 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004455 if (NewSRL.getNode())
4456 return NewSRL;
4457 }
4458
Dan Gohman600f62b2010-06-24 14:30:44 +00004459 // Attempt to convert a srl of a load into a narrower zero-extending load.
4460 SDValue NarrowLoad = ReduceLoadWidth(N);
4461 if (NarrowLoad.getNode())
4462 return NarrowLoad;
4463
Evan Chengb175de62009-12-18 21:31:31 +00004464 // Here is a common situation. We want to optimize:
4465 //
4466 // %a = ...
4467 // %b = and i32 %a, 2
4468 // %c = srl i32 %b, 1
4469 // brcond i32 %c ...
4470 //
4471 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004472 //
Evan Chengb175de62009-12-18 21:31:31 +00004473 // %a = ...
4474 // %b = and %a, 2
4475 // %c = setcc eq %b, 0
4476 // brcond %c ...
4477 //
4478 // However when after the source operand of SRL is optimized into AND, the SRL
4479 // itself may not be optimized further. Look for it and add the BRCOND into
4480 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004481 if (N->hasOneUse()) {
4482 SDNode *Use = *N->use_begin();
4483 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004484 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004485 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4486 // Also look pass the truncate.
4487 Use = *Use->use_begin();
4488 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004489 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004490 }
4491 }
Evan Chengb175de62009-12-18 21:31:31 +00004492
Evan Chengf1005572010-04-28 07:10:39 +00004493 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004494}
4495
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004496SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4497 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004498 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004499
4500 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004501 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004502 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004503 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004504}
4505
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004506SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4507 SDValue N0 = N->getOperand(0);
4508 EVT VT = N->getValueType(0);
4509
4510 // fold (ctlz_zero_undef c1) -> c2
4511 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004512 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004513 return SDValue();
4514}
4515
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004516SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4517 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004518 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004519
Nate Begeman21158fc2005-09-01 00:19:25 +00004520 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004521 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004522 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004523 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004524}
4525
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004526SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4527 SDValue N0 = N->getOperand(0);
4528 EVT VT = N->getValueType(0);
4529
4530 // fold (cttz_zero_undef c1) -> c2
4531 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004532 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004533 return SDValue();
4534}
4535
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004536SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4537 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004538 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004539
Nate Begeman21158fc2005-09-01 00:19:25 +00004540 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004541 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004542 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004543 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004544}
4545
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004546SDValue DAGCombiner::visitSELECT(SDNode *N) {
4547 SDValue N0 = N->getOperand(0);
4548 SDValue N1 = N->getOperand(1);
4549 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004550 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4552 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004553 EVT VT = N->getValueType(0);
4554 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004555
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004556 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004557 if (N1 == N2)
4558 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004559 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004560 if (N0C && !N0C->isNullValue())
4561 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004562 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004563 if (N0C && N0C->isNullValue())
4564 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004565 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004566 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004567 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004568 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004569 // We can't do this reliably if integer based booleans have different contents
4570 // to floating point based booleans. This is because we can't tell whether we
4571 // have an integer-based boolean or a floating-point-based boolean unless we
4572 // can find the SETCC that produced it and inspect its operands. This is
4573 // fairly easy if C is the SETCC node, but it can potentially be
4574 // undiscoverable (or not reasonably discoverable). For example, it could be
4575 // in another basic block or it could require searching a complicated
4576 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004577 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004578 (VT0 == MVT::i1 || (VT0.isInteger() &&
4579 TLI.getBooleanContents(false, false) ==
4580 TLI.getBooleanContents(false, true) &&
4581 TLI.getBooleanContents(false, false) ==
4582 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004583 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004584 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004585 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004586 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004587 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004588 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004589 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004590 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004591 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004592 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4593 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004594 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004595 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004596 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004597 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004598 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004599 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004600 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004601 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004602 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004603 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004604 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004605 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004606 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004607 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004608 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004609 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004610 // fold (select X, X, Y) -> (or X, Y)
4611 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004612 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004613 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004614 // fold (select X, Y, X) -> (and X, Y)
4615 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004616 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004617 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004618
Chris Lattner6c14c352005-10-18 06:04:22 +00004619 // If we can fold this based on the true/false value, do so.
4620 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004621 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004622
Nate Begemanc760f802005-09-19 22:34:01 +00004623 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004624 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004625 if ((!LegalOperations &&
4626 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4627 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004628 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004629 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004630 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004631 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004632 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004633
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004634 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004635}
4636
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004637static
4638std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4639 SDLoc DL(N);
4640 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004641 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004642
4643 // Split the inputs.
4644 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004645 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4646 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004647
4648 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4649 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4650
4651 return std::make_pair(Lo, Hi);
4652}
4653
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004654// This function assumes all the vselect's arguments are CONCAT_VECTOR
4655// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4656static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4657 SDLoc dl(N);
4658 SDValue Cond = N->getOperand(0);
4659 SDValue LHS = N->getOperand(1);
4660 SDValue RHS = N->getOperand(2);
4661 MVT VT = N->getSimpleValueType(0);
4662 int NumElems = VT.getVectorNumElements();
4663 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4664 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4665 Cond.getOpcode() == ISD::BUILD_VECTOR);
4666
4667 // We're sure we have an even number of elements due to the
4668 // concat_vectors we have as arguments to vselect.
4669 // Skip BV elements until we find one that's not an UNDEF
4670 // After we find an UNDEF element, keep looping until we get to half the
4671 // length of the BV and see if all the non-undef nodes are the same.
4672 ConstantSDNode *BottomHalf = nullptr;
4673 for (int i = 0; i < NumElems / 2; ++i) {
4674 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4675 continue;
4676
4677 if (BottomHalf == nullptr)
4678 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4679 else if (Cond->getOperand(i).getNode() != BottomHalf)
4680 return SDValue();
4681 }
4682
4683 // Do the same for the second half of the BuildVector
4684 ConstantSDNode *TopHalf = nullptr;
4685 for (int i = NumElems / 2; i < NumElems; ++i) {
4686 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4687 continue;
4688
4689 if (TopHalf == nullptr)
4690 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4691 else if (Cond->getOperand(i).getNode() != TopHalf)
4692 return SDValue();
4693 }
4694
4695 assert(TopHalf && BottomHalf &&
4696 "One half of the selector was all UNDEFs and the other was all the "
4697 "same value. This should have been addressed before this function.");
4698 return DAG.getNode(
4699 ISD::CONCAT_VECTORS, dl, VT,
4700 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4701 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4702}
4703
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004704SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4705 SDValue N0 = N->getOperand(0);
4706 SDValue N1 = N->getOperand(1);
4707 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004708 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004709
4710 // Canonicalize integer abs.
4711 // vselect (setg[te] X, 0), X, -X ->
4712 // vselect (setgt X, -1), X, -X ->
4713 // vselect (setl[te] X, 0), -X, X ->
4714 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4715 if (N0.getOpcode() == ISD::SETCC) {
4716 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4717 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4718 bool isAbs = false;
4719 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4720
4721 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4722 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4723 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4724 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4725 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4726 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4727 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4728
4729 if (isAbs) {
4730 EVT VT = LHS.getValueType();
4731 SDValue Shift = DAG.getNode(
4732 ISD::SRA, DL, VT, LHS,
4733 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4734 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004735 AddToWorklist(Shift.getNode());
4736 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004737 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4738 }
4739 }
4740
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004741 // If the VSELECT result requires splitting and the mask is provided by a
4742 // SETCC, then split both nodes and its operands before legalization. This
4743 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4744 // and enables future optimizations (e.g. min/max pattern matching on X86).
4745 if (N0.getOpcode() == ISD::SETCC) {
4746 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004747
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004748 // Check if any splitting is required.
4749 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4750 TargetLowering::TypeSplitVector)
4751 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004752
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004753 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004754 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4755 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4756 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004757
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004758 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4759 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004760
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004761 // Add the new VSELECT nodes to the work list in case they need to be split
4762 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004763 AddToWorklist(Lo.getNode());
4764 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004765
4766 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004767 }
4768
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004769 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4770 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4771 return N1;
4772 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4773 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4774 return N2;
4775
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004776 // The ConvertSelectToConcatVector function is assuming both the above
4777 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4778 // and addressed.
4779 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4780 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4781 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4782 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4783 if (CV.getNode())
4784 return CV;
4785 }
4786
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004787 return SDValue();
4788}
4789
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004790SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4791 SDValue N0 = N->getOperand(0);
4792 SDValue N1 = N->getOperand(1);
4793 SDValue N2 = N->getOperand(2);
4794 SDValue N3 = N->getOperand(3);
4795 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004796 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004797
Nate Begemanc760f802005-09-19 22:34:01 +00004798 // fold select_cc lhs, rhs, x, x, cc -> x
4799 if (N2 == N3)
4800 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004801
Chris Lattner8b68dec2006-09-20 06:19:26 +00004802 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004803 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004804 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004805 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004806 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004807
Stephen Lin605207f2013-06-15 04:03:33 +00004808 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4809 if (!SCCC->isNullValue())
4810 return N2; // cond always true -> true val
4811 else
4812 return N3; // cond always false -> false val
4813 }
4814
4815 // Fold to a simpler select_cc
4816 if (SCC.getOpcode() == ISD::SETCC)
4817 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4818 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4819 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004820 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004821
Chris Lattner6c14c352005-10-18 06:04:22 +00004822 // If we can fold this based on the true/false value, do so.
4823 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004824 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004825
Nate Begemanc760f802005-09-19 22:34:01 +00004826 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004827 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004828}
4829
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004830SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004831 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004832 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004833 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004834}
4835
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004836// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4837// dag node into a ConstantSDNode or a build_vector of constants.
4838// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004839// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004840// Vector extends are not folded if operations are legal; this is to
4841// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004842static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4843 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004844 bool LegalOperations) {
4845 unsigned Opcode = N->getOpcode();
4846 SDValue N0 = N->getOperand(0);
4847 EVT VT = N->getValueType(0);
4848
4849 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4850 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4851
4852 // fold (sext c1) -> c1
4853 // fold (zext c1) -> c1
4854 // fold (aext c1) -> c1
4855 if (isa<ConstantSDNode>(N0))
4856 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4857
4858 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4859 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4860 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004861 EVT SVT = VT.getScalarType();
4862 if (!(VT.isVector() &&
4863 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004864 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004865 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004866
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004867 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004868 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004869 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4870 unsigned ShAmt = VTBits - EVTBits;
4871 SmallVector<SDValue, 8> Elts;
4872 unsigned NumElts = N0->getNumOperands();
4873 SDLoc DL(N);
4874
4875 for (unsigned i=0; i != NumElts; ++i) {
4876 SDValue Op = N0->getOperand(i);
4877 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004878 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004879 continue;
4880 }
4881
4882 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4883 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4884 if (Opcode == ISD::SIGN_EXTEND)
4885 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004886 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004887 else
4888 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004889 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004890 }
4891
Craig Topper48d114b2014-04-26 18:35:24 +00004892 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004893}
4894
Evan Chenge106e2f2007-10-29 19:58:20 +00004895// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004896// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004897// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004898// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004899static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004900 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004901 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004902 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004903 bool HasCopyToRegUses = false;
4904 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004905 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4906 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004907 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004908 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004909 if (User == N)
4910 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004911 if (UI.getUse().getResNo() != N0.getResNo())
4912 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004913 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004914 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004915 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4916 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4917 // Sign bits will be lost after a zext.
4918 return false;
4919 bool Add = false;
4920 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004921 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004922 if (UseOp == N0)
4923 continue;
4924 if (!isa<ConstantSDNode>(UseOp))
4925 return false;
4926 Add = true;
4927 }
4928 if (Add)
4929 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004930 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004931 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004932 // If truncates aren't free and there are users we can't
4933 // extend, it isn't worthwhile.
4934 if (!isTruncFree)
4935 return false;
4936 // Remember if this value is live-out.
4937 if (User->getOpcode() == ISD::CopyToReg)
4938 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004939 }
4940
4941 if (HasCopyToRegUses) {
4942 bool BothLiveOut = false;
4943 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4944 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004945 SDUse &Use = UI.getUse();
4946 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4947 BothLiveOut = true;
4948 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004949 }
4950 }
4951 if (BothLiveOut)
4952 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004953 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004954 return ExtendNodes.size();
4955 }
4956 return true;
4957}
4958
Craig Toppere0b71182013-07-13 07:43:40 +00004959void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004960 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004961 ISD::NodeType ExtType) {
4962 // Extend SetCC uses if necessary.
4963 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4964 SDNode *SetCC = SetCCs[i];
4965 SmallVector<SDValue, 4> Ops;
4966
4967 for (unsigned j = 0; j != 2; ++j) {
4968 SDValue SOp = SetCC->getOperand(j);
4969 if (SOp == Trunc)
4970 Ops.push_back(ExtLoad);
4971 else
4972 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4973 }
4974
4975 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00004976 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004977 }
4978}
4979
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004980SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4981 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004982 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004983
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004984 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4985 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004986 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004987
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004988 // fold (sext (sext x)) -> (sext x)
4989 // fold (sext (aext x)) -> (sext x)
4990 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004991 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004992 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004993
Chris Lattnerfce448f2007-02-26 03:13:59 +00004994 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004995 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4996 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004997 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4998 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004999 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5000 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005001 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005002 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005003 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005004 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005005 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005006 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005007
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005008 // See if the value being truncated is already sign extended. If so, just
5009 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005010 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005011 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5012 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5013 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005014 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005015
Chris Lattnerfce448f2007-02-26 03:13:59 +00005016 if (OpBits == DestBits) {
5017 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5018 // bits, it is already ready.
5019 if (NumSignBits > DestBits-MidBits)
5020 return Op;
5021 } else if (OpBits < DestBits) {
5022 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5023 // bits, just sext from i32.
5024 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005025 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005026 } else {
5027 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5028 // bits, just truncate to i32.
5029 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005030 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005031 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005032
Chris Lattnerfce448f2007-02-26 03:13:59 +00005033 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005034 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5035 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005036 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005037 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005038 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005039 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5040 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005041 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005042 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005043 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005044
Evan Chengbce7c472005-12-14 02:19:23 +00005045 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005046 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005047 // on vectors in one instruction. We only perform this transformation on
5048 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005049 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005050 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005051 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005052 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005053 bool DoXform = true;
5054 SmallVector<SDNode*, 4> SetCCs;
5055 if (!N0.hasOneUse())
5056 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5057 if (DoXform) {
5058 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005059 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005060 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005061 LN0->getBasePtr(), N0.getValueType(),
5062 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005063 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005064 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005065 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005066 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005067 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005068 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005069 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005070 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005071 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005072
5073 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5074 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005075 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5076 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005077 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005078 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005079 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005080 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005081 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005082 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005083 LN0->getBasePtr(), MemVT,
5084 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005085 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005086 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005087 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005088 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005089 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005090 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005091 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005092 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005093
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005094 // fold (sext (and/or/xor (load x), cst)) ->
5095 // (and/or/xor (sextload x), (sext cst))
5096 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5097 N0.getOpcode() == ISD::XOR) &&
5098 isa<LoadSDNode>(N0.getOperand(0)) &&
5099 N0.getOperand(1).getOpcode() == ISD::Constant &&
5100 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5101 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5102 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005103 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005104 bool DoXform = true;
5105 SmallVector<SDNode*, 4> SetCCs;
5106 if (!N0.hasOneUse())
5107 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5108 SetCCs, TLI);
5109 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005110 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005111 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005112 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005113 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005114 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5115 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005116 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005117 ExtLoad, DAG.getConstant(Mask, VT));
5118 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005119 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005120 N0.getOperand(0).getValueType(), ExtLoad);
5121 CombineTo(N, And);
5122 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005123 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005124 ISD::SIGN_EXTEND);
5125 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5126 }
5127 }
5128 }
5129
Chris Lattner65786b02007-04-11 05:32:27 +00005130 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005131 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005132 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005133 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005134 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005135 TLI.getBooleanContents(N0VT) ==
5136 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005137 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5138 // of the same size as the compared operands. Only optimize sext(setcc())
5139 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005140 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005141
5142 // We know that the # elements of the results is the same as the
5143 // # elements of the compare (and the # elements of the compare result
5144 // for that matter). Check to see that they are the same size. If so,
5145 // we know that the element size of the sext'd result matches the
5146 // element size of the compare operands.
5147 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005148 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005149 N0.getOperand(1),
5150 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005151
Dan Gohmane82c25e2010-04-30 17:19:19 +00005152 // If the desired elements are smaller or larger than the source
5153 // elements we can use a matching integer vector type and then
5154 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005155 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005156 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005157 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005158 N0.getOperand(0), N0.getOperand(1),
5159 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005160 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005161 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005162 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005163
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005164 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005165 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005166 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005167 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005168 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005169 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005170 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005171 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005172 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005173
5174 if (!VT.isVector()) {
5175 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5176 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5177 SDLoc DL(N);
5178 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5179 SDValue SetCC = DAG.getSetCC(DL,
5180 SetCCVT,
5181 N0.getOperand(0), N0.getOperand(1), CC);
5182 EVT SelectVT = getSetCCResultType(VT);
5183 return DAG.getSelect(DL, VT,
5184 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5185 NegOne, DAG.getConstant(0, VT));
5186
5187 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005188 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005189 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005190
Dan Gohman3eb10f72008-04-28 16:58:24 +00005191 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005192 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005193 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005194 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005195
Evan Chengf1005572010-04-28 07:10:39 +00005196 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005197}
5198
Rafael Espindola8f62b322012-04-09 16:06:03 +00005199// isTruncateOf - If N is a truncate of some other value, return true, record
5200// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5201// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005202// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005203static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5204 APInt &KnownZero) {
5205 APInt KnownOne;
5206 if (N->getOpcode() == ISD::TRUNCATE) {
5207 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005208 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005209 return true;
5210 }
5211
5212 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5213 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5214 return false;
5215
5216 SDValue Op0 = N->getOperand(0);
5217 SDValue Op1 = N->getOperand(1);
5218 assert(Op0.getValueType() == Op1.getValueType());
5219
5220 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5221 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005222 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005223 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005224 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005225 Op = Op0;
5226 else
5227 return false;
5228
Jay Foada0653a32014-05-14 21:14:37 +00005229 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005230
5231 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5232 return false;
5233
5234 return true;
5235}
5236
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005237SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5238 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005239 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005240
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005241 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5242 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005243 return SDValue(Res, 0);
5244
Nate Begeman21158fc2005-09-01 00:19:25 +00005245 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005246 // fold (zext (aext x)) -> (zext x)
5247 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005248 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005249 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005250
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005251 // fold (zext (truncate x)) -> (zext x) or
5252 // (zext (truncate x)) -> (truncate x)
5253 // This is valid when the truncated bits of x are already zero.
5254 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005255 SDValue Op;
5256 APInt KnownZero;
5257 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5258 APInt TruncatedBits =
5259 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5260 APInt(Op.getValueSizeInBits(), 0) :
5261 APInt::getBitsSet(Op.getValueSizeInBits(),
5262 N0.getValueSizeInBits(),
5263 std::min(Op.getValueSizeInBits(),
5264 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005265 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005266 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005267 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005268 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005269 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005270
5271 return Op;
5272 }
5273 }
5274
Evan Cheng464dc9b2007-03-22 01:54:19 +00005275 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5276 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005277 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005278 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5279 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005280 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5281 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005282 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005283 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005284 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005285 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005286 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005287 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005288 }
5289
Chris Lattnera31f0a62006-09-21 06:00:20 +00005290 // fold (zext (truncate x)) -> (and x, mask)
5291 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005292 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005293
5294 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5295 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5296 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5297 if (NarrowLoad.getNode()) {
5298 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5299 if (NarrowLoad.getNode() != N0.getNode()) {
5300 CombineTo(N0.getNode(), NarrowLoad);
5301 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005302 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005303 }
5304 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5305 }
5306
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005307 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005308 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005309 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005310 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005311 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005312 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005313 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005314 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005315 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005316 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005317 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005318
Dan Gohmanad3e5492009-04-08 00:15:30 +00005319 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5320 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005321 if (N0.getOpcode() == ISD::AND &&
5322 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005323 N0.getOperand(1).getOpcode() == ISD::Constant &&
5324 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5325 N0.getValueType()) ||
5326 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005327 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005328 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005329 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005330 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005331 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005332 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005333 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005334 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005335 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005336 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005337 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005338
Evan Chengbce7c472005-12-14 02:19:23 +00005339 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005340 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005341 // on vectors in one instruction. We only perform this transformation on
5342 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005343 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005344 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005345 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005346 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005347 bool DoXform = true;
5348 SmallVector<SDNode*, 4> SetCCs;
5349 if (!N0.hasOneUse())
5350 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5351 if (DoXform) {
5352 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005353 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005354 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005355 LN0->getBasePtr(), N0.getValueType(),
5356 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005357 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005358 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005359 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005360 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005361
Andrew Trickef9de2a2013-05-25 02:42:55 +00005362 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005363 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005364 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005365 }
Evan Chengbce7c472005-12-14 02:19:23 +00005366 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005367
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005368 // fold (zext (and/or/xor (load x), cst)) ->
5369 // (and/or/xor (zextload x), (zext cst))
5370 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5371 N0.getOpcode() == ISD::XOR) &&
5372 isa<LoadSDNode>(N0.getOperand(0)) &&
5373 N0.getOperand(1).getOpcode() == ISD::Constant &&
5374 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5375 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5376 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005377 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005378 bool DoXform = true;
5379 SmallVector<SDNode*, 4> SetCCs;
5380 if (!N0.hasOneUse())
5381 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5382 SetCCs, TLI);
5383 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005384 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005385 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005386 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005387 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005388 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5389 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005390 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005391 ExtLoad, DAG.getConstant(Mask, VT));
5392 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005393 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005394 N0.getOperand(0).getValueType(), ExtLoad);
5395 CombineTo(N, And);
5396 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005397 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005398 ISD::ZERO_EXTEND);
5399 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5400 }
5401 }
5402 }
5403
Chris Lattner7dac1082005-12-14 19:05:06 +00005404 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5405 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005406 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5407 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005408 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005409 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005410 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005411 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005412 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005413 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005414 LN0->getBasePtr(), MemVT,
5415 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005416 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005417 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005418 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005419 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005420 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005421 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005422 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005423 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005424
Chris Lattner65786b02007-04-11 05:32:27 +00005425 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005426 if (!LegalOperations && VT.isVector() &&
5427 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005428 EVT N0VT = N0.getOperand(0).getValueType();
5429 if (getSetCCResultType(N0VT) == N0.getValueType())
5430 return SDValue();
5431
Evan Chengabd0ad52010-05-19 01:08:17 +00005432 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5433 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005434 EVT EltVT = VT.getVectorElementType();
5435 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5436 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005437 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005438 // We know that the # elements of the results is the same as the
5439 // # elements of the compare (and the # elements of the compare result
5440 // for that matter). Check to see that they are the same size. If so,
5441 // we know that the element size of the sext'd result matches the
5442 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005443 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5444 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005445 N0.getOperand(1),
5446 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005447 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005448 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005449
5450 // If the desired elements are smaller or larger than the source
5451 // elements we can use a matching integer vector type and then
5452 // truncate/sign extend
5453 EVT MatchingElementType =
5454 EVT::getIntegerVT(*DAG.getContext(),
5455 N0VT.getScalarType().getSizeInBits());
5456 EVT MatchingVectorType =
5457 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5458 N0VT.getVectorNumElements());
5459 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005460 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005461 N0.getOperand(1),
5462 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005463 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5464 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005465 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005466 }
5467
5468 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005469 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005470 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005471 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005472 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005473 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005474 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005475
Evan Cheng852c4862009-12-15 03:00:32 +00005476 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005477 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005478 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005479 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5480 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005481 SDValue ShAmt = N0.getOperand(1);
5482 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005483 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005484 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005485 // If the original shl may be shifting out bits, do not perform this
5486 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005487 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5488 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5489 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005490 return SDValue();
5491 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005492
Andrew Trickef9de2a2013-05-25 02:42:55 +00005493 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005494
5495 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005496 if (VT.getSizeInBits() >= 256)
5497 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005498
Chris Lattnere95d1952011-02-13 19:09:16 +00005499 return DAG.getNode(N0.getOpcode(), DL, VT,
5500 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5501 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005502 }
5503
Evan Chengf1005572010-04-28 07:10:39 +00005504 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005505}
5506
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005507SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5508 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005509 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005510
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005511 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5512 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005513 return SDValue(Res, 0);
5514
Chris Lattner812646a2006-05-05 05:58:59 +00005515 // fold (aext (aext x)) -> (aext x)
5516 // fold (aext (zext x)) -> (zext x)
5517 // fold (aext (sext x)) -> (sext x)
5518 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5519 N0.getOpcode() == ISD::ZERO_EXTEND ||
5520 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005521 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005522
Evan Cheng464dc9b2007-03-22 01:54:19 +00005523 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5524 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5525 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005526 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5527 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005528 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5529 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005530 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005531 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005532 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005533 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005534 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005535 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005536 }
5537
Chris Lattner8746e2c2006-09-20 06:29:17 +00005538 // fold (aext (truncate x))
5539 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005540 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005541 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005542 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005543 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005544 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5545 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005546 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005547
Dan Gohmanad3e5492009-04-08 00:15:30 +00005548 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5549 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005550 if (N0.getOpcode() == ISD::AND &&
5551 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005552 N0.getOperand(1).getOpcode() == ISD::Constant &&
5553 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5554 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005555 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005556 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005557 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005558 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005559 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005560 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005561 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005562 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005563 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005564 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005565 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005566
Chris Lattner812646a2006-05-05 05:58:59 +00005567 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005568 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005569 // on vectors in one instruction. We only perform this transformation on
5570 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005571 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005572 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005573 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005574 bool DoXform = true;
5575 SmallVector<SDNode*, 4> SetCCs;
5576 if (!N0.hasOneUse())
5577 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5578 if (DoXform) {
5579 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005580 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005581 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005582 LN0->getBasePtr(), N0.getValueType(),
5583 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005584 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005585 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005586 N0.getValueType(), ExtLoad);
5587 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005588 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005589 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005590 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5591 }
Chris Lattner812646a2006-05-05 05:58:59 +00005592 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005593
Chris Lattner812646a2006-05-05 05:58:59 +00005594 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5595 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5596 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005597 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005598 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005599 N0.hasOneUse()) {
5600 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005601 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005602 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005603 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5604 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5605 VT, LN0->getChain(), LN0->getBasePtr(),
5606 MemVT, LN0->getMemOperand());
5607 CombineTo(N, ExtLoad);
5608 CombineTo(N0.getNode(),
5609 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5610 N0.getValueType(), ExtLoad),
5611 ExtLoad.getValue(1));
5612 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5613 }
Chris Lattner812646a2006-05-05 05:58:59 +00005614 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005615
Chris Lattner65786b02007-04-11 05:32:27 +00005616 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005617 // For vectors:
5618 // aext(setcc) -> vsetcc
5619 // aext(setcc) -> truncate(vsetcc)
5620 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005621 // Only do this before legalize for now.
5622 if (VT.isVector() && !LegalOperations) {
5623 EVT N0VT = N0.getOperand(0).getValueType();
5624 // We know that the # elements of the results is the same as the
5625 // # elements of the compare (and the # elements of the compare result
5626 // for that matter). Check to see that they are the same size. If so,
5627 // we know that the element size of the sext'd result matches the
5628 // element size of the compare operands.
5629 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005630 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005631 N0.getOperand(1),
5632 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005633 // If the desired elements are smaller or larger than the source
5634 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005635 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005636 else {
Hao Liuc636d152014-04-22 09:57:06 +00005637 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005638 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005639 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005640 N0.getOperand(1),
5641 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005642 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005643 }
5644 }
5645
5646 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005647 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005648 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005649 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005650 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005651 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005652 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005653 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005654
Evan Chengf1005572010-04-28 07:10:39 +00005655 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005656}
5657
Chris Lattner5e6fe052007-10-13 06:35:54 +00005658/// GetDemandedBits - See if the specified operand can be simplified with the
5659/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005660/// simpler operand, otherwise return a null SDValue.
5661SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005662 switch (V.getOpcode()) {
5663 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005664 case ISD::Constant: {
5665 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005666 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005667 const APInt &CVal = CV->getAPIntValue();
5668 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005669 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005670 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005671 break;
5672 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005673 case ISD::OR:
5674 case ISD::XOR:
5675 // If the LHS or RHS don't contribute bits to the or, drop them.
5676 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5677 return V.getOperand(1);
5678 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5679 return V.getOperand(0);
5680 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005681 case ISD::SRL:
5682 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005683 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005684 break;
5685 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5686 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005687 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005688
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005689 // Watch out for shift count overflow though.
5690 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005691 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005692 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005693 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005694 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005695 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005696 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005697 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005698 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005699}
5700
Evan Cheng464dc9b2007-03-22 01:54:19 +00005701/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5702/// bits and then truncated to a narrower type and where N is a multiple
5703/// of number of bits of the narrower type, transform it to a narrower load
5704/// from address + N / num of bits of new type. If the result is to be
5705/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005706SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005707 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005708
Evan Cheng464dc9b2007-03-22 01:54:19 +00005709 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005710 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005711 EVT VT = N->getValueType(0);
5712 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005713
Dan Gohman550c9af2008-08-14 20:04:46 +00005714 // This transformation isn't valid for vector loads.
5715 if (VT.isVector())
5716 return SDValue();
5717
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005718 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005719 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005720 if (Opc == ISD::SIGN_EXTEND_INREG) {
5721 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005722 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005723 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005724 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005725 ExtType = ISD::ZEXTLOAD;
5726 N0 = SDValue(N, 0);
5727 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5728 if (!N01) return SDValue();
5729 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5730 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005731 }
Richard Osborne272e0842011-01-31 17:41:44 +00005732 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5733 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005734
Owen Anderson53aa7a92009-08-10 22:56:29 +00005735 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005736
Chris Lattner9a499e92010-12-22 08:01:44 +00005737 // Do not generate loads of non-round integer types since these can
5738 // be expensive (and would be wrong if the type is not byte sized).
5739 if (!ExtVT.isRound())
5740 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005741
Evan Cheng464dc9b2007-03-22 01:54:19 +00005742 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005743 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005744 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005745 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005746 // Is the shift amount a multiple of size of VT?
5747 if ((ShAmt & (EVTBits-1)) == 0) {
5748 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005749 // Is the load width a multiple of size of VT?
5750 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005751 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005752 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005753
Chris Lattnercafc1e62010-12-22 08:02:57 +00005754 // At this point, we must have a load or else we can't do the transform.
5755 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005756
Chandler Carruthb27041c2012-12-11 00:36:57 +00005757 // Because a SRL must be assumed to *need* to zero-extend the high bits
5758 // (as opposed to anyext the high bits), we can't combine the zextload
5759 // lowering of SRL and an sextload.
5760 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5761 return SDValue();
5762
Chris Lattnera2050552010-10-01 05:36:09 +00005763 // If the shift amount is larger than the input type then we're not
5764 // accessing any of the loaded bytes. If the load was a zextload/extload
5765 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005766 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005767 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005768 }
5769 }
5770
Dan Gohman68fb0042010-11-03 01:47:46 +00005771 // If the load is shifted left (and the result isn't shifted back right),
5772 // we can fold the truncate through the shift.
5773 unsigned ShLeftAmt = 0;
5774 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005775 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005776 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5777 ShLeftAmt = N01->getZExtValue();
5778 N0 = N0.getOperand(0);
5779 }
5780 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005781
Chris Lattner222374d2010-12-22 07:36:50 +00005782 // If we haven't found a load, we can't narrow it. Don't transform one with
5783 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005784 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5785 return SDValue();
5786
5787 // Don't change the width of a volatile load.
5788 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5789 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005790 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005791
Chris Lattner9a499e92010-12-22 08:01:44 +00005792 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005793 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005794 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005795
Bill Schmidtd006c692013-01-14 22:04:38 +00005796 // For the transform to be legal, the load must produce only two values
5797 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005798 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005799 // transformation is not equivalent, and the downstream logic to replace
5800 // uses gets things wrong.
5801 if (LN0->getNumValues() > 2)
5802 return SDValue();
5803
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005804 // If the load that we're shrinking is an extload and we're not just
5805 // discarding the extension we can't simply shrink the load. Bail.
5806 // TODO: It would be possible to merge the extensions in some cases.
5807 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5808 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5809 return SDValue();
5810
Chris Lattner222374d2010-12-22 07:36:50 +00005811 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005812
Evan Cheng4c6f9172012-06-26 01:19:33 +00005813 if (PtrType == MVT::Untyped || PtrType.isExtended())
5814 // It's not possible to generate a constant of extended or untyped type.
5815 return SDValue();
5816
Chris Lattner222374d2010-12-22 07:36:50 +00005817 // For big endian targets, we need to adjust the offset to the pointer to
5818 // load the correct bytes.
5819 if (TLI.isBigEndian()) {
5820 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5821 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5822 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005823 }
5824
Chris Lattner222374d2010-12-22 07:36:50 +00005825 uint64_t PtrOff = ShAmt / 8;
5826 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005827 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005828 PtrType, LN0->getBasePtr(),
5829 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005830 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00005831
Chris Lattner9a499e92010-12-22 08:01:44 +00005832 SDValue Load;
5833 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005834 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005835 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005836 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00005837 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005838 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005839 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005840 LN0->getPointerInfo().getWithOffset(PtrOff),
5841 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00005842 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005843
5844 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005845 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005846 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005847
5848 // Shift the result left, if we've swallowed a left shift.
5849 SDValue Result = Load;
5850 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005851 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005852 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5853 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005854 // If the shift amount is as large as the result size (but, presumably,
5855 // no larger than the source) then the useful bits of the result are
5856 // zero; we can't simply return the shortened shift, because the result
5857 // of that operation is undefined.
5858 if (ShLeftAmt >= VT.getSizeInBits())
5859 Result = DAG.getConstant(0, VT);
5860 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005861 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005862 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005863 }
5864
5865 // Return the new loaded value.
5866 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005867}
5868
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005869SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5870 SDValue N0 = N->getOperand(0);
5871 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005872 EVT VT = N->getValueType(0);
5873 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005874 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005875 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005876
Nate Begeman21158fc2005-09-01 00:19:25 +00005877 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005878 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005879 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005880
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005881 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005882 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005883 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005884
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005885 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5886 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005887 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005888 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005889 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005890
Dan Gohman345d63c2008-07-31 00:50:31 +00005891 // fold (sext_in_reg (sext x)) -> (sext x)
5892 // fold (sext_in_reg (aext x)) -> (sext x)
5893 // if x is small enough.
5894 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5895 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005896 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5897 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005898 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005899 }
5900
Chris Lattner9ad59152007-04-17 19:03:21 +00005901 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005902 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005903 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005904
Chris Lattner9ad59152007-04-17 19:03:21 +00005905 // fold operands of sext_in_reg based on knowledge that the top bits are not
5906 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005907 if (SimplifyDemandedBits(SDValue(N, 0)))
5908 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005909
Evan Cheng464dc9b2007-03-22 01:54:19 +00005910 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5911 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005912 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005913 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005914 return NarrowLoad;
5915
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005916 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005917 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005918 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5919 if (N0.getOpcode() == ISD::SRL) {
5920 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005921 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005922 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005923 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005924 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005925 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005926 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005927 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005928 }
5929 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005930
Nate Begeman02b23c62005-10-13 03:11:28 +00005931 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005932 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005933 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005934 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005935 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005936 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005937 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005938 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005939 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005940 LN0->getBasePtr(), EVT,
5941 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005942 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005943 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005944 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005945 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005946 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005947 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005948 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005949 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005950 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005951 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005952 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005953 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005954 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005955 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005956 LN0->getBasePtr(), EVT,
5957 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005958 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005959 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005961 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005962
5963 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5964 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5965 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5966 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005967 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005968 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005969 BSwap, N1);
5970 }
5971
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005972 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5973 // into a build_vector.
5974 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5975 SmallVector<SDValue, 8> Elts;
5976 unsigned NumElts = N0->getNumOperands();
5977 unsigned ShAmt = VTBits - EVTBits;
5978
5979 for (unsigned i = 0; i != NumElts; ++i) {
5980 SDValue Op = N0->getOperand(i);
5981 if (Op->getOpcode() == ISD::UNDEF) {
5982 Elts.push_back(Op);
5983 continue;
5984 }
5985
5986 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005987 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5988 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005989 Op.getValueType()));
5990 }
5991
Craig Topper48d114b2014-04-26 18:35:24 +00005992 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005993 }
5994
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005995 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005996}
5997
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005998SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5999 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006000 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006001 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006002
6003 // noop truncate
6004 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006005 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006006 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006007 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006008 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006009 // fold (truncate (truncate x)) -> (truncate x)
6010 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006011 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006012 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006013 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6014 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006015 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006016 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006017 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006018 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006019 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006020 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006021 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006022 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006023 // if the source and dest are the same type, we can drop both the extend
6024 // and the truncate.
6025 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006026 }
Evan Chengd63baea2007-03-21 20:14:05 +00006027
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006028 // Fold extract-and-trunc into a narrow extract. For example:
6029 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6030 // i32 y = TRUNCATE(i64 x)
6031 // -- becomes --
6032 // v16i8 b = BITCAST (v2i64 val)
6033 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6034 //
6035 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006036 // creates this pattern) and before operation legalization after which
6037 // we need to be more careful about the vector instructions that we generate.
6038 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006039 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006040
6041 EVT VecTy = N0.getOperand(0).getValueType();
6042 EVT ExTy = N0.getValueType();
6043 EVT TrTy = N->getValueType(0);
6044
6045 unsigned NumElem = VecTy.getVectorNumElements();
6046 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6047
6048 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6049 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6050
6051 SDValue EltNo = N0->getOperand(1);
6052 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6053 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006054 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006055 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6056
Andrew Trickef9de2a2013-05-25 02:42:55 +00006057 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006058 NVT, N0.getOperand(0));
6059
6060 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006061 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006062 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006063 }
6064 }
6065
Matt Arsenault3332b702014-07-10 18:21:04 +00006066 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6067 if (N0.getOpcode() == ISD::SELECT) {
6068 EVT SrcVT = N0.getValueType();
6069 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6070 TLI.isTruncateFree(SrcVT, VT)) {
6071 SDLoc SL(N0);
6072 SDValue Cond = N0.getOperand(0);
6073 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6074 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6075 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6076 }
6077 }
6078
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006079 // Fold a series of buildvector, bitcast, and truncate if possible.
6080 // For example fold
6081 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6082 // (2xi32 (buildvector x, y)).
6083 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6084 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6085 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6086 N0.getOperand(0).hasOneUse()) {
6087
6088 SDValue BuildVect = N0.getOperand(0);
6089 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6090 EVT TruncVecEltTy = VT.getVectorElementType();
6091
6092 // Check that the element types match.
6093 if (BuildVectEltTy == TruncVecEltTy) {
6094 // Now we only need to compute the offset of the truncated elements.
6095 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6096 unsigned TruncVecNumElts = VT.getVectorNumElements();
6097 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6098
6099 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6100 "Invalid number of elements");
6101
6102 SmallVector<SDValue, 8> Opnds;
6103 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6104 Opnds.push_back(BuildVect.getOperand(i));
6105
Craig Topper48d114b2014-04-26 18:35:24 +00006106 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006107 }
6108 }
6109
Chris Lattner5e6fe052007-10-13 06:35:54 +00006110 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006111 // only the low bits are being used.
6112 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006113 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006114 // may have different active low bits.
6115 if (!VT.isVector()) {
6116 SDValue Shorter =
6117 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6118 VT.getSizeInBits()));
6119 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006120 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006121 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006122 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006123 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006124 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6125 SDValue Reduced = ReduceLoadWidth(N);
6126 if (Reduced.getNode())
6127 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006128 // Handle the case where the load remains an extending load even
6129 // after truncation.
6130 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6131 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6132 if (!LN0->isVolatile() &&
6133 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6134 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6135 VT, LN0->getChain(), LN0->getBasePtr(),
6136 LN0->getMemoryVT(),
6137 LN0->getMemOperand());
6138 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6139 return NewLoad;
6140 }
6141 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006142 }
Michael Liao3ac82012012-10-17 23:45:54 +00006143 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6144 // where ... are all 'undef'.
6145 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6146 SmallVector<EVT, 8> VTs;
6147 SDValue V;
6148 unsigned Idx = 0;
6149 unsigned NumDefs = 0;
6150
6151 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6152 SDValue X = N0.getOperand(i);
6153 if (X.getOpcode() != ISD::UNDEF) {
6154 V = X;
6155 Idx = i;
6156 NumDefs++;
6157 }
6158 // Stop if more than one members are non-undef.
6159 if (NumDefs > 1)
6160 break;
6161 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6162 VT.getVectorElementType(),
6163 X.getValueType().getVectorNumElements()));
6164 }
6165
6166 if (NumDefs == 0)
6167 return DAG.getUNDEF(VT);
6168
6169 if (NumDefs == 1) {
6170 assert(V.getNode() && "The single defined operand is empty!");
6171 SmallVector<SDValue, 8> Opnds;
6172 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6173 if (i != Idx) {
6174 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6175 continue;
6176 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006177 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006178 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006179 Opnds.push_back(NV);
6180 }
Craig Topper48d114b2014-04-26 18:35:24 +00006181 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006182 }
6183 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006184
6185 // Simplify the operands using demanded-bits information.
6186 if (!VT.isVector() &&
6187 SimplifyDemandedBits(SDValue(N, 0)))
6188 return SDValue(N, 0);
6189
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006190 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006191}
6192
Evan Chengb980f6f2008-05-12 23:04:07 +00006193static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006194 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006195 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006196 return Elt.getNode();
6197 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006198}
6199
6200/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006201/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006202SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006203 assert(N->getOpcode() == ISD::BUILD_PAIR);
6204
Nate Begeman624690c2009-06-05 21:37:30 +00006205 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6206 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006207 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006208 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006209 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006210 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006211
Evan Chengb980f6f2008-05-12 23:04:07 +00006212 if (ISD::isNON_EXTLoad(LD2) &&
6213 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006214 // If both are volatile this would reduce the number of volatile loads.
6215 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006216 !LD1->isVolatile() &&
6217 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006218 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006219 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006220 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006221 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006222
Duncan Sands8651e9c2008-06-13 19:07:40 +00006223 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006224 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006225 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006226 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006227 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006228 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006229
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006230 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006231}
6232
Wesley Peck527da1b2010-11-23 03:31:01 +00006233SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006234 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006235 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006236
Dan Gohmana8665142007-06-25 16:23:39 +00006237 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6238 // Only do this before legalize, since afterward the target may be depending
6239 // on the bitconvert.
6240 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006241 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006242 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006243 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006244 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006245
Owen Anderson53aa7a92009-08-10 22:56:29 +00006246 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006247 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006248 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006249 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006250 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006251 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006252
Dan Gohman921ddd62008-09-05 01:58:21 +00006253 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006254 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006255 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006256 if (Res.getNode() != N) {
6257 if (!LegalOperations ||
6258 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6259 return Res;
6260
6261 // Folding it resulted in an illegal node, and it's too late to
6262 // do that. Clean up the old node and forego the transformation.
6263 // Ideally this won't happen very often, because instcombine
6264 // and the earlier dagcombine runs (where illegal nodes are
6265 // permitted) should have folded most of them already.
Chandler Carruth18066972014-08-02 10:02:07 +00006266 deleteAndRecombine(Res.getNode());
Dan Gohman733a64d2009-08-10 23:15:10 +00006267 }
Chris Lattnera1874602005-12-23 05:30:37 +00006268 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006269
Bill Wendling4e0a6152009-01-30 22:44:24 +00006270 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006271 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006272 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006273 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006274
Chris Lattner54560f62005-12-23 05:44:41 +00006275 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006276 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006277 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006278 // Do not change the width of a volatile load.
6279 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006280 // Do not remove the cast if the types differ in endian layout.
6281 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6282 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006283 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6284 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006285 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006286 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006287 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006288 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006289
Evan Chenga4cf58a2007-05-07 21:27:48 +00006290 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006291 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006292 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006293 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006294 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006295 LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006296 AddToWorklist(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006297 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006298 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006299 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006300 Load.getValue(1));
6301 return Load;
6302 }
Chris Lattner54560f62005-12-23 05:44:41 +00006303 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006304
Bill Wendling4e0a6152009-01-30 22:44:24 +00006305 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6306 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006307 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006308 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6309 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006310 N0.getNode()->hasOneUse() && VT.isInteger() &&
6311 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006312 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006313 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006314 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006315
Duncan Sands13237ac2008-06-06 12:08:01 +00006316 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006317 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006318 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006319 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006320 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006321 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006322 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006323 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006324
Bill Wendling4e0a6152009-01-30 22:44:24 +00006325 // fold (bitconvert (fcopysign cst, x)) ->
6326 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6327 // Note that we don't handle (copysign x, cst) because this can always be
6328 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006329 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006330 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006331 VT.isInteger() && !VT.isVector()) {
6332 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006333 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006334 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006335 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006336 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006337 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006338
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006339 // If X has a different width than the result/lhs, sext it or truncate it.
6340 unsigned VTWidth = VT.getSizeInBits();
6341 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006342 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006343 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006344 } else if (OrigXWidth > VTWidth) {
6345 // To get the sign bit in the right place, we have to shift it right
6346 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006347 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006348 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006349 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006350 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006351 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006352 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006353 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006354
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006355 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006356 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006357 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006358 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006359
Andrew Trickef9de2a2013-05-25 02:42:55 +00006360 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006361 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006362 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006363 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006364 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006365
Andrew Trickef9de2a2013-05-25 02:42:55 +00006366 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006367 }
Chris Lattner888560d2008-01-27 17:42:27 +00006368 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006369
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006370 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006371 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006372 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6373 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006374 return CombineLD;
6375 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006376
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006377 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006378}
6379
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006380SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006381 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006382 return CombineConsecutiveLoads(N, VT);
6383}
6384
Wesley Peck527da1b2010-11-23 03:31:01 +00006385/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006386/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006387/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006388SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006389ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006390 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006391
Chris Lattnere4e64b62006-04-02 02:53:43 +00006392 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006393 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006394
Duncan Sands13237ac2008-06-06 12:08:01 +00006395 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6396 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006397
Chris Lattnere4e64b62006-04-02 02:53:43 +00006398 // If this is a conversion of N elements of one type to N elements of another
6399 // type, convert each element. This handles FP<->INT cases.
6400 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006401 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6402 BV->getValueType(0).getVectorNumElements());
6403
6404 // Due to the FP element handling below calling this routine recursively,
6405 // we can end up with a scalar-to-vector node here.
6406 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006407 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6408 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006409 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006410
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006411 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006412 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006413 SDValue Op = BV->getOperand(i);
6414 // If the vector element type is not legal, the BUILD_VECTOR operands
6415 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006416 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006417 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6418 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006419 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006420 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006421 }
Craig Topper48d114b2014-04-26 18:35:24 +00006422 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006423 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006424
Chris Lattnere4e64b62006-04-02 02:53:43 +00006425 // Otherwise, we're growing or shrinking the elements. To avoid having to
6426 // handle annoying details of growing/shrinking FP values, we convert them to
6427 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006428 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006429 // Convert the input float vector to a int vector where the elements are the
6430 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006431 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006432 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006433 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006434 SrcEltVT = IntVT;
6435 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006436
Chris Lattnere4e64b62006-04-02 02:53:43 +00006437 // Now we know the input is an integer vector. If the output is a FP type,
6438 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006439 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006440 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006441 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006442 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006443
Chris Lattnere4e64b62006-04-02 02:53:43 +00006444 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006445 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006446 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006447
Chris Lattnere4e64b62006-04-02 02:53:43 +00006448 // Okay, we know the src/dst types are both integers of differing types.
6449 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006450 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006451 if (SrcBitSize < DstBitSize) {
6452 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006453
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006454 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006455 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006456 i += NumInputsPerOutput) {
6457 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006458 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006459 bool EltIsUndef = true;
6460 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6461 // Shift the previously computed bits over.
6462 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006463 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006464 if (Op.getOpcode() == ISD::UNDEF) continue;
6465 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006466
Jay Foad583abbc2010-12-07 08:25:19 +00006467 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006468 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006469 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006470
Chris Lattnere4e64b62006-04-02 02:53:43 +00006471 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006472 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006473 else
6474 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6475 }
6476
Owen Anderson117c9e82009-08-12 00:36:31 +00006477 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006478 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006479 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006480
Chris Lattnere4e64b62006-04-02 02:53:43 +00006481 // Finally, this must be the case where we are shrinking elements: each input
6482 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006483 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006484 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006485 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6486 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006487 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006488
Dan Gohmana8665142007-06-25 16:23:39 +00006489 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006490 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6491 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006492 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006493 continue;
6494 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006495
Jay Foad583abbc2010-12-07 08:25:19 +00006496 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6497 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006498
Chris Lattnere4e64b62006-04-02 02:53:43 +00006499 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006500 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006501 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006502 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006503 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006504 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006505 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006506 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006507 }
6508
6509 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006510 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006511 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6512 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006513
Craig Topper48d114b2014-04-26 18:35:24 +00006514 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006515}
6516
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006517SDValue DAGCombiner::visitFADD(SDNode *N) {
6518 SDValue N0 = N->getOperand(0);
6519 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006520 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6521 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006522 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006523
Dan Gohmana8665142007-06-25 16:23:39 +00006524 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006525 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006526 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006527 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006528 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006529
Lang Hamesa33db652012-06-14 20:37:15 +00006530 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006531 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006532 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006533 // canonicalize constant to RHS
6534 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006535 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006536 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006537 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6538 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006539 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006540 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006541 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006542 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006543 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006544 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006545 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006546 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006547 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006548 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006549 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006550
Chris Lattner0199fd62007-01-08 23:04:05 +00006551 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006552 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6553 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6554 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006555 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6556 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006557 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006558
Shuxin Yang93b1f122013-03-25 22:52:29 +00006559 // No FP constant should be created after legalization as Instruction
6560 // Selection pass has hard time in dealing with FP constant.
6561 //
6562 // We don't need test this condition for transformation like following, as
6563 // the DAG being transformed implies it is legal to take FP constant as
6564 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006565 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006566 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006567 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006568 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6569
Owen Andersonb351c8d2012-11-01 02:00:53 +00006570 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006571 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006572 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006573 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006574
6575 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006576 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006577 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006578 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006579
Owen Andersoncc61f872012-08-30 23:35:16 +00006580 // In unsafe math mode, we can fold chains of FADD's of the same value
6581 // into multiplications. This transform is not safe in general because
6582 // we are reducing the number of rounding steps.
6583 if (DAG.getTarget().Options.UnsafeFPMath &&
6584 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6585 !N0CFP && !N1CFP) {
6586 if (N0.getOpcode() == ISD::FMUL) {
6587 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6588 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6589
Stephen Line31f2d22013-06-14 18:17:35 +00006590 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006591 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006592 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006593 SDValue(CFP00, 0),
6594 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006596 N1, NewCFP);
6597 }
6598
Stephen Line31f2d22013-06-14 18:17:35 +00006599 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006600 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006601 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006602 SDValue(CFP01, 0),
6603 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006604 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006605 N1, NewCFP);
6606 }
6607
Stephen Line31f2d22013-06-14 18:17:35 +00006608 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006609 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6610 N1.getOperand(0) == N1.getOperand(1) &&
6611 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006612 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006613 SDValue(CFP00, 0),
6614 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006615 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006616 N0.getOperand(1), NewCFP);
6617 }
6618
Stephen Line31f2d22013-06-14 18:17:35 +00006619 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006620 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6621 N1.getOperand(0) == N1.getOperand(1) &&
6622 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006623 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006624 SDValue(CFP01, 0),
6625 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006626 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006627 N0.getOperand(0), NewCFP);
6628 }
6629 }
6630
6631 if (N1.getOpcode() == ISD::FMUL) {
6632 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6633 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6634
Stephen Line31f2d22013-06-14 18:17:35 +00006635 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006636 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006637 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006638 SDValue(CFP10, 0),
6639 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006640 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006641 N0, NewCFP);
6642 }
6643
Stephen Line31f2d22013-06-14 18:17:35 +00006644 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006645 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006646 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006647 SDValue(CFP11, 0),
6648 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006649 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006650 N0, NewCFP);
6651 }
6652
Owen Andersoncc61f872012-08-30 23:35:16 +00006653
Stephen Line31f2d22013-06-14 18:17:35 +00006654 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6655 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6656 N0.getOperand(0) == N0.getOperand(1) &&
6657 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006658 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006659 SDValue(CFP10, 0),
6660 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006661 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006662 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006663 }
6664
Stephen Line31f2d22013-06-14 18:17:35 +00006665 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6666 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6667 N0.getOperand(0) == N0.getOperand(1) &&
6668 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006669 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006670 SDValue(CFP11, 0),
6671 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006672 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006673 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006674 }
6675 }
6676
Shuxin Yang93b1f122013-03-25 22:52:29 +00006677 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006678 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006679 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006680 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006681 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006682 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006683 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006684 }
6685
Shuxin Yang93b1f122013-03-25 22:52:29 +00006686 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006687 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006688 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006689 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006690 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006691 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006692 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006693 }
6694
Stephen Lin4e69d012013-06-14 21:33:58 +00006695 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006696 if (AllowNewFpConst &&
6697 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006698 N0.getOperand(0) == N0.getOperand(1) &&
6699 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006700 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006701 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006702 N0.getOperand(0),
6703 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006704 }
6705
Lang Hames39fb1d02012-06-19 22:51:23 +00006706 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006707 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006708 DAG.getTarget().Options.UnsafeFPMath) &&
Eric Christopherd9134482014-08-04 21:25:23 +00006709 DAG.getTarget()
6710 .getSubtargetImpl()
6711 ->getTargetLowering()
6712 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006713 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006714
6715 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006716 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006717 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006718 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006719
Michael Liaoec3850122012-09-01 04:09:16 +00006720 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006721 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006722 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006723 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006724 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006725 }
6726
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006727 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006728}
6729
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006730SDValue DAGCombiner::visitFSUB(SDNode *N) {
6731 SDValue N0 = N->getOperand(0);
6732 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006733 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6734 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006735 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006736 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006737
Dan Gohmana8665142007-06-25 16:23:39 +00006738 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006739 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006740 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006741 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006742 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006743
Nate Begeman418c6e42005-10-18 00:28:13 +00006744 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006745 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006746 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006747 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006748 if (DAG.getTarget().Options.UnsafeFPMath &&
6749 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006750 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006751 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006752 if (DAG.getTarget().Options.UnsafeFPMath &&
6753 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006754 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006755 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006756 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006757 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006758 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006759 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006760 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006761 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006762 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006763
Bill Wendlingdf170db2012-03-15 05:12:00 +00006764 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006765 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006766 // (fsub x, (fadd x, y)) -> (fneg y) &
6767 // (fsub x, (fadd y, x)) -> (fneg y)
6768 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006769 if (N0 == N1)
6770 return DAG.getConstantFP(0.0f, VT);
6771
Bill Wendlingdf170db2012-03-15 05:12:00 +00006772 if (N1.getOpcode() == ISD::FADD) {
6773 SDValue N10 = N1->getOperand(0);
6774 SDValue N11 = N1->getOperand(1);
6775
6776 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6777 &DAG.getTarget().Options))
6778 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006779
Stephen Lin8e8424e2013-07-09 00:44:49 +00006780 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6781 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006782 return GetNegatedExpression(N10, DAG, LegalOperations);
6783 }
6784 }
6785
Lang Hames39fb1d02012-06-19 22:51:23 +00006786 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006787 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006788 DAG.getTarget().Options.UnsafeFPMath) &&
Eric Christopherd9134482014-08-04 21:25:23 +00006789 DAG.getTarget()
6790 .getSubtargetImpl()
6791 ->getTargetLowering()
6792 ->isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006793 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006794
6795 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006796 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006797 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006798 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006799 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006800
6801 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6802 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006803 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006804 return DAG.getNode(ISD::FMA, dl, VT,
6805 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006806 N1.getOperand(0)),
6807 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006808
Stephen Lin8e8424e2013-07-09 00:44:49 +00006809 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006810 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006811 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6812 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6813 SDValue N00 = N0.getOperand(0).getOperand(0);
6814 SDValue N01 = N0.getOperand(0).getOperand(1);
6815 return DAG.getNode(ISD::FMA, dl, VT,
6816 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6817 DAG.getNode(ISD::FNEG, dl, VT, N1));
6818 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006819 }
6820
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006821 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006822}
6823
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006824SDValue DAGCombiner::visitFMUL(SDNode *N) {
6825 SDValue N0 = N->getOperand(0);
6826 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006827 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6828 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006829 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006831
Dan Gohmana8665142007-06-25 16:23:39 +00006832 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006833 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006834 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006835 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006836 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006837
Nate Begemanec48a1b2005-10-17 20:40:11 +00006838 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006839 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006840 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006841 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006842 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006843 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006844 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006845 if (DAG.getTarget().Options.UnsafeFPMath &&
6846 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006847 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006848 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006849 if (DAG.getTarget().Options.UnsafeFPMath &&
6850 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006851 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006852 // fold (fmul A, 1.0) -> A
6853 if (N1CFP && N1CFP->isExactlyValue(1.0))
6854 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006855 // fold (fmul X, 2.0) -> (fadd X, X)
6856 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006857 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006858 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006859 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006860 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006861 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006862
Bill Wendling3dc5d242009-01-30 22:57:07 +00006863 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006864 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006865 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006866 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006867 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006868 // Both can be negated for free, check to see if at least one is cheaper
6869 // negated.
6870 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006871 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006872 GetNegatedExpression(N0, DAG, LegalOperations),
6873 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006874 }
6875 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006876
Chris Lattner0199fd62007-01-08 23:04:05 +00006877 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006878 if (DAG.getTarget().Options.UnsafeFPMath &&
6879 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006880 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006881 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6882 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006883 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006884
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006885 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006886}
6887
Owen Anderson41b06652012-05-02 22:17:40 +00006888SDValue DAGCombiner::visitFMA(SDNode *N) {
6889 SDValue N0 = N->getOperand(0);
6890 SDValue N1 = N->getOperand(1);
6891 SDValue N2 = N->getOperand(2);
6892 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6893 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6894 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006895 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006896
Owen Anderson9d5a8c22014-08-02 08:45:33 +00006897
6898 // Constant fold FMA.
6899 if (isa<ConstantFPSDNode>(N0) &&
6900 isa<ConstantFPSDNode>(N1) &&
6901 isa<ConstantFPSDNode>(N2)) {
6902 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6903 }
6904
Owen Andersonb351c8d2012-11-01 02:00:53 +00006905 if (DAG.getTarget().Options.UnsafeFPMath) {
6906 if (N0CFP && N0CFP->isZero())
6907 return N2;
6908 if (N1CFP && N1CFP->isZero())
6909 return N2;
6910 }
Owen Anderson41b06652012-05-02 22:17:40 +00006911 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006912 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006913 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006914 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006915
Owen Andersonc7aaf522012-05-30 18:50:39 +00006916 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006917 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006918 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006919
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006920 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6921 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6922 N2.getOpcode() == ISD::FMUL &&
6923 N0 == N2.getOperand(0) &&
6924 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6925 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6926 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6927 }
6928
6929
6930 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6931 if (DAG.getTarget().Options.UnsafeFPMath &&
6932 N0.getOpcode() == ISD::FMUL && N1CFP &&
6933 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6934 return DAG.getNode(ISD::FMA, dl, VT,
6935 N0.getOperand(0),
6936 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6937 N2);
6938 }
6939
6940 // (fma x, 1, y) -> (fadd x, y)
6941 // (fma x, -1, y) -> (fadd (fneg x), y)
6942 if (N1CFP) {
6943 if (N1CFP->isExactlyValue(1.0))
6944 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6945
6946 if (N1CFP->isExactlyValue(-1.0) &&
6947 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6948 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006949 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006950 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6951 }
6952 }
6953
6954 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006955 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6956 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006957 DAG.getNode(ISD::FADD, dl, VT,
6958 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006959
6960 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6961 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006962 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6963 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006964 DAG.getNode(ISD::FADD, dl, VT,
6965 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006966
6967
Owen Anderson41b06652012-05-02 22:17:40 +00006968 return SDValue();
6969}
6970
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006971SDValue DAGCombiner::visitFDIV(SDNode *N) {
6972 SDValue N0 = N->getOperand(0);
6973 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006974 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6975 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006976 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006977 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006978
Dan Gohmana8665142007-06-25 16:23:39 +00006979 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006980 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006981 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006982 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006983 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006984
Nate Begeman569c4392006-01-18 22:35:16 +00006985 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006986 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006987 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006988
Duncan Sands2f1dc382012-04-08 18:08:12 +00006989 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006990 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006991 // Compute the reciprocal 1.0 / c2.
6992 APFloat N1APF = N1CFP->getValueAPF();
6993 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6994 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006995 // Only do the transform if the reciprocal is a legal fp immediate that
6996 // isn't too nasty (eg NaN, denormal, ...).
6997 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006998 (!LegalOperations ||
6999 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7000 // backend)... we should handle this gracefully after Legalize.
7001 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7002 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7003 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007004 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00007005 DAG.getConstantFP(Recip, VT));
7006 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007007
Bill Wendling3dc5d242009-01-30 22:57:07 +00007008 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007009 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007010 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007011 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00007012 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007013 // Both can be negated for free, check to see if at least one is cheaper
7014 // negated.
7015 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007016 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007017 GetNegatedExpression(N0, DAG, LegalOperations),
7018 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007019 }
7020 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007021
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007022 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007023}
7024
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007025SDValue DAGCombiner::visitFREM(SDNode *N) {
7026 SDValue N0 = N->getOperand(0);
7027 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007028 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7029 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007030 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007031
Nate Begeman569c4392006-01-18 22:35:16 +00007032 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007033 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007034 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007035
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007036 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007037}
7038
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007039SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7040 SDValue N0 = N->getOperand(0);
7041 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007042 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7043 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007044 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007045
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007046 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007047 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007048
Chris Lattner3bc40502006-03-05 05:30:57 +00007049 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007050 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007051 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7052 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007053 if (!V.isNegative()) {
7054 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007055 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007056 } else {
7057 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007058 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7059 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007060 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007061 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007062
Chris Lattner3bc40502006-03-05 05:30:57 +00007063 // copysign(fabs(x), y) -> copysign(x, y)
7064 // copysign(fneg(x), y) -> copysign(x, y)
7065 // copysign(copysign(x,z), y) -> copysign(x, y)
7066 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7067 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007068 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007069 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007070
7071 // copysign(x, abs(y)) -> abs(x)
7072 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007073 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007074
Chris Lattner3bc40502006-03-05 05:30:57 +00007075 // copysign(x, copysign(y,z)) -> copysign(x, z)
7076 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007077 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007078 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007079
Chris Lattner3bc40502006-03-05 05:30:57 +00007080 // copysign(x, fp_extend(y)) -> copysign(x, y)
7081 // copysign(x, fp_round(y)) -> copysign(x, y)
7082 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007083 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007084 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007085
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007086 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007087}
7088
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007089SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7090 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007091 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007092 EVT VT = N->getValueType(0);
7093 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007094
Nate Begeman21158fc2005-09-01 00:19:25 +00007095 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007096 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007097 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007098 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007099 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007100 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007101
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007102 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7103 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007104 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7105 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007106 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007107 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007108 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007109 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007110
Alp Tokercb402912014-01-24 17:20:08 +00007111 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007112 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007113 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7114 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7115 !VT.isVector() &&
7116 (!LegalOperations ||
7117 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7118 SDValue Ops[] =
7119 { N0.getOperand(0), N0.getOperand(1),
7120 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7121 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007122 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007123 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007124
Nadav Rotem90560762012-07-23 07:59:50 +00007125 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7126 // (select_cc x, y, 1.0, 0.0,, cc)
7127 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7128 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7129 (!LegalOperations ||
7130 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7131 SDValue Ops[] =
7132 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7133 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7134 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007135 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007136 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007137 }
7138
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007139 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007140}
7141
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007142SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7143 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007144 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007145 EVT VT = N->getValueType(0);
7146 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007147
Nate Begeman21158fc2005-09-01 00:19:25 +00007148 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007149 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007150 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007151 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007152 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007153 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007154
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007155 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7156 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007157 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7158 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007159 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007160 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007161 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007162 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007163
Alp Tokercb402912014-01-24 17:20:08 +00007164 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007165 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007166 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007167
Nadav Rotem90560762012-07-23 07:59:50 +00007168 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7169 (!LegalOperations ||
7170 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7171 SDValue Ops[] =
7172 { N0.getOperand(0), N0.getOperand(1),
7173 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7174 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007175 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007176 }
7177 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007178
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007179 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007180}
7181
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007182SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7183 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007184 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007185 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007186
Nate Begeman21158fc2005-09-01 00:19:25 +00007187 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007188 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007189 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007190
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007191 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007192}
7193
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007194SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7195 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007196 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007197 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007198
Nate Begeman21158fc2005-09-01 00:19:25 +00007199 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007200 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007201 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007202
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::visitFP_ROUND(SDNode *N) {
7207 SDValue N0 = N->getOperand(0);
7208 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007209 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007210 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007211
Nate Begeman21158fc2005-09-01 00:19:25 +00007212 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007213 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007214 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007215
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007216 // fold (fp_round (fp_extend x)) -> x
7217 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7218 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007219
Chris Lattner0feb1b02008-01-24 06:45:35 +00007220 // fold (fp_round (fp_round x)) -> (fp_round x)
7221 if (N0.getOpcode() == ISD::FP_ROUND) {
7222 // This is a value preserving truncation if both round's are.
7223 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007224 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007225 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007226 DAG.getIntPtrConstant(IsTrunc));
7227 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007228
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007229 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007230 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007231 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007232 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007233 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007234 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007235 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007236 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007237
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007238 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007239}
7240
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007241SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7242 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007243 EVT VT = N->getValueType(0);
7244 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007245 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007246
Nate Begeman21158fc2005-09-01 00:19:25 +00007247 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007248 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007249 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007250 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007251 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007252
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007253 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007254}
7255
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007256SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7257 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007258 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007259 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007260
Chris Lattner5919b482007-12-29 06:55:23 +00007261 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007262 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007263 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007264 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007265
Nate Begeman21158fc2005-09-01 00:19:25 +00007266 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007267 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007268 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007269
7270 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7271 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007272 if (N0.getOpcode() == ISD::FP_ROUND
7273 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007274 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007275 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007276 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007277 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007278 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007279 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007280 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007281
Chris Lattner72733e52008-01-17 07:00:52 +00007282 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007283 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007284 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007285 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007286 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007287 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007288 LN0->getBasePtr(), N0.getValueType(),
7289 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007290 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007291 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007292 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007293 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007294 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007295 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007296 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007297
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007298 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007299}
7300
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007301SDValue DAGCombiner::visitFNEG(SDNode *N) {
7302 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007303 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007304
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007305 // Constant fold FNEG.
7306 if (isa<ConstantFPSDNode>(N0))
7307 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7308
Craig Topper82384612012-09-11 01:45:21 +00007309 if (VT.isVector()) {
7310 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7311 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007312 }
7313
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007314 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7315 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007316 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007317
Chris Lattner888560d2008-01-27 17:42:27 +00007318 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7319 // constant pool values.
Sanjay Patel2ef67442014-08-03 22:48:23 +00007320 // TODO: We can also optimize for vectors here, but we need to make sure
7321 // that the sign mask is created properly for each vector element.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007322 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007323 !VT.isVector() &&
7324 N0.getNode()->hasOneUse() &&
7325 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007326 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007327 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007328 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007329 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007330 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007331 AddToWorklist(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007332 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007333 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007334 }
7335 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007336
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007337 // (fneg (fmul c, x)) -> (fmul -c, x)
7338 if (N0.getOpcode() == ISD::FMUL) {
7339 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007340 if (CFP1) {
7341 APFloat CVal = CFP1->getValueAPF();
7342 CVal.changeSign();
7343 if (Level >= AfterLegalizeDAG &&
7344 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7345 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7346 return DAG.getNode(
7347 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7348 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7349 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007350 }
7351
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007352 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007353}
7354
Owen Andersona40319b2012-08-13 23:32:49 +00007355SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7356 SDValue N0 = N->getOperand(0);
7357 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7358 EVT VT = N->getValueType(0);
7359
7360 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007361 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007362 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007363
7364 return SDValue();
7365}
7366
7367SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7368 SDValue N0 = N->getOperand(0);
7369 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7370 EVT VT = N->getValueType(0);
7371
7372 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007373 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007374 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007375
7376 return SDValue();
7377}
7378
7379SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7380 SDValue N0 = N->getOperand(0);
7381 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7382 EVT VT = N->getValueType(0);
7383
7384 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007385 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007386 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007387
7388 return SDValue();
7389}
7390
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007391SDValue DAGCombiner::visitFABS(SDNode *N) {
7392 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007393 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007394 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007395
Craig Topper82384612012-09-11 01:45:21 +00007396 if (VT.isVector()) {
7397 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7398 if (FoldedVOp.getNode()) return FoldedVOp;
7399 }
7400
Nate Begeman21158fc2005-09-01 00:19:25 +00007401 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007402 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007403 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007404 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007405 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007406 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007407 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007408 // fold (fabs (fcopysign x, y)) -> (fabs x)
7409 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007410 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007411
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007412 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007413 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007414 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007415 N0.getOpcode() == ISD::BITCAST &&
7416 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007417 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007418 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007419 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007420 APInt SignMask;
7421 if (N0.getValueType().isVector()) {
7422 // For a vector, get a mask such as 0x7f... per scalar element
7423 // and splat it.
7424 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7425 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7426 } else {
7427 // For a scalar, just generate 0x7f...
7428 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7429 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007430 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007431 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007432 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007433 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007434 }
7435 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007436
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007437 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007438}
7439
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007440SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7441 SDValue Chain = N->getOperand(0);
7442 SDValue N1 = N->getOperand(1);
7443 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007444
Dan Gohman82e80012009-11-17 00:47:23 +00007445 // If N is a constant we could fold this into a fallthrough or unconditional
7446 // branch. However that doesn't happen very often in normal code, because
7447 // Instcombine/SimplifyCFG should have handled the available opportunities.
7448 // If we did this folding here, it would be necessary to update the
7449 // MachineBasicBlock CFG, which is awkward.
7450
Nate Begeman7e7f4392006-02-01 07:19:44 +00007451 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7452 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007453 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007454 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7455 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007456 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007457 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007458 N1.getOperand(0), N1.getOperand(1), N2);
7459 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007460
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007461 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7462 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7463 (N1.getOperand(0).hasOneUse() &&
7464 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007465 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007466 if (N1.getOpcode() == ISD::TRUNCATE) {
7467 // Look pass the truncate.
7468 Trunc = N1.getNode();
7469 N1 = N1.getOperand(0);
7470 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007471
Bill Wendlingaa28be62009-03-26 06:14:09 +00007472 // Match this pattern so that we can generate simpler code:
7473 //
7474 // %a = ...
7475 // %b = and i32 %a, 2
7476 // %c = srl i32 %b, 1
7477 // brcond i32 %c ...
7478 //
7479 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007480 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007481 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007482 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007483 // %c = setcc eq %b, 0
7484 // brcond %c ...
7485 //
7486 // This applies only when the AND constant value has one bit set and the
7487 // SRL constant is equal to the log2 of the AND constant. The back-end is
7488 // smart enough to convert the result into a TEST/JMP sequence.
7489 SDValue Op0 = N1.getOperand(0);
7490 SDValue Op1 = N1.getOperand(1);
7491
7492 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007493 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007494 SDValue AndOp1 = Op0.getOperand(1);
7495
7496 if (AndOp1.getOpcode() == ISD::Constant) {
7497 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7498
7499 if (AndConst.isPowerOf2() &&
7500 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7501 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007502 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007503 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007504 Op0, DAG.getConstant(0, Op0.getValueType()),
7505 ISD::SETNE);
7506
Andrew Trickef9de2a2013-05-25 02:42:55 +00007507 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007508 MVT::Other, Chain, SetCC, N2);
7509 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7510 // will convert it back to (X & C1) >> C2.
7511 CombineTo(N, NewBRCond, false);
7512 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00007513 if (Trunc)
7514 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007515 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007516 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007517 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007518 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007519 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007520 }
7521 }
7522 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007523
7524 if (Trunc)
7525 // Restore N1 if the above transformation doesn't match.
7526 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007527 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007528
Evan Cheng228c31f2010-02-27 07:36:59 +00007529 // Transform br(xor(x, y)) -> br(x != y)
7530 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7531 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7532 SDNode *TheXor = N1.getNode();
7533 SDValue Op0 = TheXor->getOperand(0);
7534 SDValue Op1 = TheXor->getOperand(1);
7535 if (Op0.getOpcode() == Op1.getOpcode()) {
7536 // Avoid missing important xor optimizations.
7537 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007538 if (Tmp.getNode()) {
7539 if (Tmp.getNode() != TheXor) {
7540 DEBUG(dbgs() << "\nReplacing.8 ";
7541 TheXor->dump(&DAG);
7542 dbgs() << "\nWith: ";
7543 Tmp.getNode()->dump(&DAG);
7544 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007545 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007546 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00007547 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007548 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007549 MVT::Other, Chain, Tmp, N2);
7550 }
7551
Benjamin Kramer93354432013-03-30 21:28:18 +00007552 // visitXOR has changed XOR's operands or replaced the XOR completely,
7553 // bail out.
7554 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007555 }
7556 }
7557
7558 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7559 bool Equal = false;
7560 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7561 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7562 Op0.getOpcode() == ISD::XOR) {
7563 TheXor = Op0.getNode();
7564 Equal = true;
7565 }
7566
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007567 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007568 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007569 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007570 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007571 SetCCVT,
7572 Op0, Op1,
7573 Equal ? ISD::SETEQ : ISD::SETNE);
7574 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007575 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007576 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007577 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007578 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007579 MVT::Other, Chain, SetCC, N2);
7580 }
7581 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007582
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007583 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007584}
7585
Chris Lattnera49e16f2005-10-05 06:47:48 +00007586// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7587//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007588SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007589 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007590 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007591
Dan Gohman82e80012009-11-17 00:47:23 +00007592 // If N is a constant we could fold this into a fallthrough or unconditional
7593 // branch. However that doesn't happen very often in normal code, because
7594 // Instcombine/SimplifyCFG should have handled the available opportunities.
7595 // If we did this folding here, it would be necessary to update the
7596 // MachineBasicBlock CFG, which is awkward.
7597
Duncan Sands93b66092008-06-09 11:32:28 +00007598 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007599 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007600 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007601 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007602 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007603
Nate Begemanbd7df032005-10-05 21:43:42 +00007604 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007605 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007606 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007607 N->getOperand(0), Simp.getOperand(2),
7608 Simp.getOperand(0), Simp.getOperand(1),
7609 N->getOperand(4));
7610
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007611 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007612}
7613
Evan Chengfa832632012-01-13 01:37:24 +00007614/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7615/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007616/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007617static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7618 SelectionDAG &DAG,
7619 const TargetLowering &TLI) {
7620 EVT VT;
7621 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7622 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7623 return false;
7624 VT = Use->getValueType(0);
7625 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7626 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7627 return false;
7628 VT = ST->getValue().getValueType();
7629 } else
7630 return false;
7631
Chandler Carruth95f83e02013-01-07 15:14:13 +00007632 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007633 if (N->getOpcode() == ISD::ADD) {
7634 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7635 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007636 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007637 AM.BaseOffs = Offset->getSExtValue();
7638 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007639 // [reg +/- reg]
7640 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007641 } else if (N->getOpcode() == ISD::SUB) {
7642 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7643 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007644 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007645 AM.BaseOffs = -Offset->getSExtValue();
7646 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007647 // [reg +/- reg]
7648 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007649 } else
7650 return false;
7651
7652 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7653}
7654
Duncan Sands075293f2008-06-15 20:12:31 +00007655/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7656/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007657/// and it has other uses besides the load / store. After the
7658/// transformation, the new indexed load / store has effectively folded
7659/// the add / subtract in and all of its other uses are redirected to the
7660/// new load / store.
7661bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007662 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007663 return false;
7664
7665 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007666 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007667 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007668 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007669 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007670 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007671 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007672 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007673 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7674 return false;
7675 Ptr = LD->getBasePtr();
7676 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007677 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007678 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007679 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007680 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7681 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7682 return false;
7683 Ptr = ST->getBasePtr();
7684 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007685 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007686 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007687 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007688
Chris Lattnereabc15c2006-11-11 00:56:29 +00007689 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7690 // out. There is no reason to make this a preinc/predec.
7691 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007692 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007693 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007694
Chris Lattnereabc15c2006-11-11 00:56:29 +00007695 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007696 SDValue BasePtr;
7697 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007698 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7699 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7700 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007701
7702 // Backends without true r+i pre-indexed forms may need to pass a
7703 // constant base with a variable offset so that constant coercion
7704 // will work with the patterns in canonical form.
7705 bool Swapped = false;
7706 if (isa<ConstantSDNode>(BasePtr)) {
7707 std::swap(BasePtr, Offset);
7708 Swapped = true;
7709 }
7710
Evan Cheng044a0a82007-05-03 23:52:19 +00007711 // Don't create a indexed load / store with zero offset.
7712 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007713 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007714 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007715
Chris Lattnera0a80032006-11-11 01:00:15 +00007716 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007717 // 1) The new base ptr is a frame index.
7718 // 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 +00007719 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007720 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007721 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007722 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007723
Chris Lattnera0a80032006-11-11 01:00:15 +00007724 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7725 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007726 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007727 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007728
Chris Lattnera0a80032006-11-11 01:00:15 +00007729 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007730 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007731 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007732 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007733 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007734 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007735
Hal Finkel25819052013-02-08 21:35:47 +00007736 // If the offset is a constant, there may be other adds of constants that
7737 // can be folded with this one. We should do this to avoid having to keep
7738 // a copy of the original base pointer.
7739 SmallVector<SDNode *, 16> OtherUses;
7740 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007741 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007742 if (Use == Ptr.getNode())
7743 continue;
7744
7745 if (Use->isPredecessorOf(N))
7746 continue;
7747
7748 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7749 OtherUses.clear();
7750 break;
7751 }
7752
7753 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7754 if (Op1.getNode() == BasePtr.getNode())
7755 std::swap(Op0, Op1);
7756 assert(Op0.getNode() == BasePtr.getNode() &&
7757 "Use of ADD/SUB but not an operand");
7758
7759 if (!isa<ConstantSDNode>(Op1)) {
7760 OtherUses.clear();
7761 break;
7762 }
7763
7764 // FIXME: In some cases, we can be smarter about this.
7765 if (Op1.getValueType() != Offset.getValueType()) {
7766 OtherUses.clear();
7767 break;
7768 }
7769
7770 OtherUses.push_back(Use);
7771 }
7772
7773 if (Swapped)
7774 std::swap(BasePtr, Offset);
7775
Evan Chenga4d187b2007-05-24 02:35:39 +00007776 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007777 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007778
7779 // Caches for hasPredecessorHelper
7780 SmallPtrSet<const SDNode *, 32> Visited;
7781 SmallVector<const SDNode *, 16> Worklist;
7782
Jim Grosbache8160032014-04-11 01:13:13 +00007783 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007784 if (Use == N)
7785 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007786 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007787 return false;
7788
Evan Chengfa832632012-01-13 01:37:24 +00007789 // If Ptr may be folded in addressing mode of other use, then it's
7790 // not profitable to do this transformation.
7791 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007792 RealUse = true;
7793 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007794
Chris Lattnereabc15c2006-11-11 00:56:29 +00007795 if (!RealUse)
7796 return false;
7797
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007798 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007799 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007800 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007801 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007802 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007803 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007804 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007805 ++PreIndexedNodes;
7806 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007807 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007808 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007809 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007810 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007811 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007812 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007813 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007814 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7815 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007816 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007817 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007818 }
7819
Chris Lattnereabc15c2006-11-11 00:56:29 +00007820 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00007821 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007822
Hal Finkel25819052013-02-08 21:35:47 +00007823 if (Swapped)
7824 std::swap(BasePtr, Offset);
7825
7826 // Replace other uses of BasePtr that can be updated to use Ptr
7827 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7828 unsigned OffsetIdx = 1;
7829 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7830 OffsetIdx = 0;
7831 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7832 BasePtr.getNode() && "Expected BasePtr operand");
7833
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007834 // We need to replace ptr0 in the following expression:
7835 // x0 * offset0 + y0 * ptr0 = t0
7836 // knowing that
7837 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007838 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007839 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7840 // indexed load/store and the expresion that needs to be re-written.
7841 //
7842 // Therefore, we have:
7843 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007844
7845 ConstantSDNode *CN =
7846 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007847 int X0, X1, Y0, Y1;
7848 APInt Offset0 = CN->getAPIntValue();
7849 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007850
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007851 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7852 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7853 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7854 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007855
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007856 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7857
7858 APInt CNV = Offset0;
7859 if (X0 < 0) CNV = -CNV;
7860 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7861 else CNV = CNV - Offset1;
7862
7863 // We can now generate the new expression.
7864 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7865 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7866
7867 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007868 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007869 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7870 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00007871 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00007872 }
7873
Chris Lattnereabc15c2006-11-11 00:56:29 +00007874 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007875 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00007876 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007877
7878 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007879}
7880
Duncan Sands075293f2008-06-15 20:12:31 +00007881/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007882/// add / sub of the base pointer node into a post-indexed load / store.
7883/// The transformation folded the add / subtract into the new indexed
7884/// load / store effectively and all of its uses are redirected to the
7885/// new load / store.
7886bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007887 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007888 return false;
7889
7890 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007891 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007892 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007893 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007894 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007895 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007896 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007897 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7898 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7899 return false;
7900 Ptr = LD->getBasePtr();
7901 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007902 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007903 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007904 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007905 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7906 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7907 return false;
7908 Ptr = ST->getBasePtr();
7909 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007910 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007911 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007912 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007913
Gabor Greiff304a7a2008-08-28 21:40:38 +00007914 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007915 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007916
Jim Grosbache8160032014-04-11 01:13:13 +00007917 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007918 if (Op == N ||
7919 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7920 continue;
7921
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007922 SDValue BasePtr;
7923 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007924 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7925 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007926 // Don't create a indexed load / store with zero offset.
7927 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007928 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007929 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007930
Chris Lattnereabc15c2006-11-11 00:56:29 +00007931 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007932 // 1) All uses are load / store ops that use it as base ptr (and
7933 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007934 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7935 // nor a successor of N. Otherwise, if Op is folded that would
7936 // create a cycle.
7937
Evan Chengcfc05132009-05-06 18:25:01 +00007938 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7939 continue;
7940
Chris Lattnereabc15c2006-11-11 00:56:29 +00007941 // Check for #1.
7942 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007943 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007944 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007945 continue;
7946
Chris Lattnereabc15c2006-11-11 00:56:29 +00007947 // If all the uses are load / store addresses, then don't do the
7948 // transformation.
7949 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7950 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007951 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007952 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007953 RealUse = true;
7954 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007955
Chris Lattnereabc15c2006-11-11 00:56:29 +00007956 if (!RealUse) {
7957 TryNext = true;
7958 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007959 }
7960 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007961 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007962
Chris Lattnereabc15c2006-11-11 00:56:29 +00007963 if (TryNext)
7964 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007965
Chris Lattnereabc15c2006-11-11 00:56:29 +00007966 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007967 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007968 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007969 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007970 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007971 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007972 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007973 ++PostIndexedNodes;
7974 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007975 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007976 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007977 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007978 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007979 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007980 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007981 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007982 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7983 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007984 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007985 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007986 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007987
Chris Lattnereabc15c2006-11-11 00:56:29 +00007988 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00007989 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007990
7991 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007992 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007993 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00007994 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007995 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007996 }
7997 }
7998 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007999
Chris Lattnerffad2162006-11-11 00:39:41 +00008000 return false;
8001}
8002
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008003SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008004 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008005 SDValue Chain = LD->getChain();
8006 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008007
Evan Chenga684cd22007-05-01 00:38:21 +00008008 // If load is not volatile and there are no uses of the loaded value (and
8009 // the updated indexed value in case of indexed loads), change uses of the
8010 // chain value into uses of the chain input (i.e. delete the dead load).
8011 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008012 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008013 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008014 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008015 // It's not safe to use the two value CombineTo variant here. e.g.
8016 // v1, chain2 = load chain1, loc
8017 // v2, chain3 = load chain2, loc
8018 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008019 // Now we replace use of chain2 with chain1. This makes the second load
8020 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008021 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008022 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008023 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008024 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008025 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008026 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008027 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008028
Chandler Carruth18066972014-08-02 10:02:07 +00008029 if (N->use_empty())
8030 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008031
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008032 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008033 }
Evan Chengb68343c2007-05-01 08:53:39 +00008034 } else {
8035 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008036 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel2c77fe52014-05-28 15:33:19 +00008037 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00008038 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00008039 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008040 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008041 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008042 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008043 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008044 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008045 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel2c77fe52014-05-28 15:33:19 +00008046 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8047 DAG.getUNDEF(N->getValueType(1)));
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008048 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008049 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008050 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008051 }
Evan Chenga684cd22007-05-01 00:38:21 +00008052 }
8053 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008054
Chris Lattnere260ed82005-10-10 22:04:48 +00008055 // If this load is directly stored, replace the load value with the stored
8056 // value.
8057 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008058 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008059 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008060 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008061 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8062 if (PrevST->getBasePtr() == Ptr &&
8063 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008064 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008065 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008066 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008067
Evan Cheng43cd9e32010-04-01 06:04:33 +00008068 // Try to infer better alignment information than the load already has.
8069 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008070 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008071 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8072 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008073 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008074 LD->getValueType(0),
8075 Chain, Ptr, LD->getPointerInfo(),
8076 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008077 LD->isVolatile(), LD->isNonTemporal(),
8078 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008079 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8080 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008081 }
8082 }
8083
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008084 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8085 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008086#ifndef NDEBUG
8087 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8088 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8089 UseAA = false;
8090#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008091 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008092 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008093 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008094
Jim Laskey708d0db2006-10-04 16:53:27 +00008095 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008096 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008097 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008098
Jim Laskeyd07be232006-09-25 16:29:54 +00008099 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008100 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008101 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008102 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008103 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008104 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008105 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008106 BetterChain, Ptr, LD->getMemoryVT(),
8107 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008108 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008109
Jim Laskey708d0db2006-10-04 16:53:27 +00008110 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008111 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008112 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008113
Nate Begeman879d8f12009-09-15 00:18:30 +00008114 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008115 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008116
Jim Laskeydcf983c2006-10-13 23:32:28 +00008117 // Replace uses with load result and token factor. Don't add users
8118 // to work list.
8119 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008120 }
8121 }
8122
Evan Cheng357017f2006-11-03 03:06:21 +00008123 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008124 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008125 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008126
Quentin Colombetde0e0622013-10-11 18:29:42 +00008127 // Try to slice up N to more direct loads if the slices are mapped to
8128 // different register banks or pairing can take place.
8129 if (SliceUpLoad(N))
8130 return SDValue(N, 0);
8131
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008132 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008133}
8134
Quentin Colombetde0e0622013-10-11 18:29:42 +00008135namespace {
8136/// \brief Helper structure used to slice a load in smaller loads.
8137/// Basically a slice is obtained from the following sequence:
8138/// Origin = load Ty1, Base
8139/// Shift = srl Ty1 Origin, CstTy Amount
8140/// Inst = trunc Shift to Ty2
8141///
8142/// Then, it will be rewriten into:
8143/// Slice = load SliceTy, Base + SliceOffset
8144/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8145///
8146/// SliceTy is deduced from the number of bits that are actually used to
8147/// build Inst.
8148struct LoadedSlice {
8149 /// \brief Helper structure used to compute the cost of a slice.
8150 struct Cost {
8151 /// Are we optimizing for code size.
8152 bool ForCodeSize;
8153 /// Various cost.
8154 unsigned Loads;
8155 unsigned Truncates;
8156 unsigned CrossRegisterBanksCopies;
8157 unsigned ZExts;
8158 unsigned Shift;
8159
8160 Cost(bool ForCodeSize = false)
8161 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8162 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8163
8164 /// \brief Get the cost of one isolated slice.
8165 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8166 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8167 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8168 EVT TruncType = LS.Inst->getValueType(0);
8169 EVT LoadedType = LS.getLoadedType();
8170 if (TruncType != LoadedType &&
8171 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8172 ZExts = 1;
8173 }
8174
8175 /// \brief Account for slicing gain in the current cost.
8176 /// Slicing provide a few gains like removing a shift or a
8177 /// truncate. This method allows to grow the cost of the original
8178 /// load with the gain from this slice.
8179 void addSliceGain(const LoadedSlice &LS) {
8180 // Each slice saves a truncate.
8181 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8182 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8183 LS.Inst->getOperand(0).getValueType()))
8184 ++Truncates;
8185 // If there is a shift amount, this slice gets rid of it.
8186 if (LS.Shift)
8187 ++Shift;
8188 // If this slice can merge a cross register bank copy, account for it.
8189 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8190 ++CrossRegisterBanksCopies;
8191 }
8192
8193 Cost &operator+=(const Cost &RHS) {
8194 Loads += RHS.Loads;
8195 Truncates += RHS.Truncates;
8196 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8197 ZExts += RHS.ZExts;
8198 Shift += RHS.Shift;
8199 return *this;
8200 }
8201
8202 bool operator==(const Cost &RHS) const {
8203 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8204 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8205 ZExts == RHS.ZExts && Shift == RHS.Shift;
8206 }
8207
8208 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8209
8210 bool operator<(const Cost &RHS) const {
8211 // Assume cross register banks copies are as expensive as loads.
8212 // FIXME: Do we want some more target hooks?
8213 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8214 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8215 // Unless we are optimizing for code size, consider the
8216 // expensive operation first.
8217 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8218 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8219 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8220 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8221 }
8222
8223 bool operator>(const Cost &RHS) const { return RHS < *this; }
8224
8225 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8226
8227 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8228 };
8229 // The last instruction that represent the slice. This should be a
8230 // truncate instruction.
8231 SDNode *Inst;
8232 // The original load instruction.
8233 LoadSDNode *Origin;
8234 // The right shift amount in bits from the original load.
8235 unsigned Shift;
8236 // The DAG from which Origin came from.
8237 // This is used to get some contextual information about legal types, etc.
8238 SelectionDAG *DAG;
8239
Craig Topperc0196b12014-04-14 00:51:57 +00008240 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8241 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008242 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8243
8244 LoadedSlice(const LoadedSlice &LS)
8245 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8246
8247 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8248 /// \return Result is \p BitWidth and has used bits set to 1 and
8249 /// not used bits set to 0.
8250 APInt getUsedBits() const {
8251 // Reproduce the trunc(lshr) sequence:
8252 // - Start from the truncated value.
8253 // - Zero extend to the desired bit width.
8254 // - Shift left.
8255 assert(Origin && "No original load to compare against.");
8256 unsigned BitWidth = Origin->getValueSizeInBits(0);
8257 assert(Inst && "This slice is not bound to an instruction");
8258 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8259 "Extracted slice is bigger than the whole type!");
8260 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8261 UsedBits.setAllBits();
8262 UsedBits = UsedBits.zext(BitWidth);
8263 UsedBits <<= Shift;
8264 return UsedBits;
8265 }
8266
8267 /// \brief Get the size of the slice to be loaded in bytes.
8268 unsigned getLoadedSize() const {
8269 unsigned SliceSize = getUsedBits().countPopulation();
8270 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8271 return SliceSize / 8;
8272 }
8273
8274 /// \brief Get the type that will be loaded for this slice.
8275 /// Note: This may not be the final type for the slice.
8276 EVT getLoadedType() const {
8277 assert(DAG && "Missing context");
8278 LLVMContext &Ctxt = *DAG->getContext();
8279 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8280 }
8281
8282 /// \brief Get the alignment of the load used for this slice.
8283 unsigned getAlignment() const {
8284 unsigned Alignment = Origin->getAlignment();
8285 unsigned Offset = getOffsetFromBase();
8286 if (Offset != 0)
8287 Alignment = MinAlign(Alignment, Alignment + Offset);
8288 return Alignment;
8289 }
8290
8291 /// \brief Check if this slice can be rewritten with legal operations.
8292 bool isLegal() const {
8293 // An invalid slice is not legal.
8294 if (!Origin || !Inst || !DAG)
8295 return false;
8296
8297 // Offsets are for indexed load only, we do not handle that.
8298 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8299 return false;
8300
8301 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8302
8303 // Check that the type is legal.
8304 EVT SliceType = getLoadedType();
8305 if (!TLI.isTypeLegal(SliceType))
8306 return false;
8307
8308 // Check that the load is legal for this type.
8309 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8310 return false;
8311
8312 // Check that the offset can be computed.
8313 // 1. Check its type.
8314 EVT PtrType = Origin->getBasePtr().getValueType();
8315 if (PtrType == MVT::Untyped || PtrType.isExtended())
8316 return false;
8317
8318 // 2. Check that it fits in the immediate.
8319 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8320 return false;
8321
8322 // 3. Check that the computation is legal.
8323 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8324 return false;
8325
8326 // Check that the zext is legal if it needs one.
8327 EVT TruncateType = Inst->getValueType(0);
8328 if (TruncateType != SliceType &&
8329 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8330 return false;
8331
8332 return true;
8333 }
8334
8335 /// \brief Get the offset in bytes of this slice in the original chunk of
8336 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008337 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008338 uint64_t getOffsetFromBase() const {
8339 assert(DAG && "Missing context.");
8340 bool IsBigEndian =
8341 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8342 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8343 uint64_t Offset = Shift / 8;
8344 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8345 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8346 "The size of the original loaded type is not a multiple of a"
8347 " byte.");
8348 // If Offset is bigger than TySizeInBytes, it means we are loading all
8349 // zeros. This should have been optimized before in the process.
8350 assert(TySizeInBytes > Offset &&
8351 "Invalid shift amount for given loaded size");
8352 if (IsBigEndian)
8353 Offset = TySizeInBytes - Offset - getLoadedSize();
8354 return Offset;
8355 }
8356
8357 /// \brief Generate the sequence of instructions to load the slice
8358 /// represented by this object and redirect the uses of this slice to
8359 /// this new sequence of instructions.
8360 /// \pre this->Inst && this->Origin are valid Instructions and this
8361 /// object passed the legal check: LoadedSlice::isLegal returned true.
8362 /// \return The last instruction of the sequence used to load the slice.
8363 SDValue loadSlice() const {
8364 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8365 const SDValue &OldBaseAddr = Origin->getBasePtr();
8366 SDValue BaseAddr = OldBaseAddr;
8367 // Get the offset in that chunk of bytes w.r.t. the endianess.
8368 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8369 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8370 if (Offset) {
8371 // BaseAddr = BaseAddr + Offset.
8372 EVT ArithType = BaseAddr.getValueType();
8373 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8374 DAG->getConstant(Offset, ArithType));
8375 }
8376
8377 // Create the type of the loaded slice according to its size.
8378 EVT SliceType = getLoadedType();
8379
8380 // Create the load for the slice.
8381 SDValue LastInst = DAG->getLoad(
8382 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8383 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8384 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8385 // If the final type is not the same as the loaded type, this means that
8386 // we have to pad with zero. Create a zero extend for that.
8387 EVT FinalType = Inst->getValueType(0);
8388 if (SliceType != FinalType)
8389 LastInst =
8390 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8391 return LastInst;
8392 }
8393
8394 /// \brief Check if this slice can be merged with an expensive cross register
8395 /// bank copy. E.g.,
8396 /// i = load i32
8397 /// f = bitcast i32 i to float
8398 bool canMergeExpensiveCrossRegisterBankCopy() const {
8399 if (!Inst || !Inst->hasOneUse())
8400 return false;
8401 SDNode *Use = *Inst->use_begin();
8402 if (Use->getOpcode() != ISD::BITCAST)
8403 return false;
8404 assert(DAG && "Missing context");
8405 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8406 EVT ResVT = Use->getValueType(0);
8407 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8408 const TargetRegisterClass *ArgRC =
8409 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8410 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8411 return false;
8412
8413 // At this point, we know that we perform a cross-register-bank copy.
8414 // Check if it is expensive.
Eric Christopherd9134482014-08-04 21:25:23 +00008415 const TargetRegisterInfo *TRI =
8416 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00008417 // Assume bitcasts are cheap, unless both register classes do not
8418 // explicitly share a common sub class.
8419 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8420 return false;
8421
8422 // Check if it will be merged with the load.
8423 // 1. Check the alignment constraint.
8424 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8425 ResVT.getTypeForEVT(*DAG->getContext()));
8426
8427 if (RequiredAlignment > getAlignment())
8428 return false;
8429
8430 // 2. Check that the load is a legal operation for that type.
8431 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8432 return false;
8433
8434 // 3. Check that we do not have a zext in the way.
8435 if (Inst->getValueType(0) != getLoadedType())
8436 return false;
8437
8438 return true;
8439 }
8440};
8441}
8442
Quentin Colombetde0e0622013-10-11 18:29:42 +00008443/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8444/// \p UsedBits looks like 0..0 1..1 0..0.
8445static bool areUsedBitsDense(const APInt &UsedBits) {
8446 // If all the bits are one, this is dense!
8447 if (UsedBits.isAllOnesValue())
8448 return true;
8449
8450 // Get rid of the unused bits on the right.
8451 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8452 // Get rid of the unused bits on the left.
8453 if (NarrowedUsedBits.countLeadingZeros())
8454 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8455 // Check that the chunk of bits is completely used.
8456 return NarrowedUsedBits.isAllOnesValue();
8457}
8458
8459/// \brief Check whether or not \p First and \p Second are next to each other
8460/// in memory. This means that there is no hole between the bits loaded
8461/// by \p First and the bits loaded by \p Second.
8462static bool areSlicesNextToEachOther(const LoadedSlice &First,
8463 const LoadedSlice &Second) {
8464 assert(First.Origin == Second.Origin && First.Origin &&
8465 "Unable to match different memory origins.");
8466 APInt UsedBits = First.getUsedBits();
8467 assert((UsedBits & Second.getUsedBits()) == 0 &&
8468 "Slices are not supposed to overlap.");
8469 UsedBits |= Second.getUsedBits();
8470 return areUsedBitsDense(UsedBits);
8471}
8472
8473/// \brief Adjust the \p GlobalLSCost according to the target
8474/// paring capabilities and the layout of the slices.
8475/// \pre \p GlobalLSCost should account for at least as many loads as
8476/// there is in the slices in \p LoadedSlices.
8477static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8478 LoadedSlice::Cost &GlobalLSCost) {
8479 unsigned NumberOfSlices = LoadedSlices.size();
8480 // If there is less than 2 elements, no pairing is possible.
8481 if (NumberOfSlices < 2)
8482 return;
8483
8484 // Sort the slices so that elements that are likely to be next to each
8485 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008486 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8487 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8488 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8489 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8490 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008491 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8492 // First (resp. Second) is the first (resp. Second) potentially candidate
8493 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008494 const LoadedSlice *First = nullptr;
8495 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008496 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8497 // Set the beginning of the pair.
8498 First = Second) {
8499
8500 Second = &LoadedSlices[CurrSlice];
8501
8502 // If First is NULL, it means we start a new pair.
8503 // Get to the next slice.
8504 if (!First)
8505 continue;
8506
8507 EVT LoadedType = First->getLoadedType();
8508
8509 // If the types of the slices are different, we cannot pair them.
8510 if (LoadedType != Second->getLoadedType())
8511 continue;
8512
8513 // Check if the target supplies paired loads for this type.
8514 unsigned RequiredAlignment = 0;
8515 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8516 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008517 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008518 continue;
8519 }
8520 // Check if we meet the alignment requirement.
8521 if (RequiredAlignment > First->getAlignment())
8522 continue;
8523
8524 // Check that both loads are next to each other in memory.
8525 if (!areSlicesNextToEachOther(*First, *Second))
8526 continue;
8527
8528 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8529 --GlobalLSCost.Loads;
8530 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008531 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008532 }
8533}
8534
8535/// \brief Check the profitability of all involved LoadedSlice.
8536/// Currently, it is considered profitable if there is exactly two
8537/// involved slices (1) which are (2) next to each other in memory, and
8538/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8539///
8540/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8541/// the elements themselves.
8542///
8543/// FIXME: When the cost model will be mature enough, we can relax
8544/// constraints (1) and (2).
8545static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8546 const APInt &UsedBits, bool ForCodeSize) {
8547 unsigned NumberOfSlices = LoadedSlices.size();
8548 if (StressLoadSlicing)
8549 return NumberOfSlices > 1;
8550
8551 // Check (1).
8552 if (NumberOfSlices != 2)
8553 return false;
8554
8555 // Check (2).
8556 if (!areUsedBitsDense(UsedBits))
8557 return false;
8558
8559 // Check (3).
8560 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8561 // The original code has one big load.
8562 OrigCost.Loads = 1;
8563 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8564 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8565 // Accumulate the cost of all the slices.
8566 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8567 GlobalSlicingCost += SliceCost;
8568
8569 // Account as cost in the original configuration the gain obtained
8570 // with the current slices.
8571 OrigCost.addSliceGain(LS);
8572 }
8573
8574 // If the target supports paired load, adjust the cost accordingly.
8575 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8576 return OrigCost > GlobalSlicingCost;
8577}
8578
8579/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8580/// operations, split it in the various pieces being extracted.
8581///
8582/// This sort of thing is introduced by SROA.
8583/// This slicing takes care not to insert overlapping loads.
8584/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8585bool DAGCombiner::SliceUpLoad(SDNode *N) {
8586 if (Level < AfterLegalizeDAG)
8587 return false;
8588
8589 LoadSDNode *LD = cast<LoadSDNode>(N);
8590 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8591 !LD->getValueType(0).isInteger())
8592 return false;
8593
8594 // Keep track of already used bits to detect overlapping values.
8595 // In that case, we will just abort the transformation.
8596 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8597
8598 SmallVector<LoadedSlice, 4> LoadedSlices;
8599
8600 // Check if this load is used as several smaller chunks of bits.
8601 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8602 // of computation for each trunc.
8603 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8604 UI != UIEnd; ++UI) {
8605 // Skip the uses of the chain.
8606 if (UI.getUse().getResNo() != 0)
8607 continue;
8608
8609 SDNode *User = *UI;
8610 unsigned Shift = 0;
8611
8612 // Check if this is a trunc(lshr).
8613 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8614 isa<ConstantSDNode>(User->getOperand(1))) {
8615 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8616 User = *User->use_begin();
8617 }
8618
8619 // At this point, User is a Truncate, iff we encountered, trunc or
8620 // trunc(lshr).
8621 if (User->getOpcode() != ISD::TRUNCATE)
8622 return false;
8623
8624 // The width of the type must be a power of 2 and greater than 8-bits.
8625 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008626 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008627 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008628 unsigned Width = User->getValueSizeInBits(0);
8629 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8630 return 0;
8631
8632 // Build the slice for this chain of computations.
8633 LoadedSlice LS(User, LD, Shift, &DAG);
8634 APInt CurrentUsedBits = LS.getUsedBits();
8635
8636 // Check if this slice overlaps with another.
8637 if ((CurrentUsedBits & UsedBits) != 0)
8638 return false;
8639 // Update the bits used globally.
8640 UsedBits |= CurrentUsedBits;
8641
8642 // Check if the new slice would be legal.
8643 if (!LS.isLegal())
8644 return false;
8645
8646 // Record the slice.
8647 LoadedSlices.push_back(LS);
8648 }
8649
8650 // Abort slicing if it does not seem to be profitable.
8651 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8652 return false;
8653
8654 ++SlicedLoads;
8655
8656 // Rewrite each chain to use an independent load.
8657 // By construction, each chain can be represented by a unique load.
8658
8659 // Prepare the argument for the new token factor for all the slices.
8660 SmallVector<SDValue, 8> ArgChains;
8661 for (SmallVectorImpl<LoadedSlice>::const_iterator
8662 LSIt = LoadedSlices.begin(),
8663 LSItEnd = LoadedSlices.end();
8664 LSIt != LSItEnd; ++LSIt) {
8665 SDValue SliceInst = LSIt->loadSlice();
8666 CombineTo(LSIt->Inst, SliceInst, true);
8667 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8668 SliceInst = SliceInst.getOperand(0);
8669 assert(SliceInst->getOpcode() == ISD::LOAD &&
8670 "It takes more than a zext to get to the loaded slice!!");
8671 ArgChains.push_back(SliceInst.getValue(1));
8672 }
8673
8674 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008675 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008676 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8677 return true;
8678}
8679
Chris Lattner4041ab62010-04-15 04:48:01 +00008680/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8681/// load is having specific bytes cleared out. If so, return the byte size
8682/// being masked out and the shift amount.
8683static std::pair<unsigned, unsigned>
8684CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8685 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008686
Chris Lattner4041ab62010-04-15 04:48:01 +00008687 // Check for the structure we're looking for.
8688 if (V->getOpcode() != ISD::AND ||
8689 !isa<ConstantSDNode>(V->getOperand(1)) ||
8690 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8691 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008692
Chris Lattner3245afd2010-04-15 06:10:49 +00008693 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008694 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008695 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008696
Chris Lattner3245afd2010-04-15 06:10:49 +00008697 // The store should be chained directly to the load or be an operand of a
8698 // tokenfactor.
8699 if (LD == Chain.getNode())
8700 ; // ok.
8701 else if (Chain->getOpcode() != ISD::TokenFactor)
8702 return Result; // Fail.
8703 else {
8704 bool isOk = false;
8705 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8706 if (Chain->getOperand(i).getNode() == LD) {
8707 isOk = true;
8708 break;
8709 }
8710 if (!isOk) return Result;
8711 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008712
Chris Lattner4041ab62010-04-15 04:48:01 +00008713 // This only handles simple types.
8714 if (V.getValueType() != MVT::i16 &&
8715 V.getValueType() != MVT::i32 &&
8716 V.getValueType() != MVT::i64)
8717 return Result;
8718
8719 // Check the constant mask. Invert it so that the bits being masked out are
8720 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8721 // follow the sign bit for uniformity.
8722 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008723 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008724 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008725 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008726 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8727 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008728
Chris Lattner4041ab62010-04-15 04:48:01 +00008729 // See if we have a continuous run of bits. If so, we have 0*1+0*
8730 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8731 return Result;
8732
8733 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8734 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8735 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008736
Chris Lattner4041ab62010-04-15 04:48:01 +00008737 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8738 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008739 case 1:
8740 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008741 case 4: break;
8742 default: return Result; // All one mask, or 5-byte mask.
8743 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008744
Chris Lattner4041ab62010-04-15 04:48:01 +00008745 // Verify that the first bit starts at a multiple of mask so that the access
8746 // is aligned the same as the access width.
8747 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008748
Chris Lattner4041ab62010-04-15 04:48:01 +00008749 Result.first = MaskedBytes;
8750 Result.second = NotMaskTZ/8;
8751 return Result;
8752}
8753
8754
8755/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8756/// provides a value as specified by MaskInfo. If so, replace the specified
8757/// store with a narrower store of truncated IVal.
8758static SDNode *
8759ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8760 SDValue IVal, StoreSDNode *St,
8761 DAGCombiner *DC) {
8762 unsigned NumBytes = MaskInfo.first;
8763 unsigned ByteShift = MaskInfo.second;
8764 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008765
Chris Lattner4041ab62010-04-15 04:48:01 +00008766 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8767 // that uses this. If not, this is not a replacement.
8768 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8769 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008770 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008771
Chris Lattner4041ab62010-04-15 04:48:01 +00008772 // Check that it is legal on the target to do this. It is legal if the new
8773 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8774 // legalization.
8775 MVT VT = MVT::getIntegerVT(NumBytes*8);
8776 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008777 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008778
Chris Lattner4041ab62010-04-15 04:48:01 +00008779 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8780 // shifted by ByteShift and truncated down to NumBytes.
8781 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008782 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008783 DAG.getConstant(ByteShift*8,
8784 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008785
8786 // Figure out the offset for the store and the alignment of the access.
8787 unsigned StOffset;
8788 unsigned NewAlign = St->getAlignment();
8789
8790 if (DAG.getTargetLoweringInfo().isLittleEndian())
8791 StOffset = ByteShift;
8792 else
8793 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008794
Chris Lattner4041ab62010-04-15 04:48:01 +00008795 SDValue Ptr = St->getBasePtr();
8796 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008797 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008798 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8799 NewAlign = MinAlign(NewAlign, StOffset);
8800 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008801
Chris Lattner4041ab62010-04-15 04:48:01 +00008802 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008803 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008804
Chris Lattner4041ab62010-04-15 04:48:01 +00008805 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008806 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008807 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008808 false, false, NewAlign).getNode();
8809}
8810
Evan Chenga9cda8a2009-05-28 00:35:15 +00008811
8812/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8813/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8814/// of the loaded bits, try narrowing the load and store if it would end up
8815/// being a win for performance or code size.
8816SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8817 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008818 if (ST->isVolatile())
8819 return SDValue();
8820
Evan Chenga9cda8a2009-05-28 00:35:15 +00008821 SDValue Chain = ST->getChain();
8822 SDValue Value = ST->getValue();
8823 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008824 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008825
8826 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008827 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008828
8829 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008830
Chris Lattner4041ab62010-04-15 04:48:01 +00008831 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8832 // is a byte mask indicating a consecutive number of bytes, check to see if
8833 // Y is known to provide just those bytes. If so, we try to replace the
8834 // load + replace + store sequence with a single (narrower) store, which makes
8835 // the load dead.
8836 if (Opc == ISD::OR) {
8837 std::pair<unsigned, unsigned> MaskedLoad;
8838 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8839 if (MaskedLoad.first)
8840 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8841 Value.getOperand(1), ST,this))
8842 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008843
Chris Lattner4041ab62010-04-15 04:48:01 +00008844 // Or is commutative, so try swapping X and Y.
8845 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8846 if (MaskedLoad.first)
8847 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8848 Value.getOperand(0), ST,this))
8849 return SDValue(NewST, 0);
8850 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008851
Evan Chenga9cda8a2009-05-28 00:35:15 +00008852 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8853 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008854 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008855
8856 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008857 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8858 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008859 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008860 if (LD->getBasePtr() != Ptr ||
8861 LD->getPointerInfo().getAddrSpace() !=
8862 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008863 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008864
8865 // Find the type to narrow it the load / op / store to.
8866 SDValue N1 = Value.getOperand(1);
8867 unsigned BitWidth = N1.getValueSizeInBits();
8868 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8869 if (Opc == ISD::AND)
8870 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008871 if (Imm == 0 || Imm.isAllOnesValue())
8872 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008873 unsigned ShAmt = Imm.countTrailingZeros();
8874 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8875 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008876 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008877 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008878 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008879 TLI.isNarrowingProfitable(VT, NewVT))) {
8880 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008881 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008882 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008883 if (NewBW >= BitWidth)
8884 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008885
8886 // If the lsb changed does not start at the type bitwidth boundary,
8887 // start at the previous one.
8888 if (ShAmt % NewBW)
8889 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008890 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8891 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008892 if ((Imm & Mask) == Imm) {
8893 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8894 if (Opc == ISD::AND)
8895 NewImm ^= APInt::getAllOnesValue(NewBW);
8896 uint64_t PtrOff = ShAmt / 8;
8897 // For big endian targets, we need to adjust the offset to the pointer to
8898 // load the correct bytes.
8899 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008900 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008901
8902 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008903 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008904 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008905 return SDValue();
8906
Andrew Trickef9de2a2013-05-25 02:42:55 +00008907 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008908 Ptr.getValueType(), Ptr,
8909 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008910 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008911 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008912 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008913 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008914 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00008915 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008916 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008917 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008918 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008919 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008920 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008921 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008922
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008923 AddToWorklist(NewPtr.getNode());
8924 AddToWorklist(NewLD.getNode());
8925 AddToWorklist(NewVal.getNode());
8926 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008927 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008928 ++OpsNarrowed;
8929 return NewST;
8930 }
8931 }
8932
Evan Cheng6673ff02009-05-28 18:41:02 +00008933 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008934}
8935
Evan Chengd42641c2011-02-02 01:06:55 +00008936/// TransformFPLoadStorePair - For a given floating point load / store pair,
8937/// if the load value isn't used by any other operations, then consider
8938/// transforming the pair to integer load / store operations if the target
8939/// deems the transformation profitable.
8940SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8941 StoreSDNode *ST = cast<StoreSDNode>(N);
8942 SDValue Chain = ST->getChain();
8943 SDValue Value = ST->getValue();
8944 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8945 Value.hasOneUse() &&
8946 Chain == SDValue(Value.getNode(), 1)) {
8947 LoadSDNode *LD = cast<LoadSDNode>(Value);
8948 EVT VT = LD->getMemoryVT();
8949 if (!VT.isFloatingPoint() ||
8950 VT != ST->getMemoryVT() ||
8951 LD->isNonTemporal() ||
8952 ST->isNonTemporal() ||
8953 LD->getPointerInfo().getAddrSpace() != 0 ||
8954 ST->getPointerInfo().getAddrSpace() != 0)
8955 return SDValue();
8956
8957 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8958 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8959 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8960 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8961 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8962 return SDValue();
8963
8964 unsigned LDAlign = LD->getAlignment();
8965 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008966 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008967 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008968 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8969 return SDValue();
8970
Andrew Trickef9de2a2013-05-25 02:42:55 +00008971 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008972 LD->getChain(), LD->getBasePtr(),
8973 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008974 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008975
Andrew Trickef9de2a2013-05-25 02:42:55 +00008976 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008977 NewLD, ST->getBasePtr(),
8978 ST->getPointerInfo(),
8979 false, false, STAlign);
8980
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008981 AddToWorklist(NewLD.getNode());
8982 AddToWorklist(NewST.getNode());
8983 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008984 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008985 ++LdStFP2Int;
8986 return NewST;
8987 }
8988
8989 return SDValue();
8990}
8991
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008992/// Helper struct to parse and store a memory address as base + index + offset.
8993/// We ignore sign extensions when it is safe to do so.
8994/// The following two expressions are not equivalent. To differentiate we need
8995/// to store whether there was a sign extension involved in the index
8996/// computation.
8997/// (load (i64 add (i64 copyfromreg %c)
8998/// (i64 signextend (add (i8 load %index)
8999/// (i8 1))))
9000/// vs
9001///
9002/// (load (i64 add (i64 copyfromreg %c)
9003/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9004/// (i32 1)))))
9005struct BaseIndexOffset {
9006 SDValue Base;
9007 SDValue Index;
9008 int64_t Offset;
9009 bool IsIndexSignExt;
9010
9011 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9012
9013 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9014 bool IsIndexSignExt) :
9015 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9016
9017 bool equalBaseIndex(const BaseIndexOffset &Other) {
9018 return Other.Base == Base && Other.Index == Index &&
9019 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009020 }
9021
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009022 /// Parses tree in Ptr for base, index, offset addresses.
9023 static BaseIndexOffset match(SDValue Ptr) {
9024 bool IsIndexSignExt = false;
9025
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009026 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9027 // instruction, then it could be just the BASE or everything else we don't
9028 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009029 if (Ptr->getOpcode() != ISD::ADD)
9030 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9031
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009032 // We know that we have at least an ADD instruction. Try to pattern match
9033 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009034 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9035 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9036 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9037 IsIndexSignExt);
9038 }
9039
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009040 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009041 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009042 // (i64 add (i64 %array_ptr)
9043 // (i64 mul (i64 %induction_var)
9044 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009045 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009046 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009047
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009048 // Look at Base + Index + Offset cases.
9049 SDValue Base = Ptr->getOperand(0);
9050 SDValue IndexOffset = Ptr->getOperand(1);
9051
9052 // Skip signextends.
9053 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9054 IndexOffset = IndexOffset->getOperand(0);
9055 IsIndexSignExt = true;
9056 }
9057
9058 // Either the case of Base + Index (no offset) or something else.
9059 if (IndexOffset->getOpcode() != ISD::ADD)
9060 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9061
9062 // Now we have the case of Base + Index + offset.
9063 SDValue Index = IndexOffset->getOperand(0);
9064 SDValue Offset = IndexOffset->getOperand(1);
9065
9066 if (!isa<ConstantSDNode>(Offset))
9067 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9068
9069 // Ignore signextends.
9070 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9071 Index = Index->getOperand(0);
9072 IsIndexSignExt = true;
9073 } else IsIndexSignExt = false;
9074
9075 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9076 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9077 }
9078};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009079
9080/// Holds a pointer to an LSBaseSDNode as well as information on where it
9081/// is located in a sequence of memory operations connected by a chain.
9082struct MemOpLink {
9083 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9084 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9085 // Ptr to the mem node.
9086 LSBaseSDNode *MemNode;
9087 // Offset from the base ptr.
9088 int64_t OffsetFromBase;
9089 // What is the sequence number of this mem node.
9090 // Lowest mem operand in the DAG starts at zero.
9091 unsigned SequenceNum;
9092};
9093
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009094bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9095 EVT MemVT = St->getMemoryVT();
9096 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009097 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9098 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009099
9100 // Don't merge vectors into wider inputs.
9101 if (MemVT.isVector() || !MemVT.isSimple())
9102 return false;
9103
9104 // Perform an early exit check. Do not bother looking at stored values that
9105 // are not constants or loads.
9106 SDValue StoredVal = St->getValue();
9107 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9108 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9109 !IsLoadSrc)
9110 return false;
9111
9112 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +00009113 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009114 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9115 return false;
9116
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009117 // This holds the base pointer, index, and the offset in bytes from the base
9118 // pointer.
9119 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009120
9121 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009122 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009123 return false;
9124
9125 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009126 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009127 return false;
9128
Nadav Rotem307d7672012-11-29 00:00:08 +00009129 // Save the LoadSDNodes that we find in the chain.
9130 // We need to make sure that these nodes do not interfere with
9131 // any of the store nodes.
9132 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9133
9134 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009135 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009136
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009137 // Walk up the chain and look for nodes with offsets from the same
9138 // base pointer. Stop when reaching an instruction with a different kind
9139 // or instruction which has a different base pointer.
9140 unsigned Seq = 0;
9141 StoreSDNode *Index = St;
9142 while (Index) {
9143 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +00009144 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009145 break;
9146
9147 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009148 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009149
9150 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009151 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009152 break;
9153
9154 // Check that the alignment is the same.
9155 if (Index->getAlignment() != St->getAlignment())
9156 break;
9157
9158 // The memory operands must not be volatile.
9159 if (Index->isVolatile() || Index->isIndexed())
9160 break;
9161
9162 // No truncation.
9163 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9164 if (St->isTruncatingStore())
9165 break;
9166
9167 // The stored memory type must be the same.
9168 if (Index->getMemoryVT() != MemVT)
9169 break;
9170
9171 // We do not allow unaligned stores because we want to prevent overriding
9172 // stores.
9173 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9174 break;
9175
9176 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009177 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009178
Nadav Rotem307d7672012-11-29 00:00:08 +00009179 // Find the next memory operand in the chain. If the next operand in the
9180 // chain is a store then move up and continue the scan with the next
9181 // memory operand. If the next operand is a load save it and use alias
9182 // information to check if it interferes with anything.
9183 SDNode *NextInChain = Index->getChain().getNode();
9184 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009185 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009186 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009187 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009188 break;
9189 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009190 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009191 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009192 break;
9193 }
9194
Nadav Rotem307d7672012-11-29 00:00:08 +00009195 // Save the load node for later. Continue the scan.
9196 AliasLoadNodes.push_back(Ldn);
9197 NextInChain = Ldn->getChain().getNode();
9198 continue;
9199 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009200 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009201 break;
9202 }
9203 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009204 }
9205
9206 // Check if there is anything to merge.
9207 if (StoreNodes.size() < 2)
9208 return false;
9209
9210 // Sort the memory operands according to their distance from the base pointer.
9211 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009212 [](MemOpLink LHS, MemOpLink RHS) {
9213 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9214 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9215 LHS.SequenceNum > RHS.SequenceNum);
9216 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009217
9218 // Scan the memory operations on the chain and find the first non-consecutive
9219 // store memory address.
9220 unsigned LastConsecutiveStore = 0;
9221 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009222 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9223
9224 // Check that the addresses are consecutive starting from the second
9225 // element in the list of stores.
9226 if (i > 0) {
9227 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9228 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9229 break;
9230 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009231
Nadav Rotem307d7672012-11-29 00:00:08 +00009232 bool Alias = false;
9233 // Check if this store interferes with any of the loads that we found.
9234 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9235 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9236 Alias = true;
9237 break;
9238 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009239 // We found a load that alias with this store. Stop the sequence.
9240 if (Alias)
9241 break;
9242
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009243 // Mark this node as useful.
9244 LastConsecutiveStore = i;
9245 }
9246
9247 // The node with the lowest store address.
9248 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9249
9250 // Store the constants into memory as one consecutive store.
9251 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009252 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009253 unsigned LastLegalVectorType = 0;
9254 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009255 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9256 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9257 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009258
9259 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009260 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009261 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009262 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009263 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009264 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009265 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009266 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009267
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009268 // Find a legal type for the constant store.
9269 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9270 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9271 if (TLI.isTypeLegal(StoreTy))
9272 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009273 // Or check whether a truncstore is legal.
9274 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9275 TargetLowering::TypePromoteInteger) {
9276 EVT LegalizedStoredValueTy =
9277 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9278 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9279 LastLegalType = i+1;
9280 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009281
9282 // Find a legal type for the vector store.
9283 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9284 if (TLI.isTypeLegal(Ty))
9285 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009286 }
9287
Bob Wilson3365b802012-12-20 01:36:20 +00009288 // We only use vectors if the constant is known to be zero and the
9289 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009290 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009291 LastLegalVectorType = 0;
9292
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009293 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009294 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009295 return false;
9296
Nadav Rotem495b1a42013-02-14 18:28:52 +00009297 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009298 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9299
9300 // Make sure we have something to merge.
9301 if (NumElem < 2)
9302 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009303
9304 unsigned EarliestNodeUsed = 0;
9305 for (unsigned i=0; i < NumElem; ++i) {
9306 // Find a chain for the new wide-store operand. Notice that some
9307 // of the store nodes that we found may not be selected for inclusion
9308 // in the wide store. The chain we use needs to be the chain of the
9309 // earliest store node which is *used* and replaced by the wide store.
9310 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9311 EarliestNodeUsed = i;
9312 }
9313
9314 // The earliest Node in the DAG.
9315 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009316 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009317
Nadav Rotemb27777f2012-10-04 22:35:15 +00009318 SDValue StoredVal;
9319 if (UseVector) {
9320 // Find a legal type for the vector store.
9321 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9322 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9323 StoredVal = DAG.getConstant(0, Ty);
9324 } else {
9325 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9326 APInt StoreInt(StoreBW, 0);
9327
9328 // Construct a single integer constant which is made of the smaller
9329 // constant inputs.
9330 bool IsLE = TLI.isLittleEndian();
9331 for (unsigned i = 0; i < NumElem ; ++i) {
9332 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9333 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9334 SDValue Val = St->getValue();
9335 StoreInt<<=ElementSizeBytes*8;
9336 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9337 StoreInt|=C->getAPIntValue().zext(StoreBW);
9338 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9339 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9340 } else {
9341 assert(false && "Invalid constant element type");
9342 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009343 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009344
9345 // Create the new Load and Store operations.
9346 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9347 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009348 }
9349
Nadav Rotemb27777f2012-10-04 22:35:15 +00009350 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009351 FirstInChain->getBasePtr(),
9352 FirstInChain->getPointerInfo(),
9353 false, false,
9354 FirstInChain->getAlignment());
9355
9356 // Replace the first store with the new store
9357 CombineTo(EarliestOp, NewStore);
9358 // Erase all other stores.
9359 for (unsigned i = 0; i < NumElem ; ++i) {
9360 if (StoreNodes[i].MemNode == EarliestOp)
9361 continue;
9362 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009363 // ReplaceAllUsesWith will replace all uses that existed when it was
9364 // called, but graph optimizations may cause new ones to appear. For
9365 // example, the case in pr14333 looks like
9366 //
9367 // St's chain -> St -> another store -> X
9368 //
9369 // And the only difference from St to the other store is the chain.
9370 // When we change it's chain to be St's chain they become identical,
9371 // get CSEed and the net result is that X is now a use of St.
9372 // Since we know that St is redundant, just iterate.
9373 while (!St->use_empty())
9374 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009375 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009376 }
9377
9378 return true;
9379 }
9380
9381 // Below we handle the case of multiple consecutive stores that
9382 // come from multiple consecutive loads. We merge them into a single
9383 // wide load and a single wide store.
9384
9385 // Look for load nodes which are used by the stored values.
9386 SmallVector<MemOpLink, 8> LoadNodes;
9387
9388 // Find acceptable loads. Loads need to have the same chain (token factor),
9389 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009390 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009391 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9392 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9393 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9394 if (!Ld) break;
9395
9396 // Loads must only have one use.
9397 if (!Ld->hasNUsesOfValue(1, 0))
9398 break;
9399
9400 // Check that the alignment is the same as the stores.
9401 if (Ld->getAlignment() != St->getAlignment())
9402 break;
9403
9404 // The memory operands must not be volatile.
9405 if (Ld->isVolatile() || Ld->isIndexed())
9406 break;
9407
9408 // We do not accept ext loads.
9409 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9410 break;
9411
9412 // The stored memory type must be the same.
9413 if (Ld->getMemoryVT() != MemVT)
9414 break;
9415
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009416 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009417 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009418 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009419 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009420 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009421 break;
9422 } else {
9423 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009424 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009425 }
9426
9427 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009428 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009429 }
9430
9431 if (LoadNodes.size() < 2)
9432 return false;
9433
James Molloyce45be02014-08-02 14:51:24 +00009434 // If we have load/store pair instructions and we only have two values,
9435 // don't bother.
9436 unsigned RequiredAlignment;
9437 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9438 St->getAlignment() >= RequiredAlignment)
9439 return false;
9440
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009441 // Scan the memory operations on the chain and find the first non-consecutive
9442 // load memory address. These variables hold the index in the store node
9443 // array.
9444 unsigned LastConsecutiveLoad = 0;
9445 // This variable refers to the size and not index in the array.
9446 unsigned LastLegalVectorType = 0;
9447 unsigned LastLegalIntegerType = 0;
9448 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009449 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9450 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9451 // All loads much share the same chain.
9452 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9453 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009454
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009455 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9456 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9457 break;
9458 LastConsecutiveLoad = i;
9459
9460 // Find a legal type for the vector store.
9461 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9462 if (TLI.isTypeLegal(StoreTy))
9463 LastLegalVectorType = i + 1;
9464
9465 // Find a legal type for the integer store.
9466 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9467 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9468 if (TLI.isTypeLegal(StoreTy))
9469 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009470 // Or check whether a truncstore and extload is legal.
9471 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9472 TargetLowering::TypePromoteInteger) {
9473 EVT LegalizedStoredValueTy =
9474 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9475 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9476 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9477 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9478 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9479 LastLegalIntegerType = i+1;
9480 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009481 }
9482
9483 // Only use vector types if the vector type is larger than the integer type.
9484 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009485 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009486 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9487
9488 // We add +1 here because the LastXXX variables refer to location while
9489 // the NumElem refers to array/index size.
9490 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9491 NumElem = std::min(LastLegalType, NumElem);
9492
9493 if (NumElem < 2)
9494 return false;
9495
9496 // The earliest Node in the DAG.
9497 unsigned EarliestNodeUsed = 0;
9498 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9499 for (unsigned i=1; i<NumElem; ++i) {
9500 // Find a chain for the new wide-store operand. Notice that some
9501 // of the store nodes that we found may not be selected for inclusion
9502 // in the wide store. The chain we use needs to be the chain of the
9503 // earliest store node which is *used* and replaced by the wide store.
9504 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9505 EarliestNodeUsed = i;
9506 }
9507
9508 // Find if it is better to use vectors or integers to load and store
9509 // to memory.
9510 EVT JointMemOpVT;
9511 if (UseVectorTy) {
9512 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9513 } else {
9514 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9515 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9516 }
9517
Andrew Trickef9de2a2013-05-25 02:42:55 +00009518 SDLoc LoadDL(LoadNodes[0].MemNode);
9519 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009520
9521 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9522 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9523 FirstLoad->getChain(),
9524 FirstLoad->getBasePtr(),
9525 FirstLoad->getPointerInfo(),
9526 false, false, false,
9527 FirstLoad->getAlignment());
9528
9529 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9530 FirstInChain->getBasePtr(),
9531 FirstInChain->getPointerInfo(), false, false,
9532 FirstInChain->getAlignment());
9533
Nadav Rotemac920662012-10-03 19:30:31 +00009534 // Replace one of the loads with the new load.
9535 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9536 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9537 SDValue(NewLoad.getNode(), 1));
9538
9539 // Remove the rest of the load chains.
9540 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009541 // Replace all chain users of the old load nodes with the chain of the new
9542 // load node.
9543 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009544 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9545 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009546
Nadav Rotemac920662012-10-03 19:30:31 +00009547 // Replace the first store with the new store.
9548 CombineTo(EarliestOp, NewStore);
9549 // Erase all other stores.
9550 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009551 // Remove all Store nodes.
9552 if (StoreNodes[i].MemNode == EarliestOp)
9553 continue;
9554 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9555 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009556 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009557 }
9558
9559 return true;
9560}
9561
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009562SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009563 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009564 SDValue Chain = ST->getChain();
9565 SDValue Value = ST->getValue();
9566 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009567
Evan Chenga4cf58a2007-05-07 21:27:48 +00009568 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009569 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009570 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009571 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009572 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009573 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009574 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009575 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009576 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009577 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009578 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009579 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009580 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009581 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009582 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009583 }
Owen Andersona5192842011-04-14 17:30:49 +00009584
Chris Lattner41c80e82011-04-09 02:32:02 +00009585 // Turn 'store undef, Ptr' -> nothing.
9586 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9587 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009588
Nate Begeman8e20c762006-12-11 02:23:46 +00009589 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009590 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009591 // NOTE: If the original store is volatile, this transform must not increase
9592 // the number of stores. For example, on x86-32 an f64 can be stored in one
9593 // processor operation but an i64 (which is not legal) requires two. So the
9594 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009595 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009596 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009597 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009598 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009599 case MVT::f16: // We don't do this for these yet.
9600 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009601 case MVT::f128:
9602 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009603 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009604 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009605 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009606 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009607 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009608 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009609 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009610 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009611 }
9612 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009613 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009614 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009615 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009616 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009617 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009618 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009619 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009620 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009621 }
Owen Andersona5192842011-04-14 17:30:49 +00009622
Chris Lattner41c80e82011-04-09 02:32:02 +00009623 if (!ST->isVolatile() &&
9624 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009625 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009626 // argument passing. Since this is so common, custom legalize the
9627 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009628 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009629 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9630 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009631 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009632
Dan Gohman2af30632007-07-09 22:18:38 +00009633 unsigned Alignment = ST->getAlignment();
9634 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009635 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +00009636 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009637
Andrew Trickef9de2a2013-05-25 02:42:55 +00009638 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009639 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009640 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009641 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009642 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009643 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009644 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009645 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009646 Ptr, ST->getPointerInfo().getWithOffset(4),
9647 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +00009648 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009649 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009650 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009651 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009652
Chris Lattnerb7524b62006-12-12 04:16:14 +00009653 break;
Evan Cheng21836982006-12-11 17:25:19 +00009654 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009655 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009656 }
9657
Evan Cheng43cd9e32010-04-01 06:04:33 +00009658 // Try to infer better alignment information than the store already has.
9659 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009660 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9661 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009662 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009663 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009664 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +00009665 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009666 }
9667 }
9668
Evan Chengd42641c2011-02-02 01:06:55 +00009669 // Try transforming a pair floating point load / store ops to integer
9670 // load / store ops.
9671 SDValue NewST = TransformFPLoadStorePair(N);
9672 if (NewST.getNode())
9673 return NewST;
9674
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009675 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9676 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009677#ifndef NDEBUG
9678 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9679 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9680 UseAA = false;
9681#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009682 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009683 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009684 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009685
Jim Laskey708d0db2006-10-04 16:53:27 +00009686 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009687 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009688 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009689
9690 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009691 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009692 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009693 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009694 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009695 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009696 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009697 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009698
Jim Laskeyd07be232006-09-25 16:29:54 +00009699 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009700 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009701 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009702
Nate Begeman879d8f12009-09-15 00:18:30 +00009703 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009704 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +00009705
Jim Laskeydcf983c2006-10-13 23:32:28 +00009706 // Don't add users to work list.
9707 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009708 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009709 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009710
Evan Cheng33157702006-11-05 09:31:14 +00009711 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009712 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009713 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009714
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009715 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009716 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009717 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009718 // See if we can simplify the input to this truncstore with knowledge that
9719 // only the low bits are being used. For example:
9720 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009721 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009722 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009723 APInt::getLowBitsSet(
9724 Value.getValueType().getScalarType().getSizeInBits(),
9725 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009726 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00009727 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009728 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009729 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009730
Chris Lattnerf47e3062007-10-13 06:58:48 +00009731 // Otherwise, see if we can simplify the operation with
9732 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009733 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009734 APInt::getLowBitsSet(
9735 Value.getValueType().getScalarType().getSizeInBits(),
9736 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009737 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009738 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009739
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009740 // If this is a load followed by a store to the same location, then the store
9741 // is dead/noop.
9742 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009743 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009744 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009745 // There can't be any side effects between the load and store, such as
9746 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009747 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009748 // The store is dead, remove it.
9749 return Chain;
9750 }
9751 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009752
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009753 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9754 // truncating store. We can do this even if this is already a truncstore.
9755 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009756 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009757 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009758 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009759 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009760 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009761 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009762
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009763 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009764 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009765 if (!LegalTypes) {
9766 bool EverChanged = false;
9767
9768 do {
9769 // There can be multiple store sequences on the same chain.
9770 // Keep trying to merge store sequences until we are unable to do so
9771 // or until we merge the last store on the chain.
9772 bool Changed = MergeConsecutiveStores(ST);
9773 EverChanged |= Changed;
9774 if (!Changed) break;
9775 } while (ST->getOpcode() != ISD::DELETED_NODE);
9776
9777 if (EverChanged)
9778 return SDValue(N, 0);
9779 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009780
Evan Chenga9cda8a2009-05-28 00:35:15 +00009781 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009782}
9783
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009784SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9785 SDValue InVec = N->getOperand(0);
9786 SDValue InVal = N->getOperand(1);
9787 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009788 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009789
Bob Wilson42603952010-05-19 23:42:58 +00009790 // If the inserted element is an UNDEF, just use the input vector.
9791 if (InVal.getOpcode() == ISD::UNDEF)
9792 return InVec;
9793
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009794 EVT VT = InVec.getValueType();
9795
Owen Andersonb2c80da2011-02-25 21:41:48 +00009796 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009797 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9798 return SDValue();
9799
Eli Friedmanb7910b72011-09-09 21:04:06 +00009800 // Check that we know which element is being inserted
9801 if (!isa<ConstantSDNode>(EltNo))
9802 return SDValue();
9803 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009804
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009805 // Canonicalize insert_vector_elt dag nodes.
9806 // Example:
9807 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9808 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9809 //
9810 // Do this only if the child insert_vector node has one use; also
9811 // do this only if indices are both constants and Idx1 < Idx0.
9812 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9813 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9814 unsigned OtherElt =
9815 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9816 if (Elt < OtherElt) {
9817 // Swap nodes.
9818 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9819 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009820 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009821 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9822 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9823 }
9824 }
9825
Eli Friedmanb7910b72011-09-09 21:04:06 +00009826 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9827 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9828 // vector elements.
9829 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009830 // Do not combine these two vectors if the output vector will not replace
9831 // the input vector.
9832 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009833 Ops.append(InVec.getNode()->op_begin(),
9834 InVec.getNode()->op_end());
9835 } else if (InVec.getOpcode() == ISD::UNDEF) {
9836 unsigned NElts = VT.getVectorNumElements();
9837 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9838 } else {
9839 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009840 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009841
9842 // Insert the element
9843 if (Elt < Ops.size()) {
9844 // All the operands of BUILD_VECTOR must have the same type;
9845 // we enforce that here.
9846 EVT OpVT = Ops[0].getValueType();
9847 if (InVal.getValueType() != OpVT)
9848 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9849 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9850 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9851 Ops[Elt] = InVal;
9852 }
9853
9854 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009855 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009856}
9857
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009858SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009859 // (vextract (scalar_to_vector val, 0) -> val
9860 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009861 EVT VT = InVec.getValueType();
9862 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009863
Duncan Sands6be291a2011-05-09 08:03:33 +00009864 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9865 // Check if the result type doesn't match the inserted element type. A
9866 // SCALAR_TO_VECTOR may truncate the inserted element and the
9867 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9868 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009869 if (InOp.getValueType() != NVT) {
9870 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009871 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009872 }
9873 return InOp;
9874 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009875
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009876 SDValue EltNo = N->getOperand(1);
9877 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9878
9879 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9880 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009881 // we may introduce new vector instructions which are not backed by TD
9882 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009883 // without using extract_subvector. However, if we can find an underlying
9884 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009885 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009886 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009887 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9888 int NumElem = VT.getVectorNumElements();
9889 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9890 // Find the new index to extract from.
9891 int OrigElt = SVOp->getMaskElt(Elt);
9892
9893 // Extracting an undef index is undef.
9894 if (OrigElt == -1)
9895 return DAG.getUNDEF(NVT);
9896
9897 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009898 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009899 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009900 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009901 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009902 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009903 OrigElt -= NumElem;
9904 }
9905
Hal Finkel02807592014-03-31 11:43:19 +00009906 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9907 SDValue InOp = SVInVec.getOperand(OrigElt);
9908 if (InOp.getValueType() != NVT) {
9909 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9910 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9911 }
9912
9913 return InOp;
9914 }
9915
9916 // FIXME: We should handle recursing on other vector shuffles and
9917 // scalar_to_vector here as well.
9918
9919 if (!LegalOperations) {
9920 EVT IndexTy = TLI.getVectorIdxTy();
9921 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9922 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9923 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009924 }
9925
Evan Cheng1120279a2008-05-13 08:35:03 +00009926 // Perform only after legalization to ensure build_vector / vector_shuffle
9927 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009928 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009929
Mon P Wangca6d6de2009-01-17 00:07:25 +00009930 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9931 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9932 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009933
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009934 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009935 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Michael J. Spencer1eb02302014-07-18 00:15:50 +00009936 bool NewLoad = false;
9937 bool BCNumEltsChanged = false;
9938 EVT ExtVT = VT.getVectorElementType();
9939 EVT LVT = ExtVT;
9940
9941 // If the result of load has to be truncated, then it's not necessarily
9942 // profitable.
9943 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9944 return SDValue();
9945
9946 if (InVec.getOpcode() == ISD::BITCAST) {
9947 // Don't duplicate a load with other uses.
9948 if (!InVec.hasOneUse())
9949 return SDValue();
9950
9951 EVT BCVT = InVec.getOperand(0).getValueType();
9952 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9953 return SDValue();
9954 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9955 BCNumEltsChanged = true;
9956 InVec = InVec.getOperand(0);
9957 ExtVT = BCVT.getVectorElementType();
9958 NewLoad = true;
9959 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009960
Craig Topperc0196b12014-04-14 00:51:57 +00009961 LoadSDNode *LN0 = nullptr;
9962 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009963 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009964 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009965 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009966 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009967 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009968 // Don't duplicate a load with other uses.
9969 if (!InVec.hasOneUse())
9970 return SDValue();
9971
Evan Cheng1120279a2008-05-13 08:35:03 +00009972 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009973 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009974 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9975 // =>
9976 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009977
Eli Friedmane96286c2011-12-26 22:49:32 +00009978 // Don't duplicate a load with other uses.
9979 if (!InVec.hasOneUse())
9980 return SDValue();
9981
Mon P Wangb5eb7202008-12-11 00:26:16 +00009982 // If the bit convert changed the number of elements, it is unsafe
9983 // to examine the mask.
9984 if (BCNumEltsChanged)
9985 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009986
9987 // Select the input vector, guarding against out of range extract vector.
9988 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009989 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009990 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9991
Eli Friedmane96286c2011-12-26 22:49:32 +00009992 if (InVec.getOpcode() == ISD::BITCAST) {
9993 // Don't duplicate a load with other uses.
9994 if (!InVec.hasOneUse())
9995 return SDValue();
9996
Evan Cheng1120279a2008-05-13 08:35:03 +00009997 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009998 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009999 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010000 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010001 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +000010002 }
10003 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010004
Eli Friedmane96286c2011-12-26 22:49:32 +000010005 // Make sure we found a non-volatile load and the extractelement is
10006 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010007 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010008 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010009
Eric Christopherc6418b12010-11-03 20:44:42 +000010010 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10011 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010012 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010013
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010014 unsigned Align = LN0->getAlignment();
10015 if (NewLoad) {
10016 // Check the resultant load doesn't need a higher alignment than the
10017 // original load.
10018 unsigned NewAlign =
10019 TLI.getDataLayout()
10020 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
10021
10022 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
10023 return SDValue();
10024
10025 Align = NewAlign;
10026 }
10027
10028 SDValue NewPtr = LN0->getBasePtr();
10029 unsigned PtrOff = 0;
10030
10031 if (Elt) {
10032 PtrOff = LVT.getSizeInBits() * Elt / 8;
10033 EVT PtrType = NewPtr.getValueType();
10034 if (TLI.isBigEndian())
10035 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
10036 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
10037 DAG.getConstant(PtrOff, PtrType));
10038 }
10039
10040 // The replacement we need to do here is a little tricky: we need to
10041 // replace an extractelement of a load with a load.
10042 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10043 // Note that this replacement assumes that the extractvalue is the only
10044 // use of the load; that's okay because we don't want to perform this
10045 // transformation in other cases anyway.
10046 SDValue Load;
10047 SDValue Chain;
10048 if (NVT.bitsGT(LVT)) {
10049 // If the result type of vextract is wider than the load, then issue an
10050 // extending load instead.
10051 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10052 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10053 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10054 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10055 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000010056 LN0->isInvariant(), Align, LN0->getAAInfo());
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010057 Chain = Load.getValue(1);
10058 } else {
10059 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10060 LN0->getPointerInfo().getWithOffset(PtrOff),
10061 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +000010062 LN0->isInvariant(), Align, LN0->getAAInfo());
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010063 Chain = Load.getValue(1);
10064 if (NVT.bitsLT(LVT))
10065 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10066 else
10067 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10068 }
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010069 WorklistRemover DeadNodes(*this);
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010070 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10071 SDValue To[] = { Load, Chain };
10072 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10073 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10074 // worklist explicitly as well.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010075 AddToWorklist(Load.getNode());
10076 AddUsersToWorklist(Load.getNode()); // Add users too
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010077 // Make sure to revisit this node to clean it up; it will usually be dead.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010078 AddToWorklist(N);
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010079 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010080 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010081
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010082 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010083}
Evan Cheng0de312d2007-10-06 08:19:55 +000010084
Michael Liao6d106b72012-10-23 23:06:52 +000010085// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10086SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10087 // We perform this optimization post type-legalization because
10088 // the type-legalizer often scalarizes integer-promoted vectors.
10089 // Performing this optimization before may create bit-casts which
10090 // will be type-legalized to complex code sequences.
10091 // We perform this optimization only before the operation legalizer because we
10092 // may introduce illegal operations.
10093 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10094 return SDValue();
10095
Dan Gohmana8665142007-06-25 16:23:39 +000010096 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010097 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010098 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010099
Nadav Rotembf6568b2011-10-29 21:23:04 +000010100 // Check to see if this is a BUILD_VECTOR of a bunch of values
10101 // which come from any_extend or zero_extend nodes. If so, we can create
10102 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010103 // optimizations. We do not handle sign-extend because we can't fill the sign
10104 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010105 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010106 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010107
Craig Topper02cb0fb2012-01-17 09:09:48 +000010108 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010109 SDValue In = N->getOperand(i);
10110 // Ignore undef inputs.
10111 if (In.getOpcode() == ISD::UNDEF) continue;
10112
10113 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10114 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10115
Nadav Rotemf3103612011-10-31 20:08:25 +000010116 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010117 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010118 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010119 break;
10120 }
10121
10122 // The input is a ZeroExt or AnyExt. Check the original type.
10123 EVT InTy = In.getOperand(0).getValueType();
10124
10125 // Check that all of the widened source types are the same.
10126 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010127 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010128 SourceType = InTy;
10129 else if (InTy != SourceType) {
10130 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010131 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010132 break;
10133 }
10134
10135 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010136 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010137 }
10138
Nadav Rotemf3103612011-10-31 20:08:25 +000010139 // In order to have valid types, all of the inputs must be extended from the
10140 // same source type and all of the inputs must be any or zero extend.
10141 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010142 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010143 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010144 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10145 isPowerOf2_32(SourceType.getSizeInBits());
10146
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010147 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10148 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010149 if (!ValidTypes)
10150 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010151
Michael Liao6d106b72012-10-23 23:06:52 +000010152 bool isLE = TLI.isLittleEndian();
10153 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10154 assert(ElemRatio > 1 && "Invalid element size ratio");
10155 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10156 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010157
Michael Liao6d106b72012-10-23 23:06:52 +000010158 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10159 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010160
Michael Liao6d106b72012-10-23 23:06:52 +000010161 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010162 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010163 SDValue Cast = N->getOperand(i);
10164 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10165 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10166 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10167 SDValue In;
10168 if (Cast.getOpcode() == ISD::UNDEF)
10169 In = DAG.getUNDEF(SourceType);
10170 else
10171 In = Cast->getOperand(0);
10172 unsigned Index = isLE ? (i * ElemRatio) :
10173 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010174
Michael Liao6d106b72012-10-23 23:06:52 +000010175 assert(Index < Ops.size() && "Invalid index");
10176 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010177 }
Chris Lattner5336a592006-03-19 01:27:56 +000010178
Michael Liao6d106b72012-10-23 23:06:52 +000010179 // The type of the new BUILD_VECTOR node.
10180 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10181 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10182 "Invalid vector size");
10183 // Check if the new vector type is legal.
10184 if (!isTypeLegal(VecVT)) return SDValue();
10185
10186 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010187 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010188
10189 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010190 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010191 // Bitcast to the desired type.
10192 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10193}
10194
Michael Liao59229792012-10-24 04:14:18 +000010195SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10196 EVT VT = N->getValueType(0);
10197
10198 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010199 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010200
10201 EVT SrcVT = MVT::Other;
10202 unsigned Opcode = ISD::DELETED_NODE;
10203 unsigned NumDefs = 0;
10204
10205 for (unsigned i = 0; i != NumInScalars; ++i) {
10206 SDValue In = N->getOperand(i);
10207 unsigned Opc = In.getOpcode();
10208
10209 if (Opc == ISD::UNDEF)
10210 continue;
10211
10212 // If all scalar values are floats and converted from integers.
10213 if (Opcode == ISD::DELETED_NODE &&
10214 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10215 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010216 }
Tom Stellard567f8862013-01-02 22:13:01 +000010217
Michael Liao59229792012-10-24 04:14:18 +000010218 if (Opc != Opcode)
10219 return SDValue();
10220
10221 EVT InVT = In.getOperand(0).getValueType();
10222
10223 // If all scalar values are typed differently, bail out. It's chosen to
10224 // simplify BUILD_VECTOR of integer types.
10225 if (SrcVT == MVT::Other)
10226 SrcVT = InVT;
10227 if (SrcVT != InVT)
10228 return SDValue();
10229 NumDefs++;
10230 }
10231
10232 // If the vector has just one element defined, it's not worth to fold it into
10233 // a vectorized one.
10234 if (NumDefs < 2)
10235 return SDValue();
10236
10237 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10238 && "Should only handle conversion from integer to float.");
10239 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10240
10241 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010242
10243 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10244 return SDValue();
10245
Michael Liao59229792012-10-24 04:14:18 +000010246 SmallVector<SDValue, 8> Opnds;
10247 for (unsigned i = 0; i != NumInScalars; ++i) {
10248 SDValue In = N->getOperand(i);
10249
10250 if (In.getOpcode() == ISD::UNDEF)
10251 Opnds.push_back(DAG.getUNDEF(SrcVT));
10252 else
10253 Opnds.push_back(In.getOperand(0));
10254 }
Craig Topper48d114b2014-04-26 18:35:24 +000010255 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010256 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010257
10258 return DAG.getNode(Opcode, dl, VT, BV);
10259}
10260
Michael Liao6d106b72012-10-23 23:06:52 +000010261SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10262 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010263 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010264 EVT VT = N->getValueType(0);
10265
10266 // A vector built entirely of undefs is undef.
10267 if (ISD::allOperandsUndef(N))
10268 return DAG.getUNDEF(VT);
10269
10270 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10271 if (V.getNode())
10272 return V;
10273
Michael Liao59229792012-10-24 04:14:18 +000010274 V = reduceBuildVecConvertToConvertBuildVec(N);
10275 if (V.getNode())
10276 return V;
10277
Dan Gohmana8665142007-06-25 16:23:39 +000010278 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10279 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10280 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010281
10282 // May only combine to shuffle after legalize if shuffle is legal.
10283 if (LegalOperations &&
10284 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10285 return SDValue();
10286
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010287 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010288 for (unsigned i = 0; i != NumInScalars; ++i) {
10289 // Ignore undef inputs.
10290 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010291
Dan Gohmana8665142007-06-25 16:23:39 +000010292 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010293 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010294 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010295 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010296 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010297 break;
10298 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010299
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010300 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010301 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010302 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10303 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010304
Craig Topperc0196b12014-04-14 00:51:57 +000010305 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010306 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010307 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010308 VecIn2 = ExtractedFromVec;
10309 } else {
10310 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010311 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010312 break;
10313 }
10314 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010315
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010316 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010317 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010318 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010319 for (unsigned i = 0; i != NumInScalars; ++i) {
10320 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010321 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010322 continue;
10323 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010324
Rafael Espindolab93db662009-04-24 12:40:33 +000010325 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010326 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010327 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010328 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010329 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10330 if (ExtIndex > VT.getVectorNumElements())
10331 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010332
Nate Begeman5f829d82009-04-29 05:20:52 +000010333 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010334 continue;
10335 }
10336
10337 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010338 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010339 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010340 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010341
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010342 // We can't generate a shuffle node with mismatched input and output types.
10343 // Attempt to transform a single input vector to the correct type.
10344 if ((VT != VecIn1.getValueType())) {
10345 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010346 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010347 return SDValue();
10348
10349 // We only support widening of vectors which are half the size of the
10350 // output registers. For example XMM->YMM widening on X86 with AVX.
10351 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10352 return SDValue();
10353
James Molloy1e5c6112012-09-10 14:01:21 +000010354 // If the input vector type has a different base type to the output
10355 // vector type, bail out.
10356 if (VecIn1.getValueType().getVectorElementType() !=
10357 VT.getVectorElementType())
10358 return SDValue();
10359
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010360 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010361 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010362 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010363 }
10364
10365 // If VecIn2 is unused then change it to undef.
10366 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10367
Nadav Rotem841c9a82012-09-20 08:53:31 +000010368 // Check that we were able to transform all incoming values to the same
10369 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010370 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10371 VecIn1.getValueType() != VT)
10372 return SDValue();
10373
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010374 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010375 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010376 return SDValue();
10377
Dan Gohmana8665142007-06-25 16:23:39 +000010378 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010379 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010380 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010381 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010382 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010383 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010384
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010385 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010386}
10387
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010388SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010389 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10390 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10391 // inputs come from at most two distinct vectors, turn this into a shuffle
10392 // node.
10393
10394 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010395 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010396 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010397
Nadav Rotem01892102012-07-14 21:30:27 +000010398 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010399 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010400 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010401 return DAG.getUNDEF(VT);
10402
10403 // Optimize concat_vectors where one of the vectors is undef.
10404 if (N->getNumOperands() == 2 &&
10405 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10406 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010407 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010408
10409 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10410 if (In->getOpcode() == ISD::BITCAST &&
10411 !In->getOperand(0)->getValueType(0).isVector()) {
10412 SDValue Scalar = In->getOperand(0);
10413 EVT SclTy = Scalar->getValueType(0);
10414
10415 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10416 return SDValue();
10417
10418 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10419 VT.getSizeInBits() / SclTy.getSizeInBits());
10420 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10421 return SDValue();
10422
10423 SDLoc dl = SDLoc(N);
10424 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10425 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10426 }
10427 }
Nadav Rotem01892102012-07-14 21:30:27 +000010428
Robert Lougher7d9084f2014-02-11 15:42:46 +000010429 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10430 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10431 if (N->getNumOperands() == 2 &&
10432 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10433 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10434 EVT VT = N->getValueType(0);
10435 SDValue N0 = N->getOperand(0);
10436 SDValue N1 = N->getOperand(1);
10437 SmallVector<SDValue, 8> Opnds;
10438 unsigned BuildVecNumElts = N0.getNumOperands();
10439
Hao Liu71224b02014-07-10 03:41:50 +000010440 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10441 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10442 if (SclTy0.isFloatingPoint()) {
10443 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10444 Opnds.push_back(N0.getOperand(i));
10445 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10446 Opnds.push_back(N1.getOperand(i));
10447 } else {
10448 // If BUILD_VECTOR are from built from integer, they may have different
10449 // operand types. Get the smaller type and truncate all operands to it.
10450 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10451 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10452 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10453 N0.getOperand(i)));
10454 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10455 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10456 N1.getOperand(i)));
10457 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010458
Craig Topper48d114b2014-04-26 18:35:24 +000010459 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010460 }
10461
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010462 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10463 // nodes often generate nop CONCAT_VECTOR nodes.
10464 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10465 // place the incoming vectors at the exact same location.
10466 SDValue SingleSource = SDValue();
10467 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10468
10469 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10470 SDValue Op = N->getOperand(i);
10471
10472 if (Op.getOpcode() == ISD::UNDEF)
10473 continue;
10474
10475 // Check if this is the identity extract:
10476 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10477 return SDValue();
10478
10479 // Find the single incoming vector for the extract_subvector.
10480 if (SingleSource.getNode()) {
10481 if (Op.getOperand(0) != SingleSource)
10482 return SDValue();
10483 } else {
10484 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010485
10486 // Check the source type is the same as the type of the result.
10487 // If not, this concat may extend the vector, so we can not
10488 // optimize it away.
10489 if (SingleSource.getValueType() != N->getValueType(0))
10490 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010491 }
10492
10493 unsigned IdentityIndex = i * PartNumElem;
10494 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10495 // The extract index must be constant.
10496 if (!CS)
10497 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010498
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010499 // Check that we are reading from the identity index.
10500 if (CS->getZExtValue() != IdentityIndex)
10501 return SDValue();
10502 }
10503
10504 if (SingleSource.getNode())
10505 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010506
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010507 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010508}
10509
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010510SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10511 EVT NVT = N->getValueType(0);
10512 SDValue V = N->getOperand(0);
10513
Michael Liao7a442c802012-10-17 20:48:33 +000010514 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10515 // Combine:
10516 // (extract_subvec (concat V1, V2, ...), i)
10517 // Into:
10518 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010519 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10520 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010521 if (V->getOperand(0).getValueType() != NVT)
10522 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010523 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10524 unsigned NumElems = NVT.getVectorNumElements();
10525 assert((Idx % NumElems) == 0 &&
10526 "IDX in concat is not a multiple of the result vector length.");
10527 return V->getOperand(Idx / NumElems);
10528 }
10529
Michael Liaobb05a1d2013-03-25 23:47:35 +000010530 // Skip bitcasting
10531 if (V->getOpcode() == ISD::BITCAST)
10532 V = V.getOperand(0);
10533
10534 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010535 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010536 // Handle only simple case where vector being inserted and vector
10537 // being extracted are of same type, and are half size of larger vectors.
10538 EVT BigVT = V->getOperand(0).getValueType();
10539 EVT SmallVT = V->getOperand(1).getValueType();
10540 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10541 return SDValue();
10542
10543 // Only handle cases where both indexes are constants with the same type.
10544 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10545 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10546
10547 if (InsIdx && ExtIdx &&
10548 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10549 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10550 // Combine:
10551 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10552 // Into:
10553 // indices are equal or bit offsets are equal => V1
10554 // otherwise => (extract_subvec V1, ExtIdx)
10555 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10556 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10557 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10558 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10559 DAG.getNode(ISD::BITCAST, dl,
10560 N->getOperand(0).getValueType(),
10561 V->getOperand(0)), N->getOperand(1));
10562 }
10563 }
10564
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010565 return SDValue();
10566}
10567
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010568// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10569static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10570 EVT VT = N->getValueType(0);
10571 unsigned NumElts = VT.getVectorNumElements();
10572
10573 SDValue N0 = N->getOperand(0);
10574 SDValue N1 = N->getOperand(1);
10575 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10576
10577 SmallVector<SDValue, 4> Ops;
10578 EVT ConcatVT = N0.getOperand(0).getValueType();
10579 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10580 unsigned NumConcats = NumElts / NumElemsPerConcat;
10581
10582 // Look at every vector that's inserted. We're looking for exact
10583 // subvector-sized copies from a concatenated vector
10584 for (unsigned I = 0; I != NumConcats; ++I) {
10585 // Make sure we're dealing with a copy.
10586 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010587 bool AllUndef = true, NoUndef = true;
10588 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10589 if (SVN->getMaskElt(J) >= 0)
10590 AllUndef = false;
10591 else
10592 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010593 }
10594
Hao Liubc601962013-05-13 02:07:05 +000010595 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010596 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10597 return SDValue();
10598
10599 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10600 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10601 return SDValue();
10602
10603 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10604 if (FirstElt < N0.getNumOperands())
10605 Ops.push_back(N0.getOperand(FirstElt));
10606 else
10607 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10608
10609 } else if (AllUndef) {
10610 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10611 } else { // Mixed with general masks and undefs, can't do optimization.
10612 return SDValue();
10613 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010614 }
10615
Craig Topper48d114b2014-04-26 18:35:24 +000010616 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010617}
10618
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010619SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010620 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010621 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010622
Mon P Wang25f01062008-11-10 04:46:22 +000010623 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010624 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010625
Craig Topper5894fe42012-04-09 05:16:56 +000010626 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010627
Craig Topper279c77b2012-01-04 08:07:43 +000010628 // Canonicalize shuffle undef, undef -> undef
10629 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10630 return DAG.getUNDEF(VT);
10631
10632 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10633
10634 // Canonicalize shuffle v, v -> v, undef
10635 if (N0 == N1) {
10636 SmallVector<int, 8> NewMask;
10637 for (unsigned i = 0; i != NumElts; ++i) {
10638 int Idx = SVN->getMaskElt(i);
10639 if (Idx >= (int)NumElts) Idx -= NumElts;
10640 NewMask.push_back(Idx);
10641 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010642 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010643 &NewMask[0]);
10644 }
10645
10646 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10647 if (N0.getOpcode() == ISD::UNDEF) {
10648 SmallVector<int, 8> NewMask;
10649 for (unsigned i = 0; i != NumElts; ++i) {
10650 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010651 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010652 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010653 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010654 else
10655 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010656 }
10657 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010658 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010659 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010660 &NewMask[0]);
10661 }
10662
10663 // Remove references to rhs if it is undef
10664 if (N1.getOpcode() == ISD::UNDEF) {
10665 bool Changed = false;
10666 SmallVector<int, 8> NewMask;
10667 for (unsigned i = 0; i != NumElts; ++i) {
10668 int Idx = SVN->getMaskElt(i);
10669 if (Idx >= (int)NumElts) {
10670 Idx = -1;
10671 Changed = true;
10672 }
10673 NewMask.push_back(Idx);
10674 }
10675 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010676 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010677 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010678
Bob Wilsonf63da122010-10-28 17:06:14 +000010679 // If it is a splat, check if the argument vector is another splat or a
10680 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010681 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010682 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010683
Dan Gohmana8665142007-06-25 16:23:39 +000010684 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010685 // not the number of vector elements, look through it. Be careful not to
10686 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010687 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010688 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010689 if (ConvInput.getValueType().isVector() &&
10690 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010691 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010692 }
10693
Dan Gohmana8665142007-06-25 16:23:39 +000010694 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010695 assert(V->getNumOperands() == NumElts &&
10696 "BUILD_VECTOR has wrong number of operands");
10697 SDValue Base;
10698 bool AllSame = true;
10699 for (unsigned i = 0; i != NumElts; ++i) {
10700 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10701 Base = V->getOperand(i);
10702 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010703 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010704 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010705 // Splat of <u, u, u, u>, return <u, u, u, u>
10706 if (!Base.getNode())
10707 return N0;
10708 for (unsigned i = 0; i != NumElts; ++i) {
10709 if (V->getOperand(i) != Base) {
10710 AllSame = false;
10711 break;
10712 }
10713 }
10714 // Splat of <x, x, x, x>, return <x, x, x, x>
10715 if (AllSame)
10716 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010717 }
10718 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010719
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010720 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10721 Level < AfterLegalizeVectorOps &&
10722 (N1.getOpcode() == ISD::UNDEF ||
10723 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10724 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10725 SDValue V = partitionShuffleOfConcats(N, DAG);
10726
10727 if (V.getNode())
10728 return V;
10729 }
10730
Nadav Rotemb0783502012-04-01 19:31:22 +000010731 // If this shuffle node is simply a swizzle of another shuffle node,
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010732 // then try to simplify it.
Nadav Rotemb0783502012-04-01 19:31:22 +000010733 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10734 N1.getOpcode() == ISD::UNDEF) {
10735
Nadav Rotemb0783502012-04-01 19:31:22 +000010736 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10737
Craig Topper5894fe42012-04-09 05:16:56 +000010738 // The incoming shuffle must be of the same type as the result of the
10739 // current shuffle.
10740 assert(OtherSV->getOperand(0).getValueType() == VT &&
10741 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010742
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010743 SmallVector<int, 4> Mask;
10744 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010745 for (unsigned i = 0; i != NumElts; ++i) {
10746 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010747 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010748 // Next, this index comes from the first value, which is the incoming
10749 // shuffle. Adopt the incoming index.
10750 if (Idx >= 0)
10751 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010752 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010753 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010754
10755 bool CommuteOperands = false;
10756 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10757 // To be valid, the combine shuffle mask should only reference elements
10758 // from one of the two vectors in input to the inner shufflevector.
10759 bool IsValidMask = true;
10760 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10761 // See if the combined mask only reference undefs or elements coming
10762 // from the first shufflevector operand.
10763 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010764
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010765 if (!IsValidMask) {
10766 IsValidMask = true;
10767 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10768 // Check that all the elements come from the second shuffle operand.
10769 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10770 CommuteOperands = IsValidMask;
10771 }
10772
10773 // Early exit if the combined shuffle mask is not valid.
10774 if (!IsValidMask)
10775 return SDValue();
10776 }
10777
10778 // See if this pair of shuffles can be safely folded according to either
10779 // of the following rules:
10780 // shuffle(shuffle(x, y), undef) -> x
10781 // shuffle(shuffle(x, undef), undef) -> x
10782 // shuffle(shuffle(x, y), undef) -> y
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010783 bool IsIdentityMask = true;
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010784 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010785 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10786 // Skip Undefs.
10787 if (Mask[i] < 0)
10788 continue;
10789
10790 // The combined shuffle must map each index to itself.
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010791 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010792 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010793
10794 if (IsIdentityMask) {
10795 if (CommuteOperands)
10796 // optimize shuffle(shuffle(x, y), undef) -> y.
10797 return OtherSV->getOperand(1);
10798
10799 // optimize shuffle(shuffle(x, undef), undef) -> x
10800 // optimize shuffle(shuffle(x, y), undef) -> x
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010801 return OtherSV->getOperand(0);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010802 }
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010803
10804 // It may still be beneficial to combine the two shuffles if the
10805 // resulting shuffle is legal.
Andrea Di Biagio67d8b2e2014-07-13 21:02:14 +000010806 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010807 if (!CommuteOperands)
10808 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10809 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10810 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10811 &Mask[0]);
10812
10813 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10814 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010815 &Mask[0]);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010816 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010817 }
10818
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000010819 // Canonicalize shuffles according to rules:
10820 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10821 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10822 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10823 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10824 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10825 TLI.isTypeLegal(VT)) {
10826 // The incoming shuffle must be of the same type as the result of the
10827 // current shuffle.
10828 assert(N1->getOperand(0).getValueType() == VT &&
10829 "Shuffle types don't match");
10830
10831 SDValue SV0 = N1->getOperand(0);
10832 SDValue SV1 = N1->getOperand(1);
10833 bool HasSameOp0 = N0 == SV0;
10834 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10835 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10836 // Commute the operands of this shuffle so that next rule
10837 // will trigger.
10838 return DAG.getCommutedVectorShuffle(*SVN);
10839 }
10840
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010841 // Try to fold according to rules:
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010842 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10843 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10844 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10845 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010846 // Don't try to fold shuffles with illegal type.
10847 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010848 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010849 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10850
10851 // The incoming shuffle must be of the same type as the result of the
10852 // current shuffle.
10853 assert(OtherSV->getOperand(0).getValueType() == VT &&
10854 "Shuffle types don't match");
10855
10856 SDValue SV0 = OtherSV->getOperand(0);
10857 SDValue SV1 = OtherSV->getOperand(1);
10858 bool HasSameOp0 = N1 == SV0;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010859 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10860 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010861 // Early exit.
10862 return SDValue();
10863
10864 SmallVector<int, 4> Mask;
10865 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10866 // operand, and SV1 as the second operand.
10867 for (unsigned i = 0; i != NumElts; ++i) {
10868 int Idx = SVN->getMaskElt(i);
10869 if (Idx < 0) {
10870 // Propagate Undef.
10871 Mask.push_back(Idx);
10872 continue;
10873 }
10874
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010875 if (Idx < (int)NumElts) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010876 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010877 if (IsSV1Undef && Idx >= (int) NumElts)
10878 Idx = -1; // Propagate Undef.
10879 } else
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010880 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10881
10882 Mask.push_back(Idx);
10883 }
10884
10885 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010886 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10887 if (IsSV1Undef)
10888 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10889 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10890 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010891 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010892 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010893 }
10894
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010895 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010896}
10897
Manman Ren413a6cb2014-01-31 01:10:35 +000010898SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10899 SDValue N0 = N->getOperand(0);
10900 SDValue N2 = N->getOperand(2);
10901
10902 // If the input vector is a concatenation, and the insert replaces
10903 // one of the halves, we can optimize into a single concat_vectors.
10904 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10905 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10906 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10907 EVT VT = N->getValueType(0);
10908
10909 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10910 // (concat_vectors Z, Y)
10911 if (InsIdx == 0)
10912 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10913 N->getOperand(1), N0.getOperand(1));
10914
10915 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10916 // (concat_vectors X, Z)
10917 if (InsIdx == VT.getVectorNumElements()/2)
10918 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10919 N0.getOperand(0), N->getOperand(1));
10920 }
10921
10922 return SDValue();
10923}
10924
Evan Chenga320abc2006-04-20 08:56:16 +000010925/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010926/// an AND to a vector_shuffle with the destination vector and a zero vector.
10927/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010928/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010929SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010930 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010931 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010932 SDValue LHS = N->getOperand(0);
10933 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010934 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010935 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010936 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010937 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010938 SmallVector<int, 8> Indices;
10939 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010940 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010941 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010942 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010943 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010944
10945 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010946 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010947 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010948 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010949 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010950 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010951 }
10952
10953 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010954 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010955 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010956 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010957
Dan Gohmana8665142007-06-25 16:23:39 +000010958 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010959 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010960 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010961 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000010962 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000010963 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010964 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010965 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010966 }
10967 }
Bill Wendling31b50992009-01-30 23:59:18 +000010968
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010969 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010970}
10971
Dan Gohmana8665142007-06-25 16:23:39 +000010972/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010973SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010974 assert(N->getValueType(0).isVector() &&
10975 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010976
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010977 SDValue LHS = N->getOperand(0);
10978 SDValue RHS = N->getOperand(1);
10979 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010980 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010981
Dan Gohmana8665142007-06-25 16:23:39 +000010982 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010983 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010984 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010985 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010986 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010987 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10988 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010989 return SDValue();
10990
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010991 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010992 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010993 SDValue LHSOp = LHS.getOperand(i);
10994 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010995
Evan Cheng64d28462006-05-31 06:08:35 +000010996 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010997 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10998 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010999 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011000 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000011001 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011002 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000011003 break;
11004 }
Bill Wendling31b50992009-01-30 23:59:18 +000011005
Bob Wilson54081442010-12-17 23:06:49 +000011006 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000011007 EVT RVT = RHSOp.getValueType();
11008 if (RVT != VT) {
11009 // Integer BUILD_VECTOR operands may have types larger than the element
11010 // size (e.g., when the element type is not legal). Prior to type
11011 // legalization, the types may not match between the two BUILD_VECTORS.
11012 // Truncate one of the operands to make them match.
11013 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011014 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011015 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011016 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011017 VT = RVT;
11018 }
11019 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011020 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000011021 LHSOp, RHSOp);
11022 if (FoldOp.getOpcode() != ISD::UNDEF &&
11023 FoldOp.getOpcode() != ISD::Constant &&
11024 FoldOp.getOpcode() != ISD::ConstantFP)
11025 break;
11026 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011027 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000011028 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011029
Bob Wilson54081442010-12-17 23:06:49 +000011030 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000011031 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000011032 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011033
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011034 // Type legalization might introduce new shuffles in the DAG.
11035 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11036 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11037 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11038 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11039 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11040 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11041 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11042 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11043
11044 if (SVN0->getMask().equals(SVN1->getMask())) {
11045 EVT VT = N->getValueType(0);
11046 SDValue UndefVector = LHS.getOperand(1);
11047 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11048 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011049 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011050 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11051 &SVN0->getMask()[0]);
11052 }
11053 }
11054
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011055 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011056}
11057
Craig Topper82384612012-09-11 01:45:21 +000011058/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11059SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011060 assert(N->getValueType(0).isVector() &&
11061 "SimplifyVUnaryOp only works on vectors!");
11062
11063 SDValue N0 = N->getOperand(0);
11064
11065 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11066 return SDValue();
11067
11068 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11069 SmallVector<SDValue, 8> Ops;
11070 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11071 SDValue Op = N0.getOperand(i);
11072 if (Op.getOpcode() != ISD::UNDEF &&
11073 Op.getOpcode() != ISD::ConstantFP)
11074 break;
11075 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011076 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011077 if (FoldOp.getOpcode() != ISD::UNDEF &&
11078 FoldOp.getOpcode() != ISD::ConstantFP)
11079 break;
11080 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011081 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011082 }
11083
11084 if (Ops.size() != N0.getNumOperands())
11085 return SDValue();
11086
Craig Topper48d114b2014-04-26 18:35:24 +000011087 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011088}
11089
Andrew Trickef9de2a2013-05-25 02:42:55 +000011090SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011091 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011092 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011093
Bill Wendling31b50992009-01-30 23:59:18 +000011094 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011095 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011096
Nate Begeman2042aa52005-10-08 00:29:44 +000011097 // If we got a simplified select_cc node back from SimplifySelectCC, then
11098 // break it down into a new SETCC node, and a new SELECT node, and then return
11099 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011100 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011101 // Check to see if we got a select_cc back (to turn into setcc/select).
11102 // Otherwise, just return whatever node we got back, like fabs.
11103 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011104 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011105 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011106 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011107 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011108 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000011109 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11110 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000011111 }
Bill Wendling31b50992009-01-30 23:59:18 +000011112
Nate Begeman2042aa52005-10-08 00:29:44 +000011113 return SCC;
11114 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011115 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011116}
11117
Chris Lattner6c14c352005-10-18 06:04:22 +000011118/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11119/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000011120/// select. Callers of this should assume that TheSelect is deleted if this
11121/// returns true. As such, they should return the appropriate thing (e.g. the
11122/// node) back to the top-level of the DAG combiner loop to avoid it being
11123/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011124bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011125 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011126
Nadav Rotema49a02a2011-02-11 19:57:47 +000011127 // Cannot simplify select with vector condition
11128 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11129
Chris Lattner6c14c352005-10-18 06:04:22 +000011130 // If this is a select from two identical things, try to pull the operation
11131 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011132 if (LHS.getOpcode() != RHS.getOpcode() ||
11133 !LHS.hasOneUse() || !RHS.hasOneUse())
11134 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011135
Chris Lattner254c4452010-09-21 15:46:59 +000011136 // If this is a load and the token chain is identical, replace the select
11137 // of two loads with a load through a select of the address to load from.
11138 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11139 // constants have been dropped into the constant pool.
11140 if (LHS.getOpcode() == ISD::LOAD) {
11141 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11142 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011143
Chris Lattner254c4452010-09-21 15:46:59 +000011144 // Token chains must be identical.
11145 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011146 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011147 LLD->isVolatile() || RLD->isVolatile() ||
11148 // If this is an EXTLOAD, the VT's must match.
11149 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011150 // If this is an EXTLOAD, the kind of extension must match.
11151 (LLD->getExtensionType() != RLD->getExtensionType() &&
11152 // The only exception is if one of the extensions is anyext.
11153 LLD->getExtensionType() != ISD::EXTLOAD &&
11154 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011155 // FIXME: this discards src value information. This is
11156 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011157 // both potential memory locations. Since we are discarding
11158 // src value info, don't do the transformation if the memory
11159 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011160 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011161 RLD->getPointerInfo().getAddrSpace() != 0 ||
11162 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11163 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011164 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011165
Chris Lattnere3267522010-09-21 15:58:55 +000011166 // Check that the select condition doesn't reach either load. If so,
11167 // folding this will induce a cycle into the DAG. If not, this is safe to
11168 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011169 SDValue Addr;
11170 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011171 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11172 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11173 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11174 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011175 // The loads must not depend on one another.
11176 if (LLD->isPredecessorOf(RLD) ||
11177 RLD->isPredecessorOf(LLD))
11178 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011179 Addr = DAG.getSelect(SDLoc(TheSelect),
11180 LLD->getBasePtr().getValueType(),
11181 TheSelect->getOperand(0), LLD->getBasePtr(),
11182 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011183 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011184 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11185 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11186
11187 if ((LLD->hasAnyUseOfValue(1) &&
11188 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011189 (RLD->hasAnyUseOfValue(1) &&
11190 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011191 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011192
Andrew Trickef9de2a2013-05-25 02:42:55 +000011193 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011194 LLD->getBasePtr().getValueType(),
11195 TheSelect->getOperand(0),
11196 TheSelect->getOperand(1),
11197 LLD->getBasePtr(), RLD->getBasePtr(),
11198 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011199 }
11200
Chris Lattnere3267522010-09-21 15:58:55 +000011201 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000011202 // It is safe to replace the two loads if they have different alignments,
11203 // but the new load must be the minimum (most restrictive) alignment of the
11204 // inputs.
Louis Gerbarg67474e32014-07-31 21:45:05 +000011205 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000011206 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011207 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11208 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011209 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000011210 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011211 LLD->getChain(), Addr, MachinePointerInfo(),
11212 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011213 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000011214 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011215 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11216 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011217 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011218 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000011219 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011220 LLD->getChain(), Addr, MachinePointerInfo(),
11221 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011222 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000011223 }
Chris Lattnere3267522010-09-21 15:58:55 +000011224
11225 // Users of the select now use the result of the load.
11226 CombineTo(TheSelect, Load);
11227
11228 // Users of the old loads now use the new load's chain. We know the
11229 // old-load value is dead now.
11230 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11231 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11232 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011233 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011234
Chris Lattner6c14c352005-10-18 06:04:22 +000011235 return false;
11236}
11237
Chris Lattner43d63772009-03-11 05:08:08 +000011238/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11239/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011240SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011241 SDValue N2, SDValue N3,
11242 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011243 // (x ? y : y) -> y.
11244 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011245
Owen Anderson53aa7a92009-08-10 22:56:29 +000011246 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011247 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11248 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11249 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011250
11251 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011252 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011253 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011254 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011255 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011256
11257 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011258 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011259 return N2;
11260 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011261 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011262 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011263
Nate Begeman2042aa52005-10-08 00:29:44 +000011264 // Check to see if we can simplify the select into an fabs node
11265 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11266 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011267 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011268 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11269 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11270 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11271 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011272 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011273
Nate Begeman2042aa52005-10-08 00:29:44 +000011274 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11275 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11276 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11277 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011278 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011279 }
11280 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011281
Chris Lattner43d63772009-03-11 05:08:08 +000011282 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11283 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11284 // in it. This is a win when the constant is not otherwise available because
11285 // it replaces two constant pool loads with one. We only do this if the FP
11286 // type is known to be legal, because if it isn't, then we are before legalize
11287 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011288 // messing with soft float) and if the ConstantFP is not legal, because if
11289 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011290 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11291 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11292 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011293 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011294 TargetLowering::Legal &&
11295 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11296 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011297 // If both constants have multiple uses, then we won't need to do an
11298 // extra load, they are likely around in registers for other users.
11299 (TV->hasOneUse() || FV->hasOneUse())) {
11300 Constant *Elts[] = {
11301 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11302 const_cast<ConstantFP*>(TV->getConstantFPValue())
11303 };
Chris Lattner229907c2011-07-18 04:54:35 +000011304 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011305 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011306
Chris Lattner43d63772009-03-11 05:08:08 +000011307 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011308 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011309 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11310 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011311 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011312
11313 // Get the offsets to the 0 and 1 element of the array so that we can
11314 // select between them.
11315 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011316 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011317 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011318
Chris Lattner43d63772009-03-11 05:08:08 +000011319 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011320 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011321 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011322 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011323 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11324 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011325 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011326 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011327 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011328 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011329 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011330 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011331 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011332
11333 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011334 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011335
Nate Begeman2042aa52005-10-08 00:29:44 +000011336 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011337 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011338 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011339 (N1C->isNullValue() || // (a < 0) ? b : 0
11340 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011341 EVT XType = N0.getValueType();
11342 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011343 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011344 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011345 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011346 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11347 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011348 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011349 SDValue ShCt = DAG.getConstant(ShCtV,
11350 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011351 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011352 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011353 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011354
Duncan Sands11dd4242008-06-08 20:54:56 +000011355 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011356 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011357 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011358 }
Bill Wendling31b50992009-01-30 23:59:18 +000011359
11360 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011361 }
Bill Wendling31b50992009-01-30 23:59:18 +000011362
Andrew Trickef9de2a2013-05-25 02:42:55 +000011363 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011364 XType, N0,
11365 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011366 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011367 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011368
Duncan Sands11dd4242008-06-08 20:54:56 +000011369 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011370 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011371 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011372 }
Bill Wendling31b50992009-01-30 23:59:18 +000011373
11374 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011375 }
11376 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011377
Owen Anderson3231d132010-09-22 22:58:22 +000011378 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11379 // where y is has a single bit set.
11380 // A plaintext description would be, we can turn the SELECT_CC into an AND
11381 // when the condition can be materialized as an all-ones register. Any
11382 // single bit-test can be materialized as an all-ones register with
11383 // shift-left and shift-right-arith.
11384 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11385 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011386 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011387 N2C && N2C->isNullValue()) {
11388 SDValue AndLHS = N0->getOperand(0);
11389 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11390 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11391 // Shift the tested bit over the sign bit.
11392 APInt AndMask = ConstAndRHS->getAPIntValue();
11393 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011394 DAG.getConstant(AndMask.countLeadingZeros(),
11395 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011396 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011397
Owen Anderson3231d132010-09-22 22:58:22 +000011398 // Now arithmetic right shift it all the way over, so the result is either
11399 // all-ones, or zero.
11400 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011401 DAG.getConstant(AndMask.getBitWidth()-1,
11402 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011403 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011404
Owen Anderson3231d132010-09-22 22:58:22 +000011405 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11406 }
11407 }
11408
Nate Begeman6828ed92005-10-10 21:26:48 +000011409 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011410 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011411 TLI.getBooleanContents(N0.getValueType()) ==
11412 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011413
Chris Lattnera083ffc2007-04-11 06:50:51 +000011414 // If the caller doesn't want us to simplify this into a zext of a compare,
11415 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011416 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011417 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011418
Nate Begeman6828ed92005-10-10 21:26:48 +000011419 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011420 // NOTE: Don't create a SETCC if it's not legal on this target.
11421 if (!LegalOperations ||
11422 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011423 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011424 SDValue Temp, SCC;
11425 // cast from setcc result type to select result type
11426 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011427 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011428 N0, N1, CC);
11429 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011430 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011431 N2.getValueType());
11432 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011433 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011434 N2.getValueType(), SCC);
11435 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011436 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11437 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011438 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011439 }
11440
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011441 AddToWorklist(SCC.getNode());
11442 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011443
11444 if (N2C->getAPIntValue() == 1)
11445 return Temp;
11446
11447 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011448 return DAG.getNode(
11449 ISD::SHL, DL, N2.getValueType(), Temp,
11450 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11451 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011452 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011453 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011454
Nate Begeman2042aa52005-10-08 00:29:44 +000011455 // Check to see if this is the equivalent of setcc
11456 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11457 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011458 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011459 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011460 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011461 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11462 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011463 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011464 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011465 return Res;
11466 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011467
Bill Wendling31b50992009-01-30 23:59:18 +000011468 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011469 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011470 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011471 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011472 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011473 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011474 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011475 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011476 }
Bill Wendling31b50992009-01-30 23:59:18 +000011477 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011478 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011479 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011480 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011481 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011482 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011483 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011484 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011485 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011486 }
Bill Wendling31b50992009-01-30 23:59:18 +000011487 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011488 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011489 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011490 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011491 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011492 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011493 }
11494 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011495
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011496 // Check to see if this is an integer abs.
11497 // select_cc setg[te] X, 0, X, -X ->
11498 // select_cc setgt X, -1, X, -X ->
11499 // select_cc setl[te] X, 0, -X, X ->
11500 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011501 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011502 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011503 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011504 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11505 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11506 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11507 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11508 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11509 (N1C->isOne() && CC == ISD::SETLT)) &&
11510 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11511 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11512
Owen Anderson53aa7a92009-08-10 22:56:29 +000011513 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011514 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011515 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011516 N0,
11517 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011518 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011519 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011520 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011521 AddToWorklist(Shift.getNode());
11522 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011523 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011524 }
11525 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011526
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011527 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011528}
11529
Evan Cheng92658d52007-02-08 22:13:59 +000011530/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011531SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011532 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011533 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011534 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011535 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011536 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011537}
11538
Chad Rosier17020f92014-07-23 14:57:52 +000011539/// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11540/// a DAG expression to select that will generate the same value by multiplying
11541/// by a magic number. See:
Nate Begemanc6f067a2005-10-20 02:15:44 +000011542/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011543SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011544 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11545 if (!C)
11546 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011547
11548 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011549 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011550 return SDValue();
11551
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011552 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011553 SDValue S =
11554 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011555
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011556 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011557 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011558 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011559}
11560
Chad Rosier17020f92014-07-23 14:57:52 +000011561/// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11562/// power of 2, return a DAG expression to select that will generate the same
11563/// value by right shifting.
11564SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11565 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11566 if (!C)
11567 return SDValue();
11568
11569 // Avoid division by zero.
11570 if (!C->getAPIntValue())
11571 return SDValue();
11572
11573 std::vector<SDNode *> Built;
11574 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11575
11576 for (SDNode *N : Built)
11577 AddToWorklist(N);
11578 return S;
11579}
11580
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011581/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begemanc6f067a2005-10-20 02:15:44 +000011582/// return a DAG expression to select that will generate the same value by
11583/// multiplying by a magic number. See:
11584/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011585SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011586 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11587 if (!C)
11588 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011589
11590 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011591 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011592 return SDValue();
11593
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011594 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011595 SDValue S =
11596 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011597
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011598 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011599 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011600 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011601}
11602
Nate Begeman18150d52009-09-25 06:05:26 +000011603/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011604// to alias with anything but itself. Provides base object and offset as
11605// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011606static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011607 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011608 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011609 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011610
Jim Laskey0463e082006-10-07 23:37:56 +000011611 // If it's an adding a simple constant then integrate the offset.
11612 if (Base.getOpcode() == ISD::ADD) {
11613 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11614 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011615 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011616 }
11617 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011618
Nate Begeman18150d52009-09-25 06:05:26 +000011619 // Return the underlying GlobalValue, and update the Offset. Return false
11620 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11621 // by multiple nodes with different offsets.
11622 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11623 GV = G->getGlobal();
11624 Offset += G->getOffset();
11625 return false;
11626 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011627
Nate Begeman18150d52009-09-25 06:05:26 +000011628 // Return the underlying Constant value, and update the Offset. Return false
11629 // for ConstantSDNodes since the same constant pool entry may be represented
11630 // by multiple nodes with different offsets.
11631 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011632 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11633 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011634 Offset += C->getOffset();
11635 return false;
11636 }
Jim Laskey0463e082006-10-07 23:37:56 +000011637 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011638 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011639}
11640
11641/// isAlias - Return true if there is any possibility that the two addresses
11642/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011643bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011644 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011645 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011646
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011647 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011648 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011649
Jim Laskey0463e082006-10-07 23:37:56 +000011650 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011651 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011652 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011653 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011654 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011655 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11656 Base1, Offset1, GV1, CV1);
11657 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11658 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011659
Nate Begeman18150d52009-09-25 06:05:26 +000011660 // If they have a same base address then check to see if they overlap.
11661 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011662 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11663 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011664
Owen Anderson272ff942010-09-20 20:39:59 +000011665 // It is possible for different frame indices to alias each other, mostly
11666 // when tail call optimization reuses return address slots for arguments.
11667 // To catch this case, look up the actual index of frame indices to compute
11668 // the real alias relationship.
11669 if (isFrameIndex1 && isFrameIndex2) {
11670 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11671 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11672 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011673 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11674 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011675 }
11676
Wesley Peck527da1b2010-11-23 03:31:01 +000011677 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011678 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011679 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11680 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011681
Nate Begeman879d8f12009-09-15 00:18:30 +000011682 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11683 // compared to the size and offset of the access, we may be able to prove they
11684 // do not alias. This check is conservative for now to catch cases created by
11685 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011686 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11687 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11688 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11689 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11690 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11691 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11692 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011693
Nate Begeman879d8f12009-09-15 00:18:30 +000011694 // There is no overlap between these relatively aligned accesses of similar
11695 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011696 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11697 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011698 return false;
11699 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011700
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011701 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11702 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011703#ifndef NDEBUG
11704 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11705 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11706 UseAA = false;
11707#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011708 if (UseAA &&
11709 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011710 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011711 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11712 Op1->getSrcValueOffset());
11713 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11714 Op0->getSrcValueOffset() - MinOffset;
11715 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11716 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011717 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011718 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11719 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000011720 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011721 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11722 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000011723 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011724 if (AAResult == AliasAnalysis::NoAlias)
11725 return false;
11726 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011727
11728 // Otherwise we have to assume they alias.
11729 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011730}
11731
Jim Laskey708d0db2006-10-04 16:53:27 +000011732/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11733/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011734void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011735 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011736 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011737 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011738
Jim Laskeyd07be232006-09-25 16:29:54 +000011739 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011740 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011741
Jim Laskey708d0db2006-10-04 16:53:27 +000011742 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011743 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011744 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011745
Jim Laskey6549d222006-10-05 15:07:25 +000011746 // Look at each chain and determine if it is an alias. If so, add it to the
11747 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011748 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011749 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011750 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011751 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011752
11753 // For TokenFactor nodes, look at each operand and only continue up the
11754 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011755 // find more and revert to original chain since the xform is unlikely to be
11756 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011757 //
11758 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011759 // chain we found before we hit a tokenfactor rather than the original
11760 // chain.
11761 if (Depth > 6 || Aliases.size() == 2) {
11762 Aliases.clear();
11763 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011764 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011765 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011766
Nate Begeman879d8f12009-09-15 00:18:30 +000011767 // Don't bother if we've been before.
11768 if (!Visited.insert(Chain.getNode()))
11769 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011770
Jim Laskey6549d222006-10-05 15:07:25 +000011771 switch (Chain.getOpcode()) {
11772 case ISD::EntryToken:
11773 // Entry token is ideal chain operand, but handled in FindBetterChain.
11774 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011775
Jim Laskey6549d222006-10-05 15:07:25 +000011776 case ISD::LOAD:
11777 case ISD::STORE: {
11778 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011779 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11780 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011781
Jim Laskey6549d222006-10-05 15:07:25 +000011782 // If chain is alias then stop here.
11783 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011784 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011785 Aliases.push_back(Chain);
11786 } else {
11787 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011788 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011789 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011790 }
Jim Laskey6549d222006-10-05 15:07:25 +000011791 break;
11792 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011793
Jim Laskey6549d222006-10-05 15:07:25 +000011794 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011795 // We have to check each of the operands of the token factor for "small"
11796 // token factors, so we queue them up. Adding the operands to the queue
11797 // (stack) in reverse order maintains the original order and increases the
11798 // likelihood that getNode will find a matching token factor (CSE.)
11799 if (Chain.getNumOperands() > 16) {
11800 Aliases.push_back(Chain);
11801 break;
11802 }
Jim Laskey6549d222006-10-05 15:07:25 +000011803 for (unsigned n = Chain.getNumOperands(); n;)
11804 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011805 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011806 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011807
Jim Laskey6549d222006-10-05 15:07:25 +000011808 default:
11809 // For all other instructions we will just have to take what we can get.
11810 Aliases.push_back(Chain);
11811 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011812 }
11813 }
Hal Finkel51a98382014-01-24 20:12:02 +000011814
11815 // We need to be careful here to also search for aliases through the
11816 // value operand of a store, etc. Consider the following situation:
11817 // Token1 = ...
11818 // L1 = load Token1, %52
11819 // S1 = store Token1, L1, %51
11820 // L2 = load Token1, %52+8
11821 // S2 = store Token1, L2, %51+8
11822 // Token2 = Token(S1, S2)
11823 // L3 = load Token2, %53
11824 // S3 = store Token2, L3, %52
11825 // L4 = load Token2, %53+8
11826 // S4 = store Token2, L4, %52+8
11827 // If we search for aliases of S3 (which loads address %52), and we look
11828 // only through the chain, then we'll miss the trivial dependence on L1
11829 // (which also loads from %52). We then might change all loads and
11830 // stores to use Token1 as their chain operand, which could result in
11831 // copying %53 into %52 before copying %52 into %51 (which should
11832 // happen first).
11833 //
11834 // The problem is, however, that searching for such data dependencies
11835 // can become expensive, and the cost is not directly related to the
11836 // chain depth. Instead, we'll rule out such configurations here by
11837 // insisting that we've visited all chain users (except for users
11838 // of the original chain, which is not necessary). When doing this,
11839 // we need to look through nodes we don't care about (otherwise, things
11840 // like register copies will interfere with trivial cases).
11841
11842 SmallVector<const SDNode *, 16> Worklist;
11843 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11844 IE = Visited.end(); I != IE; ++I)
11845 if (*I != OriginalChain.getNode())
11846 Worklist.push_back(*I);
11847
11848 while (!Worklist.empty()) {
11849 const SDNode *M = Worklist.pop_back_val();
11850
11851 // We have already visited M, and want to make sure we've visited any uses
11852 // of M that we care about. For uses that we've not visisted, and don't
11853 // care about, queue them to the worklist.
11854
11855 for (SDNode::use_iterator UI = M->use_begin(),
11856 UIE = M->use_end(); UI != UIE; ++UI)
11857 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11858 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11859 // We've not visited this use, and we care about it (it could have an
11860 // ordering dependency with the original node).
11861 Aliases.clear();
11862 Aliases.push_back(OriginalChain);
11863 return;
11864 }
11865
11866 // We've not visited this use, but we don't care about it. Mark it as
11867 // visited and enqueue it to the worklist.
11868 Worklist.push_back(*UI);
11869 }
11870 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011871}
11872
11873/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11874/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011875SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11876 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011877
Jim Laskey708d0db2006-10-04 16:53:27 +000011878 // Accumulate all the aliases to this node.
11879 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011880
Dan Gohman4298df62011-05-17 22:20:36 +000011881 // If no operands then chain to entry token.
11882 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011883 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011884
11885 // If a single operand then chain to it. We don't need to revisit it.
11886 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011887 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011888
Jim Laskey708d0db2006-10-04 16:53:27 +000011889 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011890 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011891}
11892
Nate Begeman21158fc2005-09-01 00:19:25 +000011893// SelectionDAG::Combine - This is the entry point for the file.
11894//
Bill Wendling084669a2009-04-29 00:15:41 +000011895void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011896 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011897 /// run - This is the main entry point to this class.
11898 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011899 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011900}