blob: c9a5919aaa87f31548bf72c2455579688fdafa13 [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"
21#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000029#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000030#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000032#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetLowering.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000037#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000039#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000040using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "dagcombine"
43
Chris Lattneraee775a2006-12-19 22:41:21 +000044STATISTIC(NodesCombined , "Number of dag nodes combined");
45STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000047STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000048STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000049STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000050
Nate Begeman21158fc2005-09-01 00:19:25 +000051namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000052 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000053 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000054 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000055
Jim Laskey55e4dca2006-10-18 19:08:31 +000056 static cl::opt<bool>
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000058 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000059
Hal Finkeldbebb522014-01-25 19:24:54 +000060 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000061 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000062 cl::desc("Enable DAG combiner's use of TBAA"));
63
Hal Finkel9b2617a2014-01-25 17:32:39 +000064#ifndef NDEBUG
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
68 " function"));
69#endif
70
Quentin Colombetde0e0622013-10-11 18:29:42 +000071 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
73 static cl::opt<bool>
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
76 "slicing"),
77 cl::init(false));
78
Jim Laskey6549d222006-10-05 15:07:25 +000079//------------------------------ DAGCombiner ---------------------------------//
80
Nick Lewycky02d5f772009-10-25 06:33:48 +000081 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000082 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000083 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000084 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000085 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000086 bool LegalOperations;
87 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000088 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000089
90 // Worklist of all of the nodes that need to be simplified.
James Molloy67b6b112012-02-16 09:17:04 +000091 //
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
95 // linear time.
96 //
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
99 //
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
102 //
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000107 SmallPtrSet<SDNode*, 64> WorklistContents;
108 SmallVector<SDNode*, 64> WorklistOrder;
Nate Begeman21158fc2005-09-01 00:19:25 +0000109
Jim Laskeydcb2b832006-10-16 20:52:31 +0000110 // AA - Used for DAG load/store alias analysis.
111 AliasAnalysis &AA;
112
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000113 /// AddUsersToWorklist - When an instruction is simplified, add all users of
Nate Begeman21158fc2005-09-01 00:19:25 +0000114 /// the instruction to the work lists because they might get more simplified
115 /// now.
116 ///
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000117 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000118 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000119 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000120 }
121
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000124 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000125
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000126 public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000127 /// AddToWorklist - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000128 /// back (next to be processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000129 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000130 // Skip handle nodes as they can't usefully be combined and confuse the
131 // zero-use deletion strategy.
132 if (N->getOpcode() == ISD::HANDLENODE)
133 return;
134
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000135 WorklistContents.insert(N);
136 WorklistOrder.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000137 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000138
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000139 /// removeFromWorklist - remove all instances of N from the worklist.
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000140 ///
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000141 void removeFromWorklist(SDNode *N) {
142 WorklistContents.erase(N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000143 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000144
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000145 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000146 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000147
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000148 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000149 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000150 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000151
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000152 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000153 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000154 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000155 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000156 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000157
158 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000159
160 private:
161
Chris Lattner375e1a72006-02-17 21:58:01 +0000162 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000163 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000164 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000165 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000166 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
167 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000168 return SimplifyDemandedBits(Op, Demanded);
169 }
170
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000171 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000172
Chris Lattnerffad2162006-11-11 00:39:41 +0000173 bool CombineToPreIndexedLoadStore(SDNode *N);
174 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000175 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000176
Evan Cheng0abb54d2010-04-24 04:43:44 +0000177 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
178 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
179 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
180 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000181 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000182 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000183 SDValue PromoteExtend(SDValue Op);
184 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000185
Craig Toppere0b71182013-07-13 07:43:40 +0000186 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000187 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000188 ISD::NodeType ExtType);
189
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000190 /// combine - call the node-specific routine that knows how to fold each
191 /// particular type of node. If that doesn't do anything, try the
192 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000193 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000194
195 // Visitation implementation - Implement dag node combining for different
196 // node types. The semantics are as follows:
197 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000198 // SDValue.getNode() == 0 - No change was made
199 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
200 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000201 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000202 SDValue visitTokenFactor(SDNode *N);
203 SDValue visitMERGE_VALUES(SDNode *N);
204 SDValue visitADD(SDNode *N);
205 SDValue visitSUB(SDNode *N);
206 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000207 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000208 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000209 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000210 SDValue visitMUL(SDNode *N);
211 SDValue visitSDIV(SDNode *N);
212 SDValue visitUDIV(SDNode *N);
213 SDValue visitSREM(SDNode *N);
214 SDValue visitUREM(SDNode *N);
215 SDValue visitMULHU(SDNode *N);
216 SDValue visitMULHS(SDNode *N);
217 SDValue visitSMUL_LOHI(SDNode *N);
218 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000219 SDValue visitSMULO(SDNode *N);
220 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000221 SDValue visitSDIVREM(SDNode *N);
222 SDValue visitUDIVREM(SDNode *N);
223 SDValue visitAND(SDNode *N);
224 SDValue visitOR(SDNode *N);
225 SDValue visitXOR(SDNode *N);
226 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000227 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000228 SDValue visitSHL(SDNode *N);
229 SDValue visitSRA(SDNode *N);
230 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000231 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000232 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000234 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000236 SDValue visitCTPOP(SDNode *N);
237 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000238 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000239 SDValue visitSELECT_CC(SDNode *N);
240 SDValue visitSETCC(SDNode *N);
241 SDValue visitSIGN_EXTEND(SDNode *N);
242 SDValue visitZERO_EXTEND(SDNode *N);
243 SDValue visitANY_EXTEND(SDNode *N);
244 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000246 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000247 SDValue visitBUILD_PAIR(SDNode *N);
248 SDValue visitFADD(SDNode *N);
249 SDValue visitFSUB(SDNode *N);
250 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000251 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitFDIV(SDNode *N);
253 SDValue visitFREM(SDNode *N);
254 SDValue visitFCOPYSIGN(SDNode *N);
255 SDValue visitSINT_TO_FP(SDNode *N);
256 SDValue visitUINT_TO_FP(SDNode *N);
257 SDValue visitFP_TO_SINT(SDNode *N);
258 SDValue visitFP_TO_UINT(SDNode *N);
259 SDValue visitFP_ROUND(SDNode *N);
260 SDValue visitFP_ROUND_INREG(SDNode *N);
261 SDValue visitFP_EXTEND(SDNode *N);
262 SDValue visitFNEG(SDNode *N);
263 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000264 SDValue visitFCEIL(SDNode *N);
265 SDValue visitFTRUNC(SDNode *N);
266 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000267 SDValue visitBRCOND(SDNode *N);
268 SDValue visitBR_CC(SDNode *N);
269 SDValue visitLOAD(SDNode *N);
270 SDValue visitSTORE(SDNode *N);
271 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273 SDValue visitBUILD_VECTOR(SDNode *N);
274 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000276 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000277 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000278
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000279 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000281
Matt Arsenault985b9de2014-03-17 18:58:01 +0000282 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000283
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000288 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000289 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000291 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000292
293 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
294 SDValue &CC) const;
295 bool isOneUseSetCC(SDValue N) const;
296
Scott Michelcf0da6c2009-02-17 22:15:04 +0000297 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000298 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000299 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000300 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000301 SDValue BuildSDIV(SDNode *N);
302 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000303 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
304 bool DemandHighBits = true);
305 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000306 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
307 SDValue InnerPos, SDValue InnerNeg,
308 unsigned PosOpcode, unsigned NegOpcode,
309 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000310 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000311 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000312 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000313 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000314 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000315 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000317 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000318
Jim Laskey708d0db2006-10-04 16:53:27 +0000319 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
320 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000321 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000322 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000323
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000324 /// isAlias - Return true if there is any possibility that the two addresses
325 /// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000326 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000327
Jim Laskeyd07be232006-09-25 16:29:54 +0000328 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000329 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000330 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000331
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000332 /// Merge consecutive store operations into a wide store.
333 /// This optimization uses wide integers or vectors when possible.
334 /// \return True if some memory operations were changed.
335 bool MergeConsecutiveStores(StoreSDNode *N);
336
Adam Nemet67483892014-03-04 23:28:31 +0000337 /// \brief Try to transform a truncation where C is a constant:
338 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
339 ///
340 /// \p N needs to be a truncation and its first operand an AND. Other
341 /// requirements are checked by the function (e.g. that trunc is
342 /// single-use) and if missed an empty SDValue is returned.
343 SDValue distributeTruncateThroughAnd(SDNode *N);
344
Chris Lattner4041ab62010-04-15 04:48:01 +0000345 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000346 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000347 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
348 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
349 AttributeSet FnAttrs =
350 DAG.getMachineFunction().getFunction()->getAttributes();
351 ForCodeSize =
352 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
353 Attribute::OptimizeForSize) ||
354 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
355 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000356
Nate Begeman21158fc2005-09-01 00:19:25 +0000357 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000358 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000359
Chris Lattner4041ab62010-04-15 04:48:01 +0000360 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000361
Chris Lattner4041ab62010-04-15 04:48:01 +0000362 /// getShiftAmountTy - Returns a type large enough to hold any valid
363 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000364 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000365 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
366 if (LHSTy.isVector())
367 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000368 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
369 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000370 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000371
Chris Lattner4041ab62010-04-15 04:48:01 +0000372 /// isTypeLegal - This method returns true if we are running before type
373 /// legalization or if the specified VT is legal.
374 bool isTypeLegal(const EVT &VT) {
375 if (!LegalTypes) return true;
376 return TLI.isTypeLegal(VT);
377 }
Matt Arsenault758659232013-05-18 00:21:46 +0000378
379 /// getSetCCResultType - Convenience wrapper around
380 /// TargetLowering::getSetCCResultType
381 EVT getSetCCResultType(EVT VT) const {
382 return TLI.getSetCCResultType(*DAG.getContext(), VT);
383 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000384 };
385}
386
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000387
388namespace {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000389/// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000390/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000391class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000392 DAGCombiner &DC;
393public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000394 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000395 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000396
Craig Topper7b883b32014-03-08 06:31:39 +0000397 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000398 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000399 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000400};
401}
402
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000403//===----------------------------------------------------------------------===//
404// TargetLowering::DAGCombinerInfo implementation
405//===----------------------------------------------------------------------===//
406
407void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000408 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000409}
410
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000411void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000412 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000413}
414
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000415SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000416CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
417 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000418}
419
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000420SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000421CombineTo(SDNode *N, SDValue Res, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000423}
424
425
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000426SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000427CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
428 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000429}
430
Dan Gohmane58ab792009-01-29 01:59:02 +0000431void TargetLowering::DAGCombinerInfo::
432CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
433 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
434}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000435
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000436//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000437// Helper Functions
438//===----------------------------------------------------------------------===//
439
440/// isNegatibleForFree - Return 1 if we can compute the negated form of the
441/// specified expression for the same cost as the expression itself, or 2 if we
442/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000443static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000444 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000445 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000446 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000447 // fneg is removable even if it has multiple uses.
448 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000449
Chris Lattnere49c9742007-05-14 22:04:50 +0000450 // Don't allow anything with multiple uses.
451 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000452
Chris Lattner46980832007-05-25 02:19:06 +0000453 // Don't recurse exponentially.
454 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000455
Chris Lattnere49c9742007-05-14 22:04:50 +0000456 switch (Op.getOpcode()) {
457 default: return false;
458 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000459 // Don't invert constant FP values after legalize. The negated constant
460 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000461 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000462 case ISD::FADD:
463 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000464 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000465
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000466 // After operation legalization, it might not be legal to create new FSUBs.
467 if (LegalOperations &&
468 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
469 return 0;
470
Craig Topper03f39772012-09-09 22:58:45 +0000471 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000472 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
473 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000474 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000475 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000476 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000477 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000478 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000479 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000480 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000481
Bill Wendling6fbf5492009-01-30 23:10:18 +0000482 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000483 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000484
Chris Lattnere49c9742007-05-14 22:04:50 +0000485 case ISD::FMUL:
486 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000487 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000488
Bill Wendling6fbf5492009-01-30 23:10:18 +0000489 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000490 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
491 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000492 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000493
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000494 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000495 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000496
Chris Lattnere49c9742007-05-14 22:04:50 +0000497 case ISD::FP_EXTEND:
498 case ISD::FP_ROUND:
499 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000500 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000501 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000502 }
503}
504
505/// GetNegatedExpression - If isNegatibleForFree returns true, this function
506/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000507static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000508 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000509 // fneg is removable even if it has multiple uses.
510 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000511
Chris Lattnere49c9742007-05-14 22:04:50 +0000512 // Don't allow anything with multiple uses.
513 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000514
Chris Lattner46980832007-05-25 02:19:06 +0000515 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000516 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000517 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000518 case ISD::ConstantFP: {
519 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
520 V.changeSign();
521 return DAG.getConstantFP(V, Op.getValueType());
522 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000523 case ISD::FADD:
524 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000525 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000526
Bill Wendling6fbf5492009-01-30 23:10:18 +0000527 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000528 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000529 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000530 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000531 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000532 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000533 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000534 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000535 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000537 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000538 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000539 Op.getOperand(0));
540 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000541 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000542 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000543
Bill Wendling6fbf5492009-01-30 23:10:18 +0000544 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000545 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000546 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000547 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000548
Bill Wendling6fbf5492009-01-30 23:10:18 +0000549 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000550 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000551 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000552
Chris Lattnere49c9742007-05-14 22:04:50 +0000553 case ISD::FMUL:
554 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000555 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000556
Bill Wendling6fbf5492009-01-30 23:10:18 +0000557 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000558 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000559 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000560 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000561 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000563 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000564 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000565
Bill Wendling6fbf5492009-01-30 23:10:18 +0000566 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000567 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000568 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000569 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000570 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000571
Chris Lattnere49c9742007-05-14 22:04:50 +0000572 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000573 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000574 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000575 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000576 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000577 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000578 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000580 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000581 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000582 }
583}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000584
Nate Begeman2504fe22005-09-01 23:24:04 +0000585// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000586// that selects between the target values used for true and false, making it
587// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
588// the appropriate nodes based on the type of node we are checking. This
589// simplifies life a bit for the callers.
590bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
591 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000592 if (N.getOpcode() == ISD::SETCC) {
593 LHS = N.getOperand(0);
594 RHS = N.getOperand(1);
595 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000596 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000597 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000598
599 if (N.getOpcode() != ISD::SELECT_CC ||
600 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
601 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
602 return false;
603
604 LHS = N.getOperand(0);
605 RHS = N.getOperand(1);
606 CC = N.getOperand(4);
607 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000608}
609
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000610// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
611// one use. If this is true, it allows the users to invert the operation for
612// free when it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000613bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000614 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000615 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000616 return true;
617 return false;
618}
619
Matt Arsenault985b9de2014-03-17 18:58:01 +0000620/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
621/// elements are all the same constant or undefined.
622static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
623 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
624 if (!C)
625 return false;
626
627 APInt SplatUndef;
628 unsigned SplatBitSize;
629 bool HasAnyUndefs;
630 EVT EltVT = N->getValueType(0).getVectorElementType();
631 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
632 HasAnyUndefs) &&
633 EltVT.getSizeInBits() >= SplatBitSize);
634}
635
636// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000637static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638 if (isa<ConstantSDNode>(N))
639 return N.getNode();
640 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641 if(BV && BV->isConstant())
642 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000643 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000644}
645
Matt Arsenault985b9de2014-03-17 18:58:01 +0000646// \brief Returns the SDNode if it is a constant splat BuildVector or constant
647// int.
648static ConstantSDNode *isConstOrConstSplat(SDValue N) {
649 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
650 return CN;
651
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000652 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000653 BitVector UndefElements;
654 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000655
656 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000657 // FIXME: We blindly ignore splats which include undef which is overly
658 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000659 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000660 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000661 return CN;
662 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000663
664 return nullptr;
665}
666
Andrew Trickef9de2a2013-05-25 02:42:55 +0000667SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000668 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000669 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000670 if (N0.getOpcode() == Opc) {
671 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
672 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
673 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
674 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
675 if (!OpNode.getNode())
676 return SDValue();
677 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000678 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000679 if (N0.hasOneUse()) {
680 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
681 // use
682 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
683 if (!OpNode.getNode())
684 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000685 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000686 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000687 }
688 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000689 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000690
Juergen Ributzka68402822014-01-13 21:49:25 +0000691 if (N1.getOpcode() == Opc) {
692 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
693 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
694 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
695 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
696 if (!OpNode.getNode())
697 return SDValue();
698 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
699 }
700 if (N1.hasOneUse()) {
701 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
702 // use
703 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
704 if (!OpNode.getNode())
705 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000706 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000707 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
708 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000709 }
710 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000711
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000712 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000713}
714
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000715SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
716 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000717 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
718 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000719 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000720 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000721 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000722 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000723 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000724 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000725 assert((!To[i].getNode() ||
726 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000727 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000728 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000729 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000730 if (AddTo) {
731 // Push the new nodes and any users onto the worklist
732 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000733 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000734 AddToWorklist(To[i].getNode());
735 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000736 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000737 }
738 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000739
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000740 // Finally, if the node is now dead, remove it from the graph. The node
741 // may not be dead if the replacement process recursively simplified to
742 // something else needing this node.
743 if (N->use_empty()) {
744 // Nodes can be reintroduced into the worklist. Make sure we do not
745 // process a node that has been replaced.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000746 removeFromWorklist(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000747
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000748 // Finally, since the node is now dead, remove it from the graph.
749 DAG.DeleteNode(N);
750 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000751 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000752}
753
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000754void DAGCombiner::
755CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000756 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000757 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000758 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000759 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000760
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000761 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000762 AddToWorklist(TLO.New.getNode());
763 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000764
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000765 // Finally, if the node is now dead, remove it from the graph. The node
766 // may not be dead if the replacement process recursively simplified to
767 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000768 if (TLO.Old.getNode()->use_empty()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000769 removeFromWorklist(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000770
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000771 // If the operands of this node are only used by the node, they will now
772 // be dead. Make sure to visit them first to delete dead nodes early.
Hal Finkel2c77fe52014-05-28 15:33:19 +0000773 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
774 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000775 AddToWorklist(TLO.Old.getNode()->getOperand(i).getNode());
Hal Finkel2c77fe52014-05-28 15:33:19 +0000776
Gabor Greiff304a7a2008-08-28 21:40:38 +0000777 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000778 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000779}
780
781/// SimplifyDemandedBits - Check the specified integer node value to see if
782/// it can be simplified or if things it uses can be simplified by bit
783/// propagation. If so, return true.
784bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000785 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000786 APInt KnownZero, KnownOne;
787 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
788 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000789
Dan Gohmane58ab792009-01-29 01:59:02 +0000790 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000791 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000792
Dan Gohmane58ab792009-01-29 01:59:02 +0000793 // Replace the old value with the new one.
794 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000795 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000796 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000797 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000798 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000799 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000800
Dan Gohmane58ab792009-01-29 01:59:02 +0000801 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000802 return true;
803}
804
Evan Cheng0abb54d2010-04-24 04:43:44 +0000805void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000806 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000807 EVT VT = Load->getValueType(0);
808 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000809
Evan Cheng0abb54d2010-04-24 04:43:44 +0000810 DEBUG(dbgs() << "\nReplacing.9 ";
811 Load->dump(&DAG);
812 dbgs() << "\nWith: ";
813 Trunc.getNode()->dump(&DAG);
814 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000815 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000816 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
817 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000818 removeFromWorklist(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000819 DAG.DeleteNode(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000820 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000821}
822
823SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
824 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000825 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000826 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000827 EVT MemVT = LD->getMemoryVT();
828 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000829 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000830 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000831 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000832 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000833 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000834 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000835 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000836 }
837
Evan Chenge19aa5c2010-04-19 19:29:22 +0000838 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000839 switch (Opc) {
840 default: break;
841 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000842 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000843 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000844 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000845 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000846 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000847 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000848 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000849 case ISD::Constant: {
850 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000851 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000852 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000853 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000854 }
855
856 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000857 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000858 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000859}
860
Evan Cheng0abb54d2010-04-24 04:43:44 +0000861SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000862 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
863 return SDValue();
864 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000865 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000866 bool Replace = false;
867 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000868 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000869 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000870 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000871
872 if (Replace)
873 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
874 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000875 DAG.getValueType(OldVT));
876}
877
Evan Cheng0abb54d2010-04-24 04:43:44 +0000878SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000879 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000880 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000881 bool Replace = false;
882 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000883 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000884 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000885 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000886
887 if (Replace)
888 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
889 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000890}
891
Evan Chengaf56fac2010-04-16 06:14:10 +0000892/// PromoteIntBinOp - Promote the specified integer binary operation if the
893/// target indicates it is beneficial. e.g. On x86, it's usually better to
894/// promote i16 operations to i32 since i16 instructions are longer.
895SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
896 if (!LegalOperations)
897 return SDValue();
898
899 EVT VT = Op.getValueType();
900 if (VT.isVector() || !VT.isInteger())
901 return SDValue();
902
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000903 // If operation type is 'undesirable', e.g. i16 on x86, consider
904 // promoting it.
905 unsigned Opc = Op.getOpcode();
906 if (TLI.isTypeDesirableForOp(Opc, VT))
907 return SDValue();
908
Evan Chengaf56fac2010-04-16 06:14:10 +0000909 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000910 // Consult target whether it is a good idea to promote this operation and
911 // what's the right type to promote it to.
912 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000913 assert(PVT != VT && "Don't know what type to promote to!");
914
Evan Cheng0abb54d2010-04-24 04:43:44 +0000915 bool Replace0 = false;
916 SDValue N0 = Op.getOperand(0);
917 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000918 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000919 return SDValue();
920
Evan Cheng0abb54d2010-04-24 04:43:44 +0000921 bool Replace1 = false;
922 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000923 SDValue NN1;
924 if (N0 == N1)
925 NN1 = NN0;
926 else {
927 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000928 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000929 return SDValue();
930 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000931
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000932 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000933 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000934 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000935
936 if (Replace0)
937 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
938 if (Replace1)
939 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000940
Evan Chenge8136902010-04-27 19:48:13 +0000941 DEBUG(dbgs() << "\nPromoting ";
942 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000943 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000944 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000945 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000946 }
947 return SDValue();
948}
949
950/// PromoteIntShiftOp - Promote the specified integer shift operation if the
951/// target indicates it is beneficial. e.g. On x86, it's usually better to
952/// promote i16 operations to i32 since i16 instructions are longer.
953SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
954 if (!LegalOperations)
955 return SDValue();
956
957 EVT VT = Op.getValueType();
958 if (VT.isVector() || !VT.isInteger())
959 return SDValue();
960
961 // If operation type is 'undesirable', e.g. i16 on x86, consider
962 // promoting it.
963 unsigned Opc = Op.getOpcode();
964 if (TLI.isTypeDesirableForOp(Opc, VT))
965 return SDValue();
966
967 EVT PVT = VT;
968 // Consult target whether it is a good idea to promote this operation and
969 // what's the right type to promote it to.
970 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
971 assert(PVT != VT && "Don't know what type to promote to!");
972
Evan Cheng0abb54d2010-04-24 04:43:44 +0000973 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000974 SDValue N0 = Op.getOperand(0);
975 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000976 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000977 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000978 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000979 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000980 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000981 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000982 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000983
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000984 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000985 if (Replace)
986 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000987
Evan Chenge8136902010-04-27 19:48:13 +0000988 DEBUG(dbgs() << "\nPromoting ";
989 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000990 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000991 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000992 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000993 }
994 return SDValue();
995}
996
Evan Chenge19aa5c2010-04-19 19:29:22 +0000997SDValue DAGCombiner::PromoteExtend(SDValue Op) {
998 if (!LegalOperations)
999 return SDValue();
1000
1001 EVT VT = Op.getValueType();
1002 if (VT.isVector() || !VT.isInteger())
1003 return SDValue();
1004
1005 // If operation type is 'undesirable', e.g. i16 on x86, consider
1006 // promoting it.
1007 unsigned Opc = Op.getOpcode();
1008 if (TLI.isTypeDesirableForOp(Opc, VT))
1009 return SDValue();
1010
1011 EVT PVT = VT;
1012 // Consult target whether it is a good idea to promote this operation and
1013 // what's the right type to promote it to.
1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015 assert(PVT != VT && "Don't know what type to promote to!");
1016 // fold (aext (aext x)) -> (aext x)
1017 // fold (aext (zext x)) -> (zext x)
1018 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001019 DEBUG(dbgs() << "\nPromoting ";
1020 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001021 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001022 }
1023 return SDValue();
1024}
1025
1026bool DAGCombiner::PromoteLoad(SDValue Op) {
1027 if (!LegalOperations)
1028 return false;
1029
1030 EVT VT = Op.getValueType();
1031 if (VT.isVector() || !VT.isInteger())
1032 return false;
1033
1034 // If operation type is 'undesirable', e.g. i16 on x86, consider
1035 // promoting it.
1036 unsigned Opc = Op.getOpcode();
1037 if (TLI.isTypeDesirableForOp(Opc, VT))
1038 return false;
1039
1040 EVT PVT = VT;
1041 // Consult target whether it is a good idea to promote this operation and
1042 // what's the right type to promote it to.
1043 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1044 assert(PVT != VT && "Don't know what type to promote to!");
1045
Andrew Trickef9de2a2013-05-25 02:42:55 +00001046 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001047 SDNode *N = Op.getNode();
1048 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001049 EVT MemVT = LD->getMemoryVT();
1050 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001051 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001052 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001053 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001054 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001055 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001056 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001057 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1058
Evan Cheng0abb54d2010-04-24 04:43:44 +00001059 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001060 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001061 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001062 Result.getNode()->dump(&DAG);
1063 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001064 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001065 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1066 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001067 removeFromWorklist(N);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001068 DAG.DeleteNode(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001069 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001070 return true;
1071 }
1072 return false;
1073}
1074
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001075
Chris Lattnere49c9742007-05-14 22:04:50 +00001076//===----------------------------------------------------------------------===//
1077// Main DAG Combiner implementation
1078//===----------------------------------------------------------------------===//
1079
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001080void DAGCombiner::Run(CombineLevel AtLevel) {
1081 // set the instance variables, so that the various visit routines may use it.
1082 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001083 LegalOperations = Level >= AfterLegalizeVectorOps;
1084 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001085
Evan Cheng5e7658c2008-08-29 22:21:44 +00001086 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001087 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1088 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001089 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001090
Evan Cheng5e7658c2008-08-29 22:21:44 +00001091 // Create a dummy node (which is not added to allnodes), that adds a reference
1092 // to the root node, preventing it from being deleted, and tracking any
1093 // changes of the root.
1094 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001095
Jim Laskeye7d2c242006-10-17 19:33:52 +00001096 // The root of the dag may dangle to deleted nodes until the dag combiner is
1097 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001098 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001099
James Molloy67b6b112012-02-16 09:17:04 +00001100 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001101 // try and combine it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001102 while (!WorklistContents.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001103 SDNode *N;
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001104 // The WorklistOrder holds the SDNodes in order, but it may contain
Jack Carterd4e96152013-10-17 01:34:33 +00001105 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001106 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1107 // worklist *should* contain, and check the node we want to visit is should
1108 // actually be visited.
1109 do {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001110 N = WorklistOrder.pop_back_val();
1111 } while (!WorklistContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001112
Evan Cheng5e7658c2008-08-29 22:21:44 +00001113 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1114 // N is deleted from the DAG, since they too may now be dead or may have a
1115 // reduced number of uses, allowing other xforms.
Chandler Carruth24ceb0c2014-07-21 08:32:31 +00001116 if (N->use_empty()) {
Evan Cheng5e7658c2008-08-29 22:21:44 +00001117 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001118 AddToWorklist(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001119
Evan Cheng5e7658c2008-08-29 22:21:44 +00001120 DAG.DeleteNode(N);
1121 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001122 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001123
Evan Cheng5e7658c2008-08-29 22:21:44 +00001124 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001125
Craig Topperc0196b12014-04-14 00:51:57 +00001126 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001127 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001128
Evan Cheng5e7658c2008-08-29 22:21:44 +00001129 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001130
Evan Cheng5e7658c2008-08-29 22:21:44 +00001131 // If we get back the same node we passed in, rather than a new node or
1132 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001133 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001134 // mechanics for us, we have no work to do in this case.
1135 if (RV.getNode() == N)
1136 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001137
Evan Cheng5e7658c2008-08-29 22:21:44 +00001138 assert(N->getOpcode() != ISD::DELETED_NODE &&
1139 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1140 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001141
Wesley Peck527da1b2010-11-23 03:31:01 +00001142 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001143 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001144 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001145 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001146 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001147
Devang Patelefec7712011-05-23 22:04:42 +00001148 // Transfer debug value.
1149 DAG.TransferDbgValues(SDValue(N, 0), RV);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001150 WorklistRemover DeadNodes(*this);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001151 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001152 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001153 else {
1154 assert(N->getValueType(0) == RV.getValueType() &&
1155 N->getNumValues() == 1 && "Type mismatch");
1156 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001157 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001158 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001159
Evan Cheng5e7658c2008-08-29 22:21:44 +00001160 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001161 AddToWorklist(RV.getNode());
1162 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001163
Evan Cheng5e7658c2008-08-29 22:21:44 +00001164 // Add any uses of the old node to the worklist in case this node is the
1165 // last one that uses them. They may become dead after this node is
1166 // deleted.
1167 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001168 AddToWorklist(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001169
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001170 // Finally, if the node is now dead, remove it from the graph. The node
1171 // may not be dead if the replacement process recursively simplified to
1172 // something else needing this node.
1173 if (N->use_empty()) {
1174 // Nodes can be reintroduced into the worklist. Make sure we do not
1175 // process a node that has been replaced.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001176 removeFromWorklist(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001177
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001178 // Finally, since the node is now dead, remove it from the graph.
1179 DAG.DeleteNode(N);
1180 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001181 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001182
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001183 // If the root changed (e.g. it was a dead load, update the root).
1184 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001185 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001186}
1187
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001188SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001189 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001190 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001191 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001192 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001193 case ISD::ADD: return visitADD(N);
1194 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001195 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001196 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001197 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001198 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001199 case ISD::MUL: return visitMUL(N);
1200 case ISD::SDIV: return visitSDIV(N);
1201 case ISD::UDIV: return visitUDIV(N);
1202 case ISD::SREM: return visitSREM(N);
1203 case ISD::UREM: return visitUREM(N);
1204 case ISD::MULHU: return visitMULHU(N);
1205 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001206 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1207 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001208 case ISD::SMULO: return visitSMULO(N);
1209 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001210 case ISD::SDIVREM: return visitSDIVREM(N);
1211 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001212 case ISD::AND: return visitAND(N);
1213 case ISD::OR: return visitOR(N);
1214 case ISD::XOR: return visitXOR(N);
1215 case ISD::SHL: return visitSHL(N);
1216 case ISD::SRA: return visitSRA(N);
1217 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001218 case ISD::ROTR:
1219 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001220 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001221 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001222 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001223 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001224 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001225 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001226 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001227 case ISD::SELECT_CC: return visitSELECT_CC(N);
1228 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001229 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1230 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001231 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001232 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1233 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001234 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001235 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001236 case ISD::FADD: return visitFADD(N);
1237 case ISD::FSUB: return visitFSUB(N);
1238 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001239 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001240 case ISD::FDIV: return visitFDIV(N);
1241 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001242 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001243 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1244 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1245 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1246 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1247 case ISD::FP_ROUND: return visitFP_ROUND(N);
1248 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1249 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1250 case ISD::FNEG: return visitFNEG(N);
1251 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001252 case ISD::FFLOOR: return visitFFLOOR(N);
1253 case ISD::FCEIL: return visitFCEIL(N);
1254 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001255 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001256 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001257 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001258 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001259 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001260 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001261 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1262 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001263 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001264 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001265 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001266 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001267 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001268}
1269
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001270SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001271 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001272
1273 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001274 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001275 assert(N->getOpcode() != ISD::DELETED_NODE &&
1276 "Node was deleted but visit returned NULL!");
1277
1278 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1279 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1280
1281 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001282 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001283 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001284
1285 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1286 }
1287 }
1288
Evan Chengf1005572010-04-28 07:10:39 +00001289 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001290 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001291 switch (N->getOpcode()) {
1292 default: break;
1293 case ISD::ADD:
1294 case ISD::SUB:
1295 case ISD::MUL:
1296 case ISD::AND:
1297 case ISD::OR:
1298 case ISD::XOR:
1299 RV = PromoteIntBinOp(SDValue(N, 0));
1300 break;
1301 case ISD::SHL:
1302 case ISD::SRA:
1303 case ISD::SRL:
1304 RV = PromoteIntShiftOp(SDValue(N, 0));
1305 break;
1306 case ISD::SIGN_EXTEND:
1307 case ISD::ZERO_EXTEND:
1308 case ISD::ANY_EXTEND:
1309 RV = PromoteExtend(SDValue(N, 0));
1310 break;
1311 case ISD::LOAD:
1312 if (PromoteLoad(SDValue(N, 0)))
1313 RV = SDValue(N, 0);
1314 break;
1315 }
1316 }
1317
Scott Michelcf0da6c2009-02-17 22:15:04 +00001318 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001319 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001320 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001321 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001322 SDValue N0 = N->getOperand(0);
1323 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001324
Evan Cheng31604a62008-03-22 01:55:50 +00001325 // Constant operands are canonicalized to RHS.
1326 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001327 SDValue Ops[] = {N1, N0};
1328 SDNode *CSENode;
1329 if (const BinaryWithFlagsSDNode *BinNode =
1330 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1331 CSENode = DAG.getNodeIfExists(
1332 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1333 BinNode->hasNoSignedWrap(), BinNode->isExact());
1334 } else {
1335 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1336 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001337 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001338 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001339 }
1340 }
1341
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001342 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001343}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001344
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001345/// getInputChainForNode - Given a node, return its input chain if it has one,
1346/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001347static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001348 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001349 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001350 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001351 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001352 return N->getOperand(NumOps-1);
1353 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001354 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001355 return N->getOperand(i);
1356 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001357 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001358}
1359
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001360SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001361 // If N has two operands, where one has an input chain equal to the other,
1362 // the 'other' chain is redundant.
1363 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001364 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001365 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001366 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001367 return N->getOperand(1);
1368 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001369
Chris Lattner48fb92f2007-05-16 06:37:59 +00001370 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001371 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001372 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001373 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001374
Jim Laskey708d0db2006-10-04 16:53:27 +00001375 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001376 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001377
Jim Laskey0463e082006-10-07 23:37:56 +00001378 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001379 // encountered.
1380 for (unsigned i = 0; i < TFs.size(); ++i) {
1381 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001382
Jim Laskey708d0db2006-10-04 16:53:27 +00001383 // Check each of the operands.
1384 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001385 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001386
Jim Laskey708d0db2006-10-04 16:53:27 +00001387 switch (Op.getOpcode()) {
1388 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001389 // Entry tokens don't need to be added to the list. They are
1390 // rededundant.
1391 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001392 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001393
Jim Laskey708d0db2006-10-04 16:53:27 +00001394 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001395 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001396 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001397 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001398 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001399 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001400 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001401 Changed = true;
1402 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001403 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001404 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001405
Jim Laskey708d0db2006-10-04 16:53:27 +00001406 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001407 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001408 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001409 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001410 else
1411 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001412 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001413 }
1414 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001415 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001416
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001417 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001418
1419 // If we've change things around then replace token factor.
1420 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001421 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001422 // The entry token is the only possible outcome.
1423 Result = DAG.getEntryNode();
1424 } else {
1425 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001426 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001427 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001428
Jim Laskeydcf983c2006-10-13 23:32:28 +00001429 // Don't add users to work list.
1430 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001431 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001432
Jim Laskey708d0db2006-10-04 16:53:27 +00001433 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001434}
1435
Chris Lattneree322b42008-02-13 07:25:05 +00001436/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001437SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001438 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001439 // Replacing results may cause a different MERGE_VALUES to suddenly
1440 // be CSE'd with N, and carry its uses with it. Iterate until no
1441 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001442 // First add the users of this node to the work list so that they
1443 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001444 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001445 do {
1446 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001447 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001448 } while (!N->use_empty());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001449 removeFromWorklist(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001450 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001451 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001452}
1453
Evan Cheng92011002007-01-19 17:51:44 +00001454static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001455SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001456 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001457 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001458 SDValue N00 = N0.getOperand(0);
1459 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001460 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001461
Gabor Greiff304a7a2008-08-28 21:40:38 +00001462 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001463 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001464 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001465 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1466 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001467 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001468 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001469 N00.getOperand(1), N01));
1470 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001471 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001472
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001473 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001474}
1475
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001476SDValue DAGCombiner::visitADD(SDNode *N) {
1477 SDValue N0 = N->getOperand(0);
1478 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001479 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001481 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001482
1483 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001484 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001485 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001486 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001487
1488 // fold (add x, 0) -> x, vector edition
1489 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1490 return N0;
1491 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1492 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001493 }
Bill Wendling0864a752008-12-10 22:36:00 +00001494
Dan Gohman06563a82007-07-03 14:03:57 +00001495 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001496 if (N0.getOpcode() == ISD::UNDEF)
1497 return N0;
1498 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001499 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001500 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001501 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001502 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001503 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001504 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001505 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001506 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001507 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001508 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001509 // fold (add Sym, c) -> Sym+c
1510 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001511 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001512 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001513 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001514 GA->getOffset() +
1515 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001516 // fold ((c1-A)+c2) -> (c1+c2)-A
1517 if (N1C && N0.getOpcode() == ISD::SUB)
1518 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001519 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001520 DAG.getConstant(N1C->getAPIntValue()+
1521 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001522 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001523 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001524 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001525 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001526 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001527 // fold ((0-A) + B) -> B-A
1528 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1529 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001530 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001531 // fold (A + (0-B)) -> A-B
1532 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1533 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001534 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001535 // fold (A+(B-A)) -> B
1536 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001537 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001538 // fold ((B-A)+A) -> B
1539 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1540 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001541 // fold (A+(B-(A+C))) to (B-C)
1542 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001543 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001544 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001545 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001546 // fold (A+(B-(C+A))) to (B-C)
1547 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001548 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001549 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001550 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001551 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001552 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1553 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001554 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001555 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001556 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001557
Dale Johannesen8c766702008-12-02 01:30:54 +00001558 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1559 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1560 SDValue N00 = N0.getOperand(0);
1561 SDValue N01 = N0.getOperand(1);
1562 SDValue N10 = N1.getOperand(0);
1563 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001564
1565 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001566 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1567 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1568 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001569 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001570
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001571 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1572 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001573
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001574 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001575 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001576 APInt LHSZero, LHSOne;
1577 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001578 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001579
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001580 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001581 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001582
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001583 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1584 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001585 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1586 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1587 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1588 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001589 }
1590 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001591
Evan Cheng92011002007-01-19 17:51:44 +00001592 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001593 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001594 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001595 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001596 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001597 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001598 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001599 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001600 }
1601
Dan Gohman954f4902010-01-19 23:30:49 +00001602 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1603 if (N1.getOpcode() == ISD::SHL &&
1604 N1.getOperand(0).getOpcode() == ISD::SUB)
1605 if (ConstantSDNode *C =
1606 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1607 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001608 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1609 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001610 N1.getOperand(0).getOperand(1),
1611 N1.getOperand(1)));
1612 if (N0.getOpcode() == ISD::SHL &&
1613 N0.getOperand(0).getOpcode() == ISD::SUB)
1614 if (ConstantSDNode *C =
1615 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1616 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001617 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1618 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001619 N0.getOperand(0).getOperand(1),
1620 N0.getOperand(1)));
1621
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001622 if (N1.getOpcode() == ISD::AND) {
1623 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001624 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001625 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1626 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001627
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001628 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1629 // and similar xforms where the inner op is either ~0 or 0.
1630 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001631 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001632 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1633 }
1634 }
1635
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001636 // add (sext i1), X -> sub X, (zext i1)
1637 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1638 N0.getOperand(0).getValueType() == MVT::i1 &&
1639 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001640 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001641 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1642 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1643 }
1644
Evan Chengf1005572010-04-28 07:10:39 +00001645 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001646}
1647
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001648SDValue DAGCombiner::visitADDC(SDNode *N) {
1649 SDValue N0 = N->getOperand(0);
1650 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001651 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1652 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001653 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001654
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001655 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001656 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001657 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001658 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001659 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001660
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001661 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001662 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001663 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001664
Chris Lattner47206662007-03-04 20:40:38 +00001665 // fold (addc x, 0) -> x + no carry out
1666 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001667 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001668 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001669
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001670 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001671 APInt LHSZero, LHSOne;
1672 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001673 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001674
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001675 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001676 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001677
Chris Lattner47206662007-03-04 20:40:38 +00001678 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1679 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001680 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001681 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001682 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001683 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001684 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001685
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001686 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001687}
1688
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001689SDValue DAGCombiner::visitADDE(SDNode *N) {
1690 SDValue N0 = N->getOperand(0);
1691 SDValue N1 = N->getOperand(1);
1692 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001693 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1694 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001695
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001696 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001697 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001698 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001699 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001700
Chris Lattner47206662007-03-04 20:40:38 +00001701 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001702 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001703 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001704
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001705 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001706}
1707
Eric Christophere5ca1e02011-02-16 04:50:12 +00001708// Since it may not be valid to emit a fold to zero for vector initializers
1709// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001710static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001711 SelectionDAG &DAG,
1712 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001713 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001714 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001715 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1716 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001717 return SDValue();
1718}
1719
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001720SDValue DAGCombiner::visitSUB(SDNode *N) {
1721 SDValue N0 = N->getOperand(0);
1722 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001723 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1724 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001725 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001726 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001727 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001728
Dan Gohmana8665142007-06-25 16:23:39 +00001729 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001730 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001731 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001732 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001733
1734 // fold (sub x, 0) -> x, vector edition
1735 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1736 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001737 }
Bill Wendling0864a752008-12-10 22:36:00 +00001738
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001739 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001740 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001741 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001742 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001743 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001744 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001745 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001746 // fold (sub x, c) -> (add x, -c)
1747 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001748 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001749 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001750 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1751 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001752 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001753 // fold A-(A-B) -> B
1754 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1755 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001756 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001757 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001758 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001759 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001760 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001761 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001762 // fold C2-(A+C1) -> (C2-C1)-A
1763 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001764 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1765 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001766 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001767 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001768 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001769 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001770 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001771 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1772 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001773 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001774 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001775 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001776 // fold ((A+(C+B))-B) -> A+C
1777 if (N0.getOpcode() == ISD::ADD &&
1778 N0.getOperand(1).getOpcode() == ISD::ADD &&
1779 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001780 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001781 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001782 // fold ((A-(B-C))-C) -> A-B
1783 if (N0.getOpcode() == ISD::SUB &&
1784 N0.getOperand(1).getOpcode() == ISD::SUB &&
1785 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001786 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001787 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001788
Dan Gohman06563a82007-07-03 14:03:57 +00001789 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001790 if (N0.getOpcode() == ISD::UNDEF)
1791 return N0;
1792 if (N1.getOpcode() == ISD::UNDEF)
1793 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001794
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001795 // If the relocation model supports it, consider symbol offsets.
1796 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001797 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001798 // fold (sub Sym, c) -> Sym-c
1799 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001800 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001801 GA->getOffset() -
1802 (uint64_t)N1C->getSExtValue());
1803 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1804 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1805 if (GA->getGlobal() == GB->getGlobal())
1806 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1807 VT);
1808 }
1809
Evan Chengf1005572010-04-28 07:10:39 +00001810 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001811}
1812
Craig Topper43a1bd62012-01-07 09:06:39 +00001813SDValue DAGCombiner::visitSUBC(SDNode *N) {
1814 SDValue N0 = N->getOperand(0);
1815 SDValue N1 = N->getOperand(1);
1816 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1817 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1818 EVT VT = N0.getValueType();
1819
1820 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001821 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001822 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1823 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001824 MVT::Glue));
1825
1826 // fold (subc x, x) -> 0 + no borrow
1827 if (N0 == N1)
1828 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001829 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001830 MVT::Glue));
1831
1832 // fold (subc x, 0) -> x + no borrow
1833 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001834 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001835 MVT::Glue));
1836
1837 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1838 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001839 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1840 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001841 MVT::Glue));
1842
1843 return SDValue();
1844}
1845
1846SDValue DAGCombiner::visitSUBE(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
1849 SDValue CarryIn = N->getOperand(2);
1850
1851 // fold (sube x, y, false) -> (subc x, y)
1852 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001853 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001854
1855 return SDValue();
1856}
1857
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001858SDValue DAGCombiner::visitMUL(SDNode *N) {
1859 SDValue N0 = N->getOperand(0);
1860 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001861 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001862
Dan Gohman06563a82007-07-03 14:03:57 +00001863 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001864 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001865 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001866
1867 bool N0IsConst = false;
1868 bool N1IsConst = false;
1869 APInt ConstValue0, ConstValue1;
1870 // fold vector ops
1871 if (VT.isVector()) {
1872 SDValue FoldedVOp = SimplifyVBinOp(N);
1873 if (FoldedVOp.getNode()) return FoldedVOp;
1874
1875 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1876 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1877 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001878 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001879 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1880 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001881 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001882 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1883 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001884 }
1885
Nate Begeman21158fc2005-09-01 00:19:25 +00001886 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001887 if (N0IsConst && N1IsConst)
1888 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1889
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001890 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001891 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001892 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001893 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001894 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001895 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001896 // We require a splat of the entire scalar bit width for non-contiguous
1897 // bit patterns.
1898 bool IsFullSplat =
1899 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001900 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001901 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001902 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001903 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001904 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001906 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001907 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001908 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001909 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001910 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001911 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001912 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001913 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001914 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001915 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001916 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001917 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001918 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001919 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001920 DAG.getConstant(Log2Val,
1921 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001922 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001923
1924 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001925 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001926 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001927 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1928 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001929 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001930 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001931 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001932 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001933 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001934 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001935
Chris Lattner324871e2006-03-01 03:44:24 +00001936 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1937 // use.
1938 {
Craig Topperc0196b12014-04-14 00:51:57 +00001939 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001940 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001941 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001944 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001945 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001946 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001947 isa<ConstantSDNode>(N1.getOperand(1)) &&
1948 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001949 Sh = N1; Y = N0;
1950 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001951
Gabor Greiff304a7a2008-08-28 21:40:38 +00001952 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001953 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001954 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001955 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001956 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001957 }
1958 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001959
Chris Lattnerf29f5202006-03-04 23:33:26 +00001960 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001961 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1962 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1963 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001964 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1965 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001966 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001967 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001968 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001969
Nate Begeman22e251a2006-02-03 06:46:56 +00001970 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001971 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001972 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001973 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001974
Evan Chengf1005572010-04-28 07:10:39 +00001975 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001976}
1977
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001978SDValue DAGCombiner::visitSDIV(SDNode *N) {
1979 SDValue N0 = N->getOperand(0);
1980 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00001981 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1982 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001983 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001984
Dan Gohmana8665142007-06-25 16:23:39 +00001985 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001986 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001987 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001988 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001989 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001990
Nate Begeman21158fc2005-09-01 00:19:25 +00001991 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001992 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001993 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001994 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001995 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001996 return N0;
1997 // fold (sdiv X, -1) -> 0-X
1998 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001999 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002000 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002001 // If we know the sign bits of both operands are zero, strength reduce to a
2002 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002003 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002004 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002005 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002006 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002007 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002008
Nate Begeman57b35672006-02-17 07:26:20 +00002009 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002010 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2011 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002012 // If dividing by powers of two is cheap, then don't perform the following
2013 // fold.
2014 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002015 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002016
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002017 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002018
Chris Lattner471627c2006-02-16 08:02:36 +00002019 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002020 SDValue SGN =
2021 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2022 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2023 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002024 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002025
Chris Lattner471627c2006-02-16 08:02:36 +00002026 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002027 SDValue SRL =
2028 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2029 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2030 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002031 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002032 AddToWorklist(SRL.getNode());
2033 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002034 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002035 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002036
Nate Begeman4dd38312005-10-21 00:02:42 +00002037 // If we're dividing by a positive value, we're done. Otherwise, we must
2038 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002039 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002040 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002041
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002042 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002043 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002044 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002045
Nate Begemanc6f067a2005-10-20 02:15:44 +00002046 // if integer divide is expensive and we satisfy the requirements, emit an
2047 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002048 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002049 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002050 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002051 }
Dan Gohmana8665142007-06-25 16:23:39 +00002052
Dan Gohman06563a82007-07-03 14:03:57 +00002053 // undef / X -> 0
2054 if (N0.getOpcode() == ISD::UNDEF)
2055 return DAG.getConstant(0, VT);
2056 // X / undef -> undef
2057 if (N1.getOpcode() == ISD::UNDEF)
2058 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002059
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002060 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002061}
2062
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002063SDValue DAGCombiner::visitUDIV(SDNode *N) {
2064 SDValue N0 = N->getOperand(0);
2065 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002066 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2067 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002068 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002069
Dan Gohmana8665142007-06-25 16:23:39 +00002070 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002071 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002072 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002073 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002074 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002075
Nate Begeman21158fc2005-09-01 00:19:25 +00002076 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002077 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002078 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002079 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002080 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002081 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002082 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002083 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002084 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002085 if (N1.getOpcode() == ISD::SHL) {
2086 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002087 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002088 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002089 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002090 N1.getOperand(1),
2091 DAG.getConstant(SHC->getAPIntValue()
2092 .logBase2(),
2093 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002094 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002095 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002096 }
2097 }
2098 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002099 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002100 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002101 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002102 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002103 }
Dan Gohmana8665142007-06-25 16:23:39 +00002104
Dan Gohman06563a82007-07-03 14:03:57 +00002105 // undef / X -> 0
2106 if (N0.getOpcode() == ISD::UNDEF)
2107 return DAG.getConstant(0, VT);
2108 // X / undef -> undef
2109 if (N1.getOpcode() == ISD::UNDEF)
2110 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002111
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002112 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002113}
2114
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002115SDValue DAGCombiner::visitSREM(SDNode *N) {
2116 SDValue N0 = N->getOperand(0);
2117 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002118 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2119 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002120 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002121
Nate Begeman21158fc2005-09-01 00:19:25 +00002122 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002123 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002124 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002125 // If we know the sign bits of both operands are zero, strength reduce to a
2126 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002127 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002128 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002129 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002130 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002131
Dan Gohman9a693412007-11-26 23:46:11 +00002132 // If X/C can be simplified by the division-by-constant logic, lower
2133 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002134 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002135 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002136 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002137 SDValue OptimizedDiv = combine(Div.getNode());
2138 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002139 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002140 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002141 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002142 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002143 return Sub;
2144 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002145 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002146
Dan Gohman06563a82007-07-03 14:03:57 +00002147 // undef % X -> 0
2148 if (N0.getOpcode() == ISD::UNDEF)
2149 return DAG.getConstant(0, VT);
2150 // X % undef -> undef
2151 if (N1.getOpcode() == ISD::UNDEF)
2152 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002153
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002154 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002155}
2156
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002157SDValue DAGCombiner::visitUREM(SDNode *N) {
2158 SDValue N0 = N->getOperand(0);
2159 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002160 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2161 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002162 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002163
Nate Begeman21158fc2005-09-01 00:19:25 +00002164 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002165 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002166 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002167 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002168 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002169 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002170 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002171 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2172 if (N1.getOpcode() == ISD::SHL) {
2173 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002174 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002175 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002176 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002177 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002178 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002179 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002180 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002181 }
2182 }
2183 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002184
Dan Gohman9a693412007-11-26 23:46:11 +00002185 // If X/C can be simplified by the division-by-constant logic, lower
2186 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002187 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002188 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002189 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002190 SDValue OptimizedDiv = combine(Div.getNode());
2191 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002192 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002193 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002194 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002195 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002196 return Sub;
2197 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002198 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002199
Dan Gohman06563a82007-07-03 14:03:57 +00002200 // undef % X -> 0
2201 if (N0.getOpcode() == ISD::UNDEF)
2202 return DAG.getConstant(0, VT);
2203 // X % undef -> undef
2204 if (N1.getOpcode() == ISD::UNDEF)
2205 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002206
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002207 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002208}
2209
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002210SDValue DAGCombiner::visitMULHS(SDNode *N) {
2211 SDValue N0 = N->getOperand(0);
2212 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002213 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002214 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002215 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002216
Nate Begeman21158fc2005-09-01 00:19:25 +00002217 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002218 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002219 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002220 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002221 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002222 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002223 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002224 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002225 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002226 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002227 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002228
Chris Lattner10bd29f2010-12-13 08:39:01 +00002229 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2230 // plus a shift.
2231 if (VT.isSimple() && !VT.isVector()) {
2232 MVT Simple = VT.getSimpleVT();
2233 unsigned SimpleSize = Simple.getSizeInBits();
2234 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2235 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2236 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2237 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2238 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002239 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002240 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002241 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2242 }
2243 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002244
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002245 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002246}
2247
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002248SDValue DAGCombiner::visitMULHU(SDNode *N) {
2249 SDValue N0 = N->getOperand(0);
2250 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002251 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002252 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002253 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002254
Nate Begeman21158fc2005-09-01 00:19:25 +00002255 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002256 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002257 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002258 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002259 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002260 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002261 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002262 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002263 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002264
Chris Lattner10bd29f2010-12-13 08:39:01 +00002265 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2266 // plus a shift.
2267 if (VT.isSimple() && !VT.isVector()) {
2268 MVT Simple = VT.getSimpleVT();
2269 unsigned SimpleSize = Simple.getSizeInBits();
2270 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2271 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2272 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2273 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2274 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2275 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002276 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002277 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2278 }
2279 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002280
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002281 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002282}
2283
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002284/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2285/// compute two values. LoOp and HiOp give the opcodes for the two computations
2286/// that are being performed. Return true if a simplification was made.
2287///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002288SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002289 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002290 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002291 bool HiExists = N->hasAnyUseOfValue(1);
2292 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002293 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002294 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002295 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002296 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002297 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002298 }
2299
2300 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002301 bool LoExists = N->hasAnyUseOfValue(0);
2302 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002303 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002304 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002305 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002306 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002307 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002308 }
2309
Evan Chengece4c682007-11-08 09:25:29 +00002310 // If both halves are used, return as it is.
2311 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002312 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002313
2314 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002315 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002316 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002317 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002318 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002319 SDValue LoOpt = combine(Lo.getNode());
2320 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002321 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002322 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002323 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002324 }
2325
Evan Chengece4c682007-11-08 09:25:29 +00002326 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002327 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002328 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002329 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002330 SDValue HiOpt = combine(Hi.getNode());
2331 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002332 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002333 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002334 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002335 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002336
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002337 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002338}
2339
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002340SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2341 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002342 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002343
Chris Lattner15090e12010-12-15 06:04:19 +00002344 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002345 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002346
2347 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2348 // plus a shift.
2349 if (VT.isSimple() && !VT.isVector()) {
2350 MVT Simple = VT.getSimpleVT();
2351 unsigned SimpleSize = Simple.getSizeInBits();
2352 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2353 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2354 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2355 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2356 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2357 // Compute the high part as N1.
2358 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002359 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002360 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2361 // Compute the low part as N0.
2362 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2363 return CombineTo(N, Lo, Hi);
2364 }
2365 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002366
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002367 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002368}
2369
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002370SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2371 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002372 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002373
Chris Lattner15090e12010-12-15 06:04:19 +00002374 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002375 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002376
Chris Lattner15090e12010-12-15 06:04:19 +00002377 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2378 // plus a shift.
2379 if (VT.isSimple() && !VT.isVector()) {
2380 MVT Simple = VT.getSimpleVT();
2381 unsigned SimpleSize = Simple.getSizeInBits();
2382 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2385 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2386 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2387 // Compute the high part as N1.
2388 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002389 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002390 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2391 // Compute the low part as N0.
2392 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2393 return CombineTo(N, Lo, Hi);
2394 }
2395 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002396
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002397 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002398}
2399
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002400SDValue DAGCombiner::visitSMULO(SDNode *N) {
2401 // (smulo x, 2) -> (saddo x, x)
2402 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2403 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002404 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002405 N->getOperand(0), N->getOperand(0));
2406
2407 return SDValue();
2408}
2409
2410SDValue DAGCombiner::visitUMULO(SDNode *N) {
2411 // (umulo x, 2) -> (uaddo x, x)
2412 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2413 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002414 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002415 N->getOperand(0), N->getOperand(0));
2416
2417 return SDValue();
2418}
2419
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002420SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2421 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002422 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002423
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002424 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002425}
2426
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002427SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2428 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002429 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002430
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002431 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002432}
2433
Chris Lattner8d6fc202006-05-05 05:51:50 +00002434/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2435/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002436SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2437 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002438 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002439 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002440
Dan Gohmandd5286d2010-01-14 03:08:49 +00002441 // Bail early if none of these transforms apply.
2442 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2443
Chris Lattner002ee912006-05-05 06:31:05 +00002444 // For each of OP in AND/OR/XOR:
2445 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2446 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2447 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002448 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002449 //
2450 // do not sink logical op inside of a vector extend, since it may combine
2451 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002452 EVT Op0VT = N0.getOperand(0).getValueType();
2453 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002454 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002455 // Avoid infinite looping with PromoteIntBinOp.
2456 (N0.getOpcode() == ISD::ANY_EXTEND &&
2457 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002458 (N0.getOpcode() == ISD::TRUNCATE &&
2459 (!TLI.isZExtFree(VT, Op0VT) ||
2460 !TLI.isTruncateFree(Op0VT, VT)) &&
2461 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002462 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002463 Op0VT == N1.getOperand(0).getValueType() &&
2464 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002465 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002466 N0.getOperand(0).getValueType(),
2467 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002468 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002469 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002470 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002471
Chris Lattner5ac42932006-05-05 06:10:43 +00002472 // For each of OP in SHL/SRL/SRA/AND...
2473 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2474 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2475 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002476 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002477 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002478 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002479 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002480 N0.getOperand(0).getValueType(),
2481 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002482 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002483 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002484 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002485 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002486
Nadav Rotemb0783502012-04-01 19:31:22 +00002487 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2488 // Only perform this optimization after type legalization and before
2489 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2490 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2491 // we don't want to undo this promotion.
2492 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2493 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002494 if ((N0.getOpcode() == ISD::BITCAST ||
2495 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2496 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002497 SDValue In0 = N0.getOperand(0);
2498 SDValue In1 = N1.getOperand(0);
2499 EVT In0Ty = In0.getValueType();
2500 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002501 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002502 // If both incoming values are integers, and the original types are the
2503 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002504 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002505 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2506 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002507 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002508 return BC;
2509 }
2510 }
2511
2512 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2513 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2514 // If both shuffles use the same mask, and both shuffle within a single
2515 // vector, then it is worthwhile to move the swizzle after the operation.
2516 // The type-legalizer generates this pattern when loading illegal
2517 // vector types from memory. In many cases this allows additional shuffle
2518 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002519 // There are other cases where moving the shuffle after the xor/and/or
2520 // is profitable even if shuffles don't perform a swizzle.
2521 // If both shuffles use the same mask, and both shuffles have the same first
2522 // or second operand, then it might still be profitable to move the shuffle
2523 // after the xor/and/or operation.
2524 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002525 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2526 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002527
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002528 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002529 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002530
Nadav Rotemb0783502012-04-01 19:31:22 +00002531 // Check that both shuffles use the same mask. The masks are known to be of
2532 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002533 // Check also that shuffles have only one use to avoid introducing extra
2534 // instructions.
2535 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2536 SVN0->getMask().equals(SVN1->getMask())) {
2537 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002538
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002539 // Don't try to fold this node if it requires introducing a
2540 // build vector of all zeros that might be illegal at this stage.
2541 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2542 if (!LegalTypes)
2543 ShOp = DAG.getConstant(0, VT);
2544 else
2545 ShOp = SDValue();
2546 }
2547
2548 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2549 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2550 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2551 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2552 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2553 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002554 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002555 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2556 &SVN0->getMask()[0]);
2557 }
2558
2559 // Don't try to fold this node if it requires introducing a
2560 // build vector of all zeros that might be illegal at this stage.
2561 ShOp = N0->getOperand(0);
2562 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2563 if (!LegalTypes)
2564 ShOp = DAG.getConstant(0, VT);
2565 else
2566 ShOp = SDValue();
2567 }
2568
2569 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2570 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2571 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2572 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2573 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2574 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002575 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002576 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2577 &SVN0->getMask()[0]);
2578 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002579 }
2580 }
Craig Topper9c3da312012-04-09 07:19:09 +00002581
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002582 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002583}
2584
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002585SDValue DAGCombiner::visitAND(SDNode *N) {
2586 SDValue N0 = N->getOperand(0);
2587 SDValue N1 = N->getOperand(1);
2588 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002589 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2590 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002591 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002592 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002593
Dan Gohmana8665142007-06-25 16:23:39 +00002594 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002595 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002596 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002597 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002598
2599 // fold (and x, 0) -> 0, vector edition
2600 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2601 return N0;
2602 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2603 return N1;
2604
2605 // fold (and x, -1) -> x, vector edition
2606 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2607 return N1;
2608 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2609 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002610 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002611
Dan Gohman06563a82007-07-03 14:03:57 +00002612 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002613 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002614 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002615 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002616 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002617 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002618 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002619 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002620 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002621 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002622 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002623 return N0;
2624 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002625 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002626 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002627 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002628 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002629 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002630 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002631 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002632 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002633 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002634 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002635 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002636 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002637 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2638 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002639 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002640 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002641 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002642 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002643 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002644 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002645
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002646 // Replace uses of the AND with uses of the Zero extend node.
2647 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002648
Chris Lattner49beaf42006-02-02 07:17:31 +00002649 // We actually want to replace all uses of the any_extend with the
2650 // zero_extend, to avoid duplicating things. This will later cause this
2651 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002652 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002654 }
2655 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002656 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002657 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2658 // already be zero by virtue of the width of the base type of the load.
2659 //
2660 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2661 // more cases.
2662 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2663 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2664 N0.getOpcode() == ISD::LOAD) {
2665 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2666 N0 : N0.getOperand(0) );
2667
2668 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2669 // This can be a pure constant or a vector splat, in which case we treat the
2670 // vector as a scalar and use the splat value.
2671 APInt Constant = APInt::getNullValue(1);
2672 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2673 Constant = C->getAPIntValue();
2674 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2675 APInt SplatValue, SplatUndef;
2676 unsigned SplatBitSize;
2677 bool HasAnyUndefs;
2678 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2679 SplatBitSize, HasAnyUndefs);
2680 if (IsSplat) {
2681 // Undef bits can contribute to a possible optimisation if set, so
2682 // set them.
2683 SplatValue |= SplatUndef;
2684
2685 // The splat value may be something like "0x00FFFFFF", which means 0 for
2686 // the first vector value and FF for the rest, repeating. We need a mask
2687 // that will apply equally to all members of the vector, so AND all the
2688 // lanes of the constant together.
2689 EVT VT = Vector->getValueType(0);
2690 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002691
2692 // If the splat value has been compressed to a bitlength lower
2693 // than the size of the vector lane, we need to re-expand it to
2694 // the lane size.
2695 if (BitWidth > SplatBitSize)
2696 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2697 SplatBitSize < BitWidth;
2698 SplatBitSize = SplatBitSize * 2)
2699 SplatValue |= SplatValue.shl(SplatBitSize);
2700
James Molloy862fe492012-02-20 12:02:38 +00002701 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002702 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002703 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2704 }
2705 }
2706
2707 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2708 // actually legal and isn't going to get expanded, else this is a false
2709 // optimisation.
2710 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2711 Load->getMemoryVT());
2712
2713 // Resize the constant to the same size as the original memory access before
2714 // extension. If it is still the AllOnesValue then this AND is completely
2715 // unneeded.
2716 Constant =
2717 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2718
2719 bool B;
2720 switch (Load->getExtensionType()) {
2721 default: B = false; break;
2722 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2723 case ISD::ZEXTLOAD:
2724 case ISD::NON_EXTLOAD: B = true; break;
2725 }
2726
2727 if (B && Constant.isAllOnesValue()) {
2728 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2729 // preserve semantics once we get rid of the AND.
2730 SDValue NewLoad(Load, 0);
2731 if (Load->getExtensionType() == ISD::EXTLOAD) {
2732 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002733 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002734 Load->getChain(), Load->getBasePtr(),
2735 Load->getOffset(), Load->getMemoryVT(),
2736 Load->getMemOperand());
2737 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002738 if (Load->getNumValues() == 3) {
2739 // PRE/POST_INC loads have 3 values.
2740 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2741 NewLoad.getValue(2) };
2742 CombineTo(Load, To, 3, true);
2743 } else {
2744 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2745 }
James Molloy862fe492012-02-20 12:02:38 +00002746 }
2747
2748 // Fold the AND away, taking care not to fold to the old load node if we
2749 // replaced it.
2750 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2751
2752 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2753 }
2754 }
Nate Begeman049b7482005-09-09 19:49:52 +00002755 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2756 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2757 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2758 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002759
Tom Stellard7783b0a2014-06-12 16:04:47 +00002760 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002761 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002762 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002763 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002764 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002765 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002766 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002767 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002768 }
Bill Wendling86171912009-01-30 20:43:18 +00002769 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002770 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002771 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002772 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002773 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002774 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002775 }
Bill Wendling86171912009-01-30 20:43:18 +00002776 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002777 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002778 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002779 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002780 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002781 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002782 }
2783 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002784 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2785 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2786 Op0 == Op1 && LL.getValueType().isInteger() &&
2787 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2788 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2789 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2790 cast<ConstantSDNode>(RR)->isNullValue()))) {
2791 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2792 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002793 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002794 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2795 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2796 }
Nate Begeman049b7482005-09-09 19:49:52 +00002797 // canonicalize equivalent to ll == rl
2798 if (LL == RR && LR == RL) {
2799 Op1 = ISD::getSetCCSwappedOperands(Op1);
2800 std::swap(RL, RR);
2801 }
2802 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002803 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002804 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002805 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002806 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002807 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2808 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002809 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002810 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002811 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002812 }
2813 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002814
Bill Wendling86171912009-01-30 20:43:18 +00002815 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002816 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002817 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002818 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002819 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002820
Nate Begemandc7bba92006-02-03 22:24:05 +00002821 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2822 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002823 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002824 SimplifyDemandedBits(SDValue(N, 0)))
2825 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002826
Nate Begeman02b23c62005-10-13 03:11:28 +00002827 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002828 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002829 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002830 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002831 // If we zero all the possible extended bits, then we can turn this into
2832 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002833 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002834 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002835 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002836 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002837 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002838 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002839 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002840 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002841 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002842 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002844 }
2845 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002846 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002847 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002848 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002849 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002850 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002851 // If we zero all the possible extended bits, then we can turn this into
2852 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002853 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002854 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002855 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002856 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002857 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002858 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002859 LN0->getChain(), LN0->getBasePtr(),
2860 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002861 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002862 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002864 }
2865 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002866
Chris Lattnerf0032b32006-02-28 06:49:37 +00002867 // fold (and (load x), 255) -> (zextload x, i8)
2868 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002869 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2870 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2871 (N0.getOpcode() == ISD::ANY_EXTEND &&
2872 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2873 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2874 LoadSDNode *LN0 = HasAnyExt
2875 ? cast<LoadSDNode>(N0.getOperand(0))
2876 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002877 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002878 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002879 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002880 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2881 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2882 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002883
Evan Cheng166a4e62010-01-06 19:38:29 +00002884 if (ExtVT == LoadedVT &&
2885 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002886 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002887
2888 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002889 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002890 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2891 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002892 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002893 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2894 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2895 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002896
Chris Lattner88de3842010-01-07 21:53:27 +00002897 // Do not change the width of a volatile load.
2898 // Do not generate loads of non-round integer types since these can
2899 // be expensive (and would be wrong if the type is not byte sized).
2900 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2901 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2902 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002903
Chris Lattner88de3842010-01-07 21:53:27 +00002904 unsigned Alignment = LN0->getAlignment();
2905 SDValue NewPtr = LN0->getBasePtr();
2906
2907 // For big endian targets, we need to add an offset to the pointer
2908 // to load the correct bytes. For little endian systems, we merely
2909 // need to read fewer bytes from the same pointer.
2910 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002911 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2912 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2913 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002914 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002915 NewPtr, DAG.getConstant(PtrOff, PtrType));
2916 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002917 }
Chris Lattner88de3842010-01-07 21:53:27 +00002918
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002919 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002920
Chris Lattner88de3842010-01-07 21:53:27 +00002921 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2922 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002923 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002924 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002925 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002926 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002927 Alignment, LN0->getTBAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002928 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002929 CombineTo(LN0, Load, Load.getValue(1));
2930 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002931 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002932 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002933 }
2934 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002935
Evan Chenge6a3b032012-07-17 18:54:11 +00002936 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2937 VT.getSizeInBits() <= 64) {
2938 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2939 APInt ADDC = ADDI->getAPIntValue();
2940 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2942 // immediate for an add, but it is legal if its top c2 bits are set,
2943 // transform the ADD so the immediate doesn't need to be materialized
2944 // in a register.
2945 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2946 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2947 SRLI->getZExtValue());
2948 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2949 ADDC |= Mask;
2950 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2951 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002952 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002953 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2954 CombineTo(N0.getNode(), NewAdd);
2955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2956 }
2957 }
2958 }
2959 }
2960 }
2961 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002962
Tim Northover819bfb52013-08-27 13:46:45 +00002963 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2964 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2965 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2966 N0.getOperand(1), false);
2967 if (BSwap.getNode())
2968 return BSwap;
2969 }
2970
Evan Chengf1005572010-04-28 07:10:39 +00002971 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002972}
2973
Evan Cheng4c0bd962011-06-21 06:01:08 +00002974/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2975///
2976SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2977 bool DemandHighBits) {
2978 if (!LegalOperations)
2979 return SDValue();
2980
2981 EVT VT = N->getValueType(0);
2982 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2983 return SDValue();
2984 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2985 return SDValue();
2986
2987 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2988 bool LookPassAnd0 = false;
2989 bool LookPassAnd1 = false;
2990 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2991 std::swap(N0, N1);
2992 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2993 std::swap(N0, N1);
2994 if (N0.getOpcode() == ISD::AND) {
2995 if (!N0.getNode()->hasOneUse())
2996 return SDValue();
2997 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2998 if (!N01C || N01C->getZExtValue() != 0xFF00)
2999 return SDValue();
3000 N0 = N0.getOperand(0);
3001 LookPassAnd0 = true;
3002 }
3003
3004 if (N1.getOpcode() == ISD::AND) {
3005 if (!N1.getNode()->hasOneUse())
3006 return SDValue();
3007 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3008 if (!N11C || N11C->getZExtValue() != 0xFF)
3009 return SDValue();
3010 N1 = N1.getOperand(0);
3011 LookPassAnd1 = true;
3012 }
3013
3014 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3015 std::swap(N0, N1);
3016 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3017 return SDValue();
3018 if (!N0.getNode()->hasOneUse() ||
3019 !N1.getNode()->hasOneUse())
3020 return SDValue();
3021
3022 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3023 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3024 if (!N01C || !N11C)
3025 return SDValue();
3026 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3027 return SDValue();
3028
3029 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3030 SDValue N00 = N0->getOperand(0);
3031 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3032 if (!N00.getNode()->hasOneUse())
3033 return SDValue();
3034 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3035 if (!N001C || N001C->getZExtValue() != 0xFF)
3036 return SDValue();
3037 N00 = N00.getOperand(0);
3038 LookPassAnd0 = true;
3039 }
3040
3041 SDValue N10 = N1->getOperand(0);
3042 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3043 if (!N10.getNode()->hasOneUse())
3044 return SDValue();
3045 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3046 if (!N101C || N101C->getZExtValue() != 0xFF00)
3047 return SDValue();
3048 N10 = N10.getOperand(0);
3049 LookPassAnd1 = true;
3050 }
3051
3052 if (N00 != N10)
3053 return SDValue();
3054
Tim Northover819bfb52013-08-27 13:46:45 +00003055 // Make sure everything beyond the low halfword gets set to zero since the SRL
3056 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003057 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003058 if (DemandHighBits && OpSizeInBits > 16) {
3059 // If the left-shift isn't masked out then the only way this is a bswap is
3060 // if all bits beyond the low 8 are 0. In that case the entire pattern
3061 // reduces to a left shift anyway: leave it for other parts of the combiner.
3062 if (!LookPassAnd0)
3063 return SDValue();
3064
3065 // However, if the right shift isn't masked out then it might be because
3066 // it's not needed. See if we can spot that too.
3067 if (!LookPassAnd1 &&
3068 !DAG.MaskedValueIsZero(
3069 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3070 return SDValue();
3071 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003072
Andrew Trickef9de2a2013-05-25 02:42:55 +00003073 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003074 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003075 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003076 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3077 return Res;
3078}
3079
3080/// isBSwapHWordElement - Return true if the specified node is an element
3081/// that makes up a 32-bit packed halfword byteswap. i.e.
3082/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003083static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003084 if (!N.getNode()->hasOneUse())
3085 return false;
3086
3087 unsigned Opc = N.getOpcode();
3088 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3089 return false;
3090
3091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3092 if (!N1C)
3093 return false;
3094
3095 unsigned Num;
3096 switch (N1C->getZExtValue()) {
3097 default:
3098 return false;
3099 case 0xFF: Num = 0; break;
3100 case 0xFF00: Num = 1; break;
3101 case 0xFF0000: Num = 2; break;
3102 case 0xFF000000: Num = 3; break;
3103 }
3104
3105 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3106 SDValue N0 = N.getOperand(0);
3107 if (Opc == ISD::AND) {
3108 if (Num == 0 || Num == 2) {
3109 // (x >> 8) & 0xff
3110 // (x >> 8) & 0xff0000
3111 if (N0.getOpcode() != ISD::SRL)
3112 return false;
3113 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114 if (!C || C->getZExtValue() != 8)
3115 return false;
3116 } else {
3117 // (x << 8) & 0xff00
3118 // (x << 8) & 0xff000000
3119 if (N0.getOpcode() != ISD::SHL)
3120 return false;
3121 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3122 if (!C || C->getZExtValue() != 8)
3123 return false;
3124 }
3125 } else if (Opc == ISD::SHL) {
3126 // (x & 0xff) << 8
3127 // (x & 0xff0000) << 8
3128 if (Num != 0 && Num != 2)
3129 return false;
3130 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3131 if (!C || C->getZExtValue() != 8)
3132 return false;
3133 } else { // Opc == ISD::SRL
3134 // (x & 0xff00) >> 8
3135 // (x & 0xff000000) >> 8
3136 if (Num != 1 && Num != 3)
3137 return false;
3138 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3139 if (!C || C->getZExtValue() != 8)
3140 return false;
3141 }
3142
3143 if (Parts[Num])
3144 return false;
3145
3146 Parts[Num] = N0.getOperand(0).getNode();
3147 return true;
3148}
3149
3150/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3151/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3152/// => (rotl (bswap x), 16)
3153SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3154 if (!LegalOperations)
3155 return SDValue();
3156
3157 EVT VT = N->getValueType(0);
3158 if (VT != MVT::i32)
3159 return SDValue();
3160 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3161 return SDValue();
3162
Craig Topperc0196b12014-04-14 00:51:57 +00003163 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003164 // Look for either
3165 // (or (or (and), (and)), (or (and), (and)))
3166 // (or (or (or (and), (and)), (and)), (and))
3167 if (N0.getOpcode() != ISD::OR)
3168 return SDValue();
3169 SDValue N00 = N0.getOperand(0);
3170 SDValue N01 = N0.getOperand(1);
3171
Evan Chengbf0baa92012-12-13 01:34:32 +00003172 if (N1.getOpcode() == ISD::OR &&
3173 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003174 // (or (or (and), (and)), (or (and), (and)))
3175 SDValue N000 = N00.getOperand(0);
3176 if (!isBSwapHWordElement(N000, Parts))
3177 return SDValue();
3178
3179 SDValue N001 = N00.getOperand(1);
3180 if (!isBSwapHWordElement(N001, Parts))
3181 return SDValue();
3182 SDValue N010 = N01.getOperand(0);
3183 if (!isBSwapHWordElement(N010, Parts))
3184 return SDValue();
3185 SDValue N011 = N01.getOperand(1);
3186 if (!isBSwapHWordElement(N011, Parts))
3187 return SDValue();
3188 } else {
3189 // (or (or (or (and), (and)), (and)), (and))
3190 if (!isBSwapHWordElement(N1, Parts))
3191 return SDValue();
3192 if (!isBSwapHWordElement(N01, Parts))
3193 return SDValue();
3194 if (N00.getOpcode() != ISD::OR)
3195 return SDValue();
3196 SDValue N000 = N00.getOperand(0);
3197 if (!isBSwapHWordElement(N000, Parts))
3198 return SDValue();
3199 SDValue N001 = N00.getOperand(1);
3200 if (!isBSwapHWordElement(N001, Parts))
3201 return SDValue();
3202 }
3203
3204 // Make sure the parts are all coming from the same node.
3205 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3206 return SDValue();
3207
Andrew Trickef9de2a2013-05-25 02:42:55 +00003208 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003209 SDValue(Parts[0],0));
3210
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003211 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003212 // do (x << 16) | (x >> 16).
3213 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3214 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003215 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003216 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003217 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3218 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3219 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3220 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003221}
3222
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003223SDValue DAGCombiner::visitOR(SDNode *N) {
3224 SDValue N0 = N->getOperand(0);
3225 SDValue N1 = N->getOperand(1);
3226 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003229 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003230
Dan Gohmana8665142007-06-25 16:23:39 +00003231 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003232 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003233 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003234 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003235
3236 // fold (or x, 0) -> x, vector edition
3237 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3238 return N1;
3239 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3240 return N0;
3241
3242 // fold (or x, -1) -> -1, vector edition
3243 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3244 return N0;
3245 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3246 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003247
3248 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3249 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3250 // Do this only if the resulting shuffle is legal.
3251 if (isa<ShuffleVectorSDNode>(N0) &&
3252 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003253 // Avoid folding a node with illegal type.
3254 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003255 N0->getOperand(1) == N1->getOperand(1) &&
3256 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3257 bool CanFold = true;
3258 unsigned NumElts = VT.getVectorNumElements();
3259 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3260 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3261 // We construct two shuffle masks:
3262 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3263 // and N1 as the second operand.
3264 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3265 // and N0 as the second operand.
3266 // We do this because OR is commutable and therefore there might be
3267 // two ways to fold this node into a shuffle.
3268 SmallVector<int,4> Mask1;
3269 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003270
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003271 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3272 int M0 = SV0->getMaskElt(i);
3273 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003274
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003275 // Both shuffle indexes are undef. Propagate Undef.
3276 if (M0 < 0 && M1 < 0) {
3277 Mask1.push_back(M0);
3278 Mask2.push_back(M0);
3279 continue;
3280 }
3281
3282 if (M0 < 0 || M1 < 0 ||
3283 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3284 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3285 CanFold = false;
3286 break;
3287 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003288
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003289 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3290 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3291 }
3292
3293 if (CanFold) {
3294 // Fold this sequence only if the resulting shuffle is 'legal'.
3295 if (TLI.isShuffleMaskLegal(Mask1, VT))
3296 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3297 N1->getOperand(0), &Mask1[0]);
3298 if (TLI.isShuffleMaskLegal(Mask2, VT))
3299 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3300 N0->getOperand(0), &Mask2[0]);
3301 }
3302 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003303 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003304
Dan Gohman06563a82007-07-03 14:03:57 +00003305 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003306 if (!LegalOperations &&
3307 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003308 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3309 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3310 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003311 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003312 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003313 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003314 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003315 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003316 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003317 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003318 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003319 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003320 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003321 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003322 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003323 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003324 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003325 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003326
3327 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3328 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003329 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003330 return BSwap;
3331 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003332 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003333 return BSwap;
3334
Nate Begeman22e251a2006-02-03 06:46:56 +00003335 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003336 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003337 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003338 return ROR;
3339 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003340 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003341 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003342 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003343 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003344 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3345 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3346 if (!COR.getNode())
3347 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003348 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3349 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003350 N0.getOperand(0), N1), COR);
3351 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003352 }
Nate Begeman049b7482005-09-09 19:49:52 +00003353 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3354 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3355 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3356 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003357
Nate Begeman049b7482005-09-09 19:49:52 +00003358 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003359 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003360 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3361 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003362 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003363 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003364 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003365 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003366 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003367 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003368 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003369 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3370 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003371 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003372 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003373 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003374 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003375 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003376 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003377 }
3378 }
3379 // canonicalize equivalent to ll == rl
3380 if (LL == RR && LR == RL) {
3381 Op1 = ISD::getSetCCSwappedOperands(Op1);
3382 std::swap(RL, RR);
3383 }
3384 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003385 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003386 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003387 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003388 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003389 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3390 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003391 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003392 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003393 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003394 }
3395 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003396
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003397 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003398 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003399 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003400 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003401 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003402
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003403 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003404 if (N0.getOpcode() == ISD::AND &&
3405 N1.getOpcode() == ISD::AND &&
3406 N0.getOperand(1).getOpcode() == ISD::Constant &&
3407 N1.getOperand(1).getOpcode() == ISD::Constant &&
3408 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003409 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003410 // We can only do this xform if we know that bits from X that are set in C2
3411 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003412 const APInt &LHSMask =
3413 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3414 const APInt &RHSMask =
3415 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003416
Dan Gohman309d3d52007-06-22 14:59:07 +00003417 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3418 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003419 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003420 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003421 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003422 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003423 }
3424 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003425
Chris Lattner97614c82006-09-14 20:50:57 +00003426 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003427 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003428 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003429
Dan Gohman600f62b2010-06-24 14:30:44 +00003430 // Simplify the operands using demanded-bits information.
3431 if (!VT.isVector() &&
3432 SimplifyDemandedBits(SDValue(N, 0)))
3433 return SDValue(N, 0);
3434
Evan Chengf1005572010-04-28 07:10:39 +00003435 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003436}
3437
Chris Lattner97614c82006-09-14 20:50:57 +00003438/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003439static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003440 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003441 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003442 Mask = Op.getOperand(1);
3443 Op = Op.getOperand(0);
3444 } else {
3445 return false;
3446 }
3447 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003448
Chris Lattner97614c82006-09-14 20:50:57 +00003449 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3450 Shift = Op;
3451 return true;
3452 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003453
Scott Michelcf0da6c2009-02-17 22:15:04 +00003454 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003455}
3456
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003457// Return true if we can prove that, whenever Neg and Pos are both in the
3458// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003459// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3460//
3461// (or (shift1 X, Neg), (shift2 X, Pos))
3462//
Adam Nemetc6553a82014-03-07 23:56:24 +00003463// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3464// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3465// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003466static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003467 // If OpSize is a power of 2 then:
3468 //
3469 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3470 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3471 //
3472 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3473 // for the stronger condition:
3474 //
3475 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3476 //
3477 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3478 // we can just replace Neg with Neg' for the rest of the function.
3479 //
3480 // In other cases we check for the even stronger condition:
3481 //
3482 // Neg == OpSize - Pos [B]
3483 //
3484 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3485 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003486 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003487 // We could actually use [A] whenever OpSize is a power of 2, but the
3488 // only extra cases that it would match are those uninteresting ones
3489 // where Neg and Pos are never in range at the same time. E.g. for
3490 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3491 // as well as (sub 32, Pos), but:
3492 //
3493 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3494 //
3495 // always invokes undefined behavior for 32-bit X.
3496 //
3497 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003498 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003499 if (Neg.getOpcode() == ISD::AND &&
3500 isPowerOf2_64(OpSize) &&
3501 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3502 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3503 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003504 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003505 }
3506
Richard Sandiford0f264db2014-01-09 10:49:40 +00003507 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3508 if (Neg.getOpcode() != ISD::SUB)
3509 return 0;
3510 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3511 if (!NegC)
3512 return 0;
3513 SDValue NegOp1 = Neg.getOperand(1);
3514
Adam Nemet5117f5d2014-03-07 23:56:28 +00003515 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3516 // Pos'. The truncation is redundant for the purpose of the equality.
3517 if (MaskLoBits &&
3518 Pos.getOpcode() == ISD::AND &&
3519 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3520 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3521 Pos = Pos.getOperand(0);
3522
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003523 // The condition we need is now:
3524 //
3525 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3526 //
3527 // If NegOp1 == Pos then we need:
3528 //
3529 // OpSize & Mask == NegC & Mask
3530 //
3531 // (because "x & Mask" is a truncation and distributes through subtraction).
3532 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003533 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003534 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003535 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3536 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003537 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003538 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3539 //
3540 // which, again because "x & Mask" is a truncation, becomes:
3541 //
3542 // NegC & Mask == (OpSize - PosC) & Mask
3543 // OpSize & Mask == (NegC + PosC) & Mask
3544 else if (Pos.getOpcode() == ISD::ADD &&
3545 Pos.getOperand(0) == NegOp1 &&
3546 Pos.getOperand(1).getOpcode() == ISD::Constant)
3547 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3548 NegC->getAPIntValue());
3549 else
3550 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003551
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003552 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003553 if (MaskLoBits)
3554 // Opsize & Mask is 0 since Mask is Opsize - 1.
3555 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003556 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003557}
3558
Richard Sandiford95c864d2014-01-08 15:40:47 +00003559// A subroutine of MatchRotate used once we have found an OR of two opposite
3560// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3561// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3562// former being preferred if supported. InnerPos and InnerNeg are Pos and
3563// Neg with outer conversions stripped away.
3564SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3565 SDValue Neg, SDValue InnerPos,
3566 SDValue InnerNeg, unsigned PosOpcode,
3567 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003568 // fold (or (shl x, (*ext y)),
3569 // (srl x, (*ext (sub 32, y)))) ->
3570 // (rotl x, y) or (rotr x, (sub 32, y))
3571 //
3572 // fold (or (shl x, (*ext (sub 32, y))),
3573 // (srl x, (*ext y))) ->
3574 // (rotr x, y) or (rotl x, (sub 32, y))
3575 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003576 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003577 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3578 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3579 HasPos ? Pos : Neg).getNode();
3580 }
3581
Craig Topperc0196b12014-04-14 00:51:57 +00003582 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003583}
3584
Chris Lattner97614c82006-09-14 20:50:57 +00003585// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3586// idioms for rotate, and if the target supports rotation instructions, generate
3587// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003588SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003589 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003590 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003591 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003592
3593 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003594 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3595 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003596 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003597
Chris Lattner97614c82006-09-14 20:50:57 +00003598 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003599 SDValue LHSShift; // The shift.
3600 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003601 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003602 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003603
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003604 SDValue RHSShift; // The shift.
3605 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003606 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003607 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003608
Chris Lattner97614c82006-09-14 20:50:57 +00003609 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003610 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003611
3612 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003613 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003614
Chris Lattner97614c82006-09-14 20:50:57 +00003615 // Canonicalize shl to left side in a shl/srl pair.
3616 if (RHSShift.getOpcode() == ISD::SHL) {
3617 std::swap(LHS, RHS);
3618 std::swap(LHSShift, RHSShift);
3619 std::swap(LHSMask , RHSMask );
3620 }
3621
Duncan Sands13237ac2008-06-06 12:08:01 +00003622 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003623 SDValue LHSShiftArg = LHSShift.getOperand(0);
3624 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003625 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003626 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003627
3628 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3629 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003630 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3631 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003632 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3633 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003634 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003635 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003636
Craig Topper65161fa2012-09-29 06:54:22 +00003637 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3638 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003639
Chris Lattner97614c82006-09-14 20:50:57 +00003640 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003641 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003642 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003643
Gabor Greiff304a7a2008-08-28 21:40:38 +00003644 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003645 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3646 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003647 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003648 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003649 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3650 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003651 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003652
Bill Wendling35972a92009-01-30 21:14:50 +00003653 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003654 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003655
Gabor Greiff304a7a2008-08-28 21:40:38 +00003656 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003657 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003658
Chris Lattner97614c82006-09-14 20:50:57 +00003659 // If there is a mask here, and we have a variable shift, we can't be sure
3660 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003661 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003662 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003663
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003664 // If the shift amount is sign/zext/any-extended just peel it off.
3665 SDValue LExtOp0 = LHSShiftAmt;
3666 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003667 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3668 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3669 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3670 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3671 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3672 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3673 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3674 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003675 LExtOp0 = LHSShiftAmt.getOperand(0);
3676 RExtOp0 = RHSShiftAmt.getOperand(0);
3677 }
3678
Richard Sandiford95c864d2014-01-08 15:40:47 +00003679 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3680 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3681 if (TryL)
3682 return TryL;
3683
3684 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3685 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3686 if (TryR)
3687 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003688
Craig Topperc0196b12014-04-14 00:51:57 +00003689 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003690}
3691
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003692SDValue DAGCombiner::visitXOR(SDNode *N) {
3693 SDValue N0 = N->getOperand(0);
3694 SDValue N1 = N->getOperand(1);
3695 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003698 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003699
Dan Gohmana8665142007-06-25 16:23:39 +00003700 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003701 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003702 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003703 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003704
3705 // fold (xor x, 0) -> x, vector edition
3706 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3707 return N1;
3708 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3709 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003710 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003711
Evan Chengdf1690d2008-03-25 20:08:07 +00003712 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3713 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3714 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003715 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003716 if (N0.getOpcode() == ISD::UNDEF)
3717 return N0;
3718 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003719 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003720 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003721 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003722 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003723 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003724 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003725 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003726 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003727 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003728 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003729 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003730 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003731 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003732 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003733
Nate Begeman21158fc2005-09-01 00:19:25 +00003734 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003735 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003736 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003737 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3738 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003739
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003740 if (!LegalOperations ||
3741 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003742 switch (N0.getOpcode()) {
3743 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003744 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003745 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003746 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003747 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003748 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003749 N0.getOperand(3), NotCC);
3750 }
3751 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003752 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003753
Chris Lattner58c227b2007-09-10 21:39:07 +00003754 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003755 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003756 N0.getNode()->hasOneUse() &&
3757 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003758 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003759 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003760 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003761 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003762 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003763 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003764
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003765 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003766 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003767 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003768 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003769 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3770 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003771 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3772 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003773 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003774 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003775 }
3776 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003777 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003778 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003779 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003780 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003781 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3782 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003783 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3784 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003785 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003786 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003787 }
3788 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003789 // fold (xor (and x, y), y) -> (and (not x), y)
3790 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003791 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003792 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003793 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003794 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003795 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003796 }
Bill Wendling35972a92009-01-30 21:14:50 +00003797 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003798 if (N1C && N0.getOpcode() == ISD::XOR) {
3799 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3800 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3801 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003802 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003803 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003804 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003805 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003806 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003807 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003808 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003809 }
3810 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003811 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003812 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003813
Chris Lattner8d6fc202006-05-05 05:51:50 +00003814 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3815 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003816 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003817 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003818 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003819
Chris Lattner098c01e2006-04-08 04:15:24 +00003820 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003821 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003822 SimplifyDemandedBits(SDValue(N, 0)))
3823 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003824
Evan Chengf1005572010-04-28 07:10:39 +00003825 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003826}
3827
Chris Lattner7c709a52007-12-06 07:33:36 +00003828/// visitShiftByConstant - Handle transforms common to the three shifts, when
3829/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003830SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003831 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003832 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003833 return SDValue();
3834
Gabor Greiff304a7a2008-08-28 21:40:38 +00003835 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003836 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003837
Chris Lattner7c709a52007-12-06 07:33:36 +00003838 // We want to pull some binops through shifts, so that we have (and (shift))
3839 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3840 // thing happens with address calculations, so it's important to canonicalize
3841 // it.
3842 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003843
Chris Lattner7c709a52007-12-06 07:33:36 +00003844 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003845 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003846 case ISD::OR:
3847 case ISD::XOR:
3848 HighBitSet = false; // We can only transform sra if the high bit is clear.
3849 break;
3850 case ISD::AND:
3851 HighBitSet = true; // We can only transform sra if the high bit is set.
3852 break;
3853 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003854 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003855 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003856 HighBitSet = false; // We can only transform sra if the high bit is clear.
3857 break;
3858 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003859
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003860 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003861 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003862 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003863
3864 // FIXME: disable this unless the input to the binop is a shift by a constant.
3865 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003866 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003867 // void foo(int *X, int i) { X[i & 1235] = 1; }
3868 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003869 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003870 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003871 BinOpLHSVal->getOpcode() != ISD::SRA &&
3872 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3873 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003874 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003875
Owen Anderson53aa7a92009-08-10 22:56:29 +00003876 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003877
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003878 // If this is a signed shift right, and the high bit is modified by the
3879 // logical operation, do not perform the transformation. The highBitSet
3880 // boolean indicates the value of the high bit of the constant which would
3881 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003882 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003883 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3884 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003885 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003886 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003887
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003888 if (!TLI.isDesirableToCommuteWithShift(LHS))
3889 return SDValue();
3890
Chris Lattner7c709a52007-12-06 07:33:36 +00003891 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003892 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003893 N->getValueType(0),
3894 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003895 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003896
3897 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003898 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003899 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003900 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003901
3902 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003903 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003904}
3905
Adam Nemet67483892014-03-04 23:28:31 +00003906SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3907 assert(N->getOpcode() == ISD::TRUNCATE);
3908 assert(N->getOperand(0).getOpcode() == ISD::AND);
3909
3910 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3911 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3912 SDValue N01 = N->getOperand(0).getOperand(1);
3913
Matt Arsenault985b9de2014-03-17 18:58:01 +00003914 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003915 EVT TruncVT = N->getValueType(0);
3916 SDValue N00 = N->getOperand(0).getOperand(0);
3917 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003918 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003919
3920 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3921 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3922 DAG.getConstant(TruncC, TruncVT));
3923 }
3924 }
3925
3926 return SDValue();
3927}
Adam Nemet7f928f12014-03-07 23:56:30 +00003928
3929SDValue DAGCombiner::visitRotate(SDNode *N) {
3930 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3931 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3932 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3933 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3934 if (NewOp1.getNode())
3935 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3936 N->getOperand(0), NewOp1);
3937 }
3938 return SDValue();
3939}
3940
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003941SDValue DAGCombiner::visitSHL(SDNode *N) {
3942 SDValue N0 = N->getOperand(0);
3943 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003944 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3945 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003946 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003947 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003948
Daniel Sandersa1840d22013-11-11 17:23:41 +00003949 // fold vector ops
3950 if (VT.isVector()) {
3951 SDValue FoldedVOp = SimplifyVBinOp(N);
3952 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003953
3954 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3955 // If setcc produces all-one true value then:
3956 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003957 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00003958 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00003959 SDValue N00 = N0->getOperand(0);
3960 SDValue N01 = N0->getOperand(1);
3961 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003962
Daniel Sanderscbd44c52014-07-10 10:18:12 +00003963 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3964 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3965 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00003966 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3967 if (C.getNode())
3968 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3969 }
3970 } else {
3971 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003972 }
3973 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003974 }
3975
Nate Begeman21158fc2005-09-01 00:19:25 +00003976 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003977 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003978 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003979 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003980 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003981 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003982 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003983 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003984 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003985 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003986 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003987 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003988 // fold (shl undef, x) -> 0
3989 if (N0.getOpcode() == ISD::UNDEF)
3990 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003991 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003992 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003993 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003994 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003995 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003996 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00003997 N1.getOperand(0).getOpcode() == ISD::AND) {
3998 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3999 if (NewOp1.getNode())
4000 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004001 }
4002
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004003 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4004 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004005
4006 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004007 if (N1C && N0.getOpcode() == ISD::SHL) {
4008 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4009 uint64_t c1 = N0C1->getZExtValue();
4010 uint64_t c2 = N1C->getZExtValue();
4011 if (c1 + c2 >= OpSizeInBits)
4012 return DAG.getConstant(0, VT);
4013 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4014 DAG.getConstant(c1 + c2, N1.getValueType()));
4015 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004016 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004017
4018 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4019 // For this to be valid, the second form must not preserve any of the bits
4020 // that are shifted out by the inner shift in the first form. This means
4021 // the outer shift size must be >= the number of bits added by the ext.
4022 // As a corollary, we don't care what kind of ext it is.
4023 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4024 N0.getOpcode() == ISD::ANY_EXTEND ||
4025 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004026 N0.getOperand(0).getOpcode() == ISD::SHL) {
4027 SDValue N0Op0 = N0.getOperand(0);
4028 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4029 uint64_t c1 = N0Op0C1->getZExtValue();
4030 uint64_t c2 = N1C->getZExtValue();
4031 EVT InnerShiftVT = N0Op0.getValueType();
4032 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4033 if (c2 >= OpSizeInBits - InnerShiftSize) {
4034 if (c1 + c2 >= OpSizeInBits)
4035 return DAG.getConstant(0, VT);
4036 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4037 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4038 N0Op0->getOperand(0)),
4039 DAG.getConstant(c1 + c2, N1.getValueType()));
4040 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004041 }
4042 }
4043
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004044 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4045 // Only fold this if the inner zext has no other uses to avoid increasing
4046 // the total number of instructions.
4047 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004048 N0.getOperand(0).getOpcode() == ISD::SRL) {
4049 SDValue N0Op0 = N0.getOperand(0);
4050 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4051 uint64_t c1 = N0Op0C1->getZExtValue();
4052 if (c1 < VT.getScalarSizeInBits()) {
4053 uint64_t c2 = N1C->getZExtValue();
4054 if (c1 == c2) {
4055 SDValue NewOp0 = N0.getOperand(0);
4056 EVT CountVT = NewOp0.getOperand(1).getValueType();
4057 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4058 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004059 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004060 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4061 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004062 }
4063 }
4064 }
4065
Eli Friedman1877ac92011-06-09 22:14:44 +00004066 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4067 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004068 // Only fold this if the inner shift has no other uses -- if it does, folding
4069 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004070 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4071 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4072 uint64_t c1 = N0C1->getZExtValue();
4073 if (c1 < OpSizeInBits) {
4074 uint64_t c2 = N1C->getZExtValue();
4075 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4076 SDValue Shift;
4077 if (c2 > c1) {
4078 Mask = Mask.shl(c2 - c1);
4079 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4080 DAG.getConstant(c2 - c1, N1.getValueType()));
4081 } else {
4082 Mask = Mask.lshr(c1 - c2);
4083 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4084 DAG.getConstant(c1 - c2, N1.getValueType()));
4085 }
4086 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4087 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004088 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004089 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004090 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004091 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004092 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004093 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004094 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004095 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4096 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004097 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004098 HiBitsMask);
4099 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004100
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004101 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004102 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004103 if (NewSHL.getNode())
4104 return NewSHL;
4105 }
4106
Evan Chengf1005572010-04-28 07:10:39 +00004107 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004108}
4109
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004110SDValue DAGCombiner::visitSRA(SDNode *N) {
4111 SDValue N0 = N->getOperand(0);
4112 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004113 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4114 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004115 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004116 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004117
Daniel Sandersa1840d22013-11-11 17:23:41 +00004118 // fold vector ops
4119 if (VT.isVector()) {
4120 SDValue FoldedVOp = SimplifyVBinOp(N);
4121 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004122
4123 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004124 }
4125
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004126 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004127 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004128 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004129 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004130 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004131 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004132 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004133 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004134 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004135 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004136 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004137 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004138 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004139 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004140 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004141 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4142 // sext_inreg.
4143 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004144 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004145 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4146 if (VT.isVector())
4147 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4148 ExtVT, VT.getVectorNumElements());
4149 if ((!LegalOperations ||
4150 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004151 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004152 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004153 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004154
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004155 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004156 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004157 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004158 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004159 if (Sum >= OpSizeInBits)
4160 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004161 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004162 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004163 }
4164 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004165
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004166 // fold (sra (shl X, m), (sub result_size, n))
4167 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004168 // result_size - n != m.
4169 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004170 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004171 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004172 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004173 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4174 if (N01C) {
4175 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004176 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004177 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4178
4179 if (VT.isVector())
4180 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4181
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004182 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004183 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004184
Scott Michelcf0da6c2009-02-17 22:15:04 +00004185 // If the shift is not a no-op (in which case this should be just a sign
4186 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004187 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004188 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004189 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004190 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4191 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004192 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004193
Owen Andersonb2c80da2011-02-25 21:41:48 +00004194 SDValue Amt = DAG.getConstant(ShiftAmt,
4195 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004196 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004197 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004198 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004199 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004200 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004201 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004202 }
4203 }
4204 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004205
Duncan Sands3ed76882009-02-01 18:06:53 +00004206 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004207 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004208 N1.getOperand(0).getOpcode() == ISD::AND) {
4209 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4210 if (NewOp1.getNode())
4211 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004212 }
4213
Matt Arsenault985b9de2014-03-17 18:58:01 +00004214 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004215 // if c1 is equal to the number of bits the trunc removes
4216 if (N0.getOpcode() == ISD::TRUNCATE &&
4217 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4218 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4219 N0.getOperand(0).hasOneUse() &&
4220 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004221 N1C) {
4222 SDValue N0Op0 = N0.getOperand(0);
4223 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4224 unsigned LargeShiftVal = LargeShift->getZExtValue();
4225 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004226
Matt Arsenault985b9de2014-03-17 18:58:01 +00004227 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4228 SDValue Amt =
4229 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4230 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4231 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4232 N0Op0.getOperand(0), Amt);
4233 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4234 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004235 }
4236 }
4237
Scott Michelcf0da6c2009-02-17 22:15:04 +00004238 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004239 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4240 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004241
4242
Nate Begeman21158fc2005-09-01 00:19:25 +00004243 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004244 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004245 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004246
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004247 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004248 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004249 if (NewSRA.getNode())
4250 return NewSRA;
4251 }
4252
Evan Chengf1005572010-04-28 07:10:39 +00004253 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004254}
4255
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004256SDValue DAGCombiner::visitSRL(SDNode *N) {
4257 SDValue N0 = N->getOperand(0);
4258 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004259 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4260 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004261 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004262 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004263
Daniel Sandersa1840d22013-11-11 17:23:41 +00004264 // fold vector ops
4265 if (VT.isVector()) {
4266 SDValue FoldedVOp = SimplifyVBinOp(N);
4267 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004268
4269 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004270 }
4271
Nate Begeman21158fc2005-09-01 00:19:25 +00004272 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004273 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004274 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004275 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004276 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004277 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004278 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004279 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004280 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004281 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004282 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004283 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004284 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004285 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004286 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004287 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004288
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004289 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004290 if (N1C && N0.getOpcode() == ISD::SRL) {
4291 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4292 uint64_t c1 = N01C->getZExtValue();
4293 uint64_t c2 = N1C->getZExtValue();
4294 if (c1 + c2 >= OpSizeInBits)
4295 return DAG.getConstant(0, VT);
4296 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4297 DAG.getConstant(c1 + c2, N1.getValueType()));
4298 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004299 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004300
Dale Johannesencd538af2010-12-17 21:45:49 +00004301 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004302 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4303 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004304 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004305 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004306 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4307 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004308 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4309 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004310 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004311 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004312 if (c1 + OpSizeInBits == InnerShiftSize) {
4313 if (c1 + c2 >= InnerShiftSize)
4314 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004315 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4316 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004317 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004318 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004319 }
4320 }
4321
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004322 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004323 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4324 unsigned BitSize = N0.getScalarValueSizeInBits();
4325 if (BitSize <= 64) {
4326 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4327 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4328 DAG.getConstant(~0ULL >> ShAmt, VT));
4329 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004330 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004331
Michael Liao62ebfd82013-06-21 18:45:27 +00004332 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004333 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4334 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004335 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004336 unsigned BitSize = SmallVT.getScalarSizeInBits();
4337 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004338 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004339
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004340 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004341 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004342 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004343 N0.getOperand(0),
4344 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004345 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004346 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004347 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4348 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4349 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004350 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004351 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004352
Chris Lattner2e33fb42006-10-12 20:23:19 +00004353 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4354 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004355 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004356 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004357 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004358 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004359
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004360 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004361 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004362 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004363 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004364 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004365
Chris Lattner49932492006-04-02 06:11:11 +00004366 // If any of the input bits are KnownOne, then the input couldn't be all
4367 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004368 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004369
Chris Lattner49932492006-04-02 06:11:11 +00004370 // If all of the bits input the to ctlz node are known to be zero, then
4371 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004372 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004373 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004374
Chris Lattner49932492006-04-02 06:11:11 +00004375 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004376 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004377 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004378 // could be set on input to the CTLZ node. If this bit is set, the SRL
4379 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4380 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004381 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004382 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004383
Chris Lattner49932492006-04-02 06:11:11 +00004384 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004385 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004386 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004387 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004388 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004389
Andrew Trickef9de2a2013-05-25 02:42:55 +00004390 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004391 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004392 }
4393 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004394
Duncan Sands3ed76882009-02-01 18:06:53 +00004395 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004396 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004397 N1.getOperand(0).getOpcode() == ISD::AND) {
4398 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4399 if (NewOp1.getNode())
4400 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004401 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004402
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004403 // fold operands of srl based on knowledge that the low bits are not
4404 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004405 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4406 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004407
Evan Chengb175de62009-12-18 21:31:31 +00004408 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004409 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004410 if (NewSRL.getNode())
4411 return NewSRL;
4412 }
4413
Dan Gohman600f62b2010-06-24 14:30:44 +00004414 // Attempt to convert a srl of a load into a narrower zero-extending load.
4415 SDValue NarrowLoad = ReduceLoadWidth(N);
4416 if (NarrowLoad.getNode())
4417 return NarrowLoad;
4418
Evan Chengb175de62009-12-18 21:31:31 +00004419 // Here is a common situation. We want to optimize:
4420 //
4421 // %a = ...
4422 // %b = and i32 %a, 2
4423 // %c = srl i32 %b, 1
4424 // brcond i32 %c ...
4425 //
4426 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004427 //
Evan Chengb175de62009-12-18 21:31:31 +00004428 // %a = ...
4429 // %b = and %a, 2
4430 // %c = setcc eq %b, 0
4431 // brcond %c ...
4432 //
4433 // However when after the source operand of SRL is optimized into AND, the SRL
4434 // itself may not be optimized further. Look for it and add the BRCOND into
4435 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004436 if (N->hasOneUse()) {
4437 SDNode *Use = *N->use_begin();
4438 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004439 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004440 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4441 // Also look pass the truncate.
4442 Use = *Use->use_begin();
4443 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004444 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004445 }
4446 }
Evan Chengb175de62009-12-18 21:31:31 +00004447
Evan Chengf1005572010-04-28 07:10:39 +00004448 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004449}
4450
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004451SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4452 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004453 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004454
4455 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004456 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004457 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004458 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004459}
4460
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004461SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4462 SDValue N0 = N->getOperand(0);
4463 EVT VT = N->getValueType(0);
4464
4465 // fold (ctlz_zero_undef c1) -> c2
4466 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004467 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004468 return SDValue();
4469}
4470
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004471SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4472 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004473 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004474
Nate Begeman21158fc2005-09-01 00:19:25 +00004475 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004476 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004477 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004478 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004479}
4480
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004481SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4482 SDValue N0 = N->getOperand(0);
4483 EVT VT = N->getValueType(0);
4484
4485 // fold (cttz_zero_undef c1) -> c2
4486 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004487 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004488 return SDValue();
4489}
4490
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004491SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4492 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004493 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004494
Nate Begeman21158fc2005-09-01 00:19:25 +00004495 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004496 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004497 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004498 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004499}
4500
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004501SDValue DAGCombiner::visitSELECT(SDNode *N) {
4502 SDValue N0 = N->getOperand(0);
4503 SDValue N1 = N->getOperand(1);
4504 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004505 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4506 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4507 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004508 EVT VT = N->getValueType(0);
4509 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004510
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004511 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004512 if (N1 == N2)
4513 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004514 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004515 if (N0C && !N0C->isNullValue())
4516 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004517 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004518 if (N0C && N0C->isNullValue())
4519 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004520 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004521 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004522 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004523 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004524 // We can't do this reliably if integer based booleans have different contents
4525 // to floating point based booleans. This is because we can't tell whether we
4526 // have an integer-based boolean or a floating-point-based boolean unless we
4527 // can find the SETCC that produced it and inspect its operands. This is
4528 // fairly easy if C is the SETCC node, but it can potentially be
4529 // undiscoverable (or not reasonably discoverable). For example, it could be
4530 // in another basic block or it could require searching a complicated
4531 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004532 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004533 (VT0 == MVT::i1 || (VT0.isInteger() &&
4534 TLI.getBooleanContents(false, false) ==
4535 TLI.getBooleanContents(false, true) &&
4536 TLI.getBooleanContents(false, false) ==
4537 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004538 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004539 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004540 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004541 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004542 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004543 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004544 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004545 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004546 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004547 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4548 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004549 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004550 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004551 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004552 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004553 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004554 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004555 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004556 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004557 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004558 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004559 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004560 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004561 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004562 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004563 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004564 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004565 // fold (select X, X, Y) -> (or X, Y)
4566 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004567 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004568 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004569 // fold (select X, Y, X) -> (and X, Y)
4570 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004571 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004572 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004573
Chris Lattner6c14c352005-10-18 06:04:22 +00004574 // If we can fold this based on the true/false value, do so.
4575 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004576 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004577
Nate Begemanc760f802005-09-19 22:34:01 +00004578 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004579 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004580 if ((!LegalOperations &&
4581 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4582 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004583 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004584 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004585 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004586 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004587 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004588
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004589 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004590}
4591
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004592static
4593std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4594 SDLoc DL(N);
4595 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004596 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004597
4598 // Split the inputs.
4599 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004600 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4601 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004602
4603 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4604 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4605
4606 return std::make_pair(Lo, Hi);
4607}
4608
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004609// This function assumes all the vselect's arguments are CONCAT_VECTOR
4610// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4611static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4612 SDLoc dl(N);
4613 SDValue Cond = N->getOperand(0);
4614 SDValue LHS = N->getOperand(1);
4615 SDValue RHS = N->getOperand(2);
4616 MVT VT = N->getSimpleValueType(0);
4617 int NumElems = VT.getVectorNumElements();
4618 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4619 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4620 Cond.getOpcode() == ISD::BUILD_VECTOR);
4621
4622 // We're sure we have an even number of elements due to the
4623 // concat_vectors we have as arguments to vselect.
4624 // Skip BV elements until we find one that's not an UNDEF
4625 // After we find an UNDEF element, keep looping until we get to half the
4626 // length of the BV and see if all the non-undef nodes are the same.
4627 ConstantSDNode *BottomHalf = nullptr;
4628 for (int i = 0; i < NumElems / 2; ++i) {
4629 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4630 continue;
4631
4632 if (BottomHalf == nullptr)
4633 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4634 else if (Cond->getOperand(i).getNode() != BottomHalf)
4635 return SDValue();
4636 }
4637
4638 // Do the same for the second half of the BuildVector
4639 ConstantSDNode *TopHalf = nullptr;
4640 for (int i = NumElems / 2; i < NumElems; ++i) {
4641 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4642 continue;
4643
4644 if (TopHalf == nullptr)
4645 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4646 else if (Cond->getOperand(i).getNode() != TopHalf)
4647 return SDValue();
4648 }
4649
4650 assert(TopHalf && BottomHalf &&
4651 "One half of the selector was all UNDEFs and the other was all the "
4652 "same value. This should have been addressed before this function.");
4653 return DAG.getNode(
4654 ISD::CONCAT_VECTORS, dl, VT,
4655 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4656 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4657}
4658
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004659SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4660 SDValue N0 = N->getOperand(0);
4661 SDValue N1 = N->getOperand(1);
4662 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004663 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004664
4665 // Canonicalize integer abs.
4666 // vselect (setg[te] X, 0), X, -X ->
4667 // vselect (setgt X, -1), X, -X ->
4668 // vselect (setl[te] X, 0), -X, X ->
4669 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4670 if (N0.getOpcode() == ISD::SETCC) {
4671 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4672 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4673 bool isAbs = false;
4674 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4675
4676 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4677 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4678 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4679 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4680 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4681 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4682 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4683
4684 if (isAbs) {
4685 EVT VT = LHS.getValueType();
4686 SDValue Shift = DAG.getNode(
4687 ISD::SRA, DL, VT, LHS,
4688 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4689 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004690 AddToWorklist(Shift.getNode());
4691 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004692 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4693 }
4694 }
4695
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004696 // If the VSELECT result requires splitting and the mask is provided by a
4697 // SETCC, then split both nodes and its operands before legalization. This
4698 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4699 // and enables future optimizations (e.g. min/max pattern matching on X86).
4700 if (N0.getOpcode() == ISD::SETCC) {
4701 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004702
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004703 // Check if any splitting is required.
4704 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4705 TargetLowering::TypeSplitVector)
4706 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004707
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004708 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004709 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4710 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4711 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004712
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004713 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4714 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004715
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004716 // Add the new VSELECT nodes to the work list in case they need to be split
4717 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004718 AddToWorklist(Lo.getNode());
4719 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004720
4721 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004722 }
4723
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004724 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4725 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4726 return N1;
4727 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4728 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4729 return N2;
4730
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004731 // The ConvertSelectToConcatVector function is assuming both the above
4732 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4733 // and addressed.
4734 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4735 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4736 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4737 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4738 if (CV.getNode())
4739 return CV;
4740 }
4741
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004742 return SDValue();
4743}
4744
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004745SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4746 SDValue N0 = N->getOperand(0);
4747 SDValue N1 = N->getOperand(1);
4748 SDValue N2 = N->getOperand(2);
4749 SDValue N3 = N->getOperand(3);
4750 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004751 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004752
Nate Begemanc760f802005-09-19 22:34:01 +00004753 // fold select_cc lhs, rhs, x, x, cc -> x
4754 if (N2 == N3)
4755 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004756
Chris Lattner8b68dec2006-09-20 06:19:26 +00004757 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004758 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004759 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004760 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004761 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004762
Stephen Lin605207f2013-06-15 04:03:33 +00004763 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4764 if (!SCCC->isNullValue())
4765 return N2; // cond always true -> true val
4766 else
4767 return N3; // cond always false -> false val
4768 }
4769
4770 // Fold to a simpler select_cc
4771 if (SCC.getOpcode() == ISD::SETCC)
4772 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4773 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4774 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004775 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004776
Chris Lattner6c14c352005-10-18 06:04:22 +00004777 // If we can fold this based on the true/false value, do so.
4778 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004779 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004780
Nate Begemanc760f802005-09-19 22:34:01 +00004781 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004782 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004783}
4784
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004785SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004786 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004787 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004788 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004789}
4790
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004791// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4792// dag node into a ConstantSDNode or a build_vector of constants.
4793// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004794// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004795// Vector extends are not folded if operations are legal; this is to
4796// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004797static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4798 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004799 bool LegalOperations) {
4800 unsigned Opcode = N->getOpcode();
4801 SDValue N0 = N->getOperand(0);
4802 EVT VT = N->getValueType(0);
4803
4804 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4805 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4806
4807 // fold (sext c1) -> c1
4808 // fold (zext c1) -> c1
4809 // fold (aext c1) -> c1
4810 if (isa<ConstantSDNode>(N0))
4811 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4812
4813 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4814 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4815 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004816 EVT SVT = VT.getScalarType();
4817 if (!(VT.isVector() &&
4818 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004819 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004820 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004821
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004822 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004823 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004824 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4825 unsigned ShAmt = VTBits - EVTBits;
4826 SmallVector<SDValue, 8> Elts;
4827 unsigned NumElts = N0->getNumOperands();
4828 SDLoc DL(N);
4829
4830 for (unsigned i=0; i != NumElts; ++i) {
4831 SDValue Op = N0->getOperand(i);
4832 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004833 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004834 continue;
4835 }
4836
4837 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4838 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4839 if (Opcode == ISD::SIGN_EXTEND)
4840 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004841 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004842 else
4843 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004844 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004845 }
4846
Craig Topper48d114b2014-04-26 18:35:24 +00004847 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004848}
4849
Evan Chenge106e2f2007-10-29 19:58:20 +00004850// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004851// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004852// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004853// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004854static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004855 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004856 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004857 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004858 bool HasCopyToRegUses = false;
4859 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004860 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4861 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004862 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004863 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004864 if (User == N)
4865 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004866 if (UI.getUse().getResNo() != N0.getResNo())
4867 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004868 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004869 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004870 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4871 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4872 // Sign bits will be lost after a zext.
4873 return false;
4874 bool Add = false;
4875 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004876 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004877 if (UseOp == N0)
4878 continue;
4879 if (!isa<ConstantSDNode>(UseOp))
4880 return false;
4881 Add = true;
4882 }
4883 if (Add)
4884 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004885 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004886 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004887 // If truncates aren't free and there are users we can't
4888 // extend, it isn't worthwhile.
4889 if (!isTruncFree)
4890 return false;
4891 // Remember if this value is live-out.
4892 if (User->getOpcode() == ISD::CopyToReg)
4893 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004894 }
4895
4896 if (HasCopyToRegUses) {
4897 bool BothLiveOut = false;
4898 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4899 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004900 SDUse &Use = UI.getUse();
4901 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4902 BothLiveOut = true;
4903 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004904 }
4905 }
4906 if (BothLiveOut)
4907 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004908 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004909 return ExtendNodes.size();
4910 }
4911 return true;
4912}
4913
Craig Toppere0b71182013-07-13 07:43:40 +00004914void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004915 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004916 ISD::NodeType ExtType) {
4917 // Extend SetCC uses if necessary.
4918 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4919 SDNode *SetCC = SetCCs[i];
4920 SmallVector<SDValue, 4> Ops;
4921
4922 for (unsigned j = 0; j != 2; ++j) {
4923 SDValue SOp = SetCC->getOperand(j);
4924 if (SOp == Trunc)
4925 Ops.push_back(ExtLoad);
4926 else
4927 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4928 }
4929
4930 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00004931 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004932 }
4933}
4934
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004935SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4936 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004937 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004938
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004939 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4940 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004941 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004942
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004943 // fold (sext (sext x)) -> (sext x)
4944 // fold (sext (aext x)) -> (sext x)
4945 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004946 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004947 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004948
Chris Lattnerfce448f2007-02-26 03:13:59 +00004949 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004950 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4951 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004952 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4953 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004954 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4955 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004956 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004957 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004958 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004959 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004961 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004962
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004963 // See if the value being truncated is already sign extended. If so, just
4964 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004965 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004966 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4967 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4968 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004969 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004970
Chris Lattnerfce448f2007-02-26 03:13:59 +00004971 if (OpBits == DestBits) {
4972 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4973 // bits, it is already ready.
4974 if (NumSignBits > DestBits-MidBits)
4975 return Op;
4976 } else if (OpBits < DestBits) {
4977 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4978 // bits, just sext from i32.
4979 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004980 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004981 } else {
4982 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4983 // bits, just truncate to i32.
4984 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004985 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004986 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004987
Chris Lattnerfce448f2007-02-26 03:13:59 +00004988 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004989 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4990 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004991 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004992 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004993 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004994 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4995 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004996 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004997 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004998 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004999
Evan Chengbce7c472005-12-14 02:19:23 +00005000 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005001 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005002 // on vectors in one instruction. We only perform this transformation on
5003 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005004 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005005 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005006 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005007 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005008 bool DoXform = true;
5009 SmallVector<SDNode*, 4> SetCCs;
5010 if (!N0.hasOneUse())
5011 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5012 if (DoXform) {
5013 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005014 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005015 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005016 LN0->getBasePtr(), N0.getValueType(),
5017 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005018 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005019 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005020 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005021 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005022 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005023 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005024 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005025 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005026 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005027
5028 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5029 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005030 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5031 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005032 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005033 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005034 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005035 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005036 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005037 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005038 LN0->getBasePtr(), MemVT,
5039 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005040 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005041 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005042 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005043 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005044 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005045 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005046 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005047 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005048
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005049 // fold (sext (and/or/xor (load x), cst)) ->
5050 // (and/or/xor (sextload x), (sext cst))
5051 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5052 N0.getOpcode() == ISD::XOR) &&
5053 isa<LoadSDNode>(N0.getOperand(0)) &&
5054 N0.getOperand(1).getOpcode() == ISD::Constant &&
5055 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5056 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5057 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005058 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005059 bool DoXform = true;
5060 SmallVector<SDNode*, 4> SetCCs;
5061 if (!N0.hasOneUse())
5062 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5063 SetCCs, TLI);
5064 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005065 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005066 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005067 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005068 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005069 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5070 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005071 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005072 ExtLoad, DAG.getConstant(Mask, VT));
5073 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005074 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005075 N0.getOperand(0).getValueType(), ExtLoad);
5076 CombineTo(N, And);
5077 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005078 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005079 ISD::SIGN_EXTEND);
5080 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5081 }
5082 }
5083 }
5084
Chris Lattner65786b02007-04-11 05:32:27 +00005085 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005086 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005087 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005088 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005089 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005090 TLI.getBooleanContents(N0VT) ==
5091 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005092 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5093 // of the same size as the compared operands. Only optimize sext(setcc())
5094 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005095 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005096
5097 // We know that the # elements of the results is the same as the
5098 // # elements of the compare (and the # elements of the compare result
5099 // for that matter). Check to see that they are the same size. If so,
5100 // we know that the element size of the sext'd result matches the
5101 // element size of the compare operands.
5102 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005103 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005104 N0.getOperand(1),
5105 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005106
Dan Gohmane82c25e2010-04-30 17:19:19 +00005107 // If the desired elements are smaller or larger than the source
5108 // elements we can use a matching integer vector type and then
5109 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005110 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005111 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005112 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005113 N0.getOperand(0), N0.getOperand(1),
5114 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005115 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005116 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005117 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005118
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005119 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005120 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005121 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005122 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005123 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005124 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005125 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005126 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005127 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005128
5129 if (!VT.isVector()) {
5130 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5131 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5132 SDLoc DL(N);
5133 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5134 SDValue SetCC = DAG.getSetCC(DL,
5135 SetCCVT,
5136 N0.getOperand(0), N0.getOperand(1), CC);
5137 EVT SelectVT = getSetCCResultType(VT);
5138 return DAG.getSelect(DL, VT,
5139 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5140 NegOne, DAG.getConstant(0, VT));
5141
5142 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005143 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005145
Dan Gohman3eb10f72008-04-28 16:58:24 +00005146 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005147 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005148 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005149 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005150
Evan Chengf1005572010-04-28 07:10:39 +00005151 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005152}
5153
Rafael Espindola8f62b322012-04-09 16:06:03 +00005154// isTruncateOf - If N is a truncate of some other value, return true, record
5155// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5156// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005157// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005158static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5159 APInt &KnownZero) {
5160 APInt KnownOne;
5161 if (N->getOpcode() == ISD::TRUNCATE) {
5162 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005163 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005164 return true;
5165 }
5166
5167 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5168 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5169 return false;
5170
5171 SDValue Op0 = N->getOperand(0);
5172 SDValue Op1 = N->getOperand(1);
5173 assert(Op0.getValueType() == Op1.getValueType());
5174
5175 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5176 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005177 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005178 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005179 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005180 Op = Op0;
5181 else
5182 return false;
5183
Jay Foada0653a32014-05-14 21:14:37 +00005184 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005185
5186 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5187 return false;
5188
5189 return true;
5190}
5191
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005192SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5193 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005194 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005195
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005196 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5197 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005198 return SDValue(Res, 0);
5199
Nate Begeman21158fc2005-09-01 00:19:25 +00005200 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005201 // fold (zext (aext x)) -> (zext x)
5202 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005203 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005204 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005205
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005206 // fold (zext (truncate x)) -> (zext x) or
5207 // (zext (truncate x)) -> (truncate x)
5208 // This is valid when the truncated bits of x are already zero.
5209 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005210 SDValue Op;
5211 APInt KnownZero;
5212 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5213 APInt TruncatedBits =
5214 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5215 APInt(Op.getValueSizeInBits(), 0) :
5216 APInt::getBitsSet(Op.getValueSizeInBits(),
5217 N0.getValueSizeInBits(),
5218 std::min(Op.getValueSizeInBits(),
5219 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005220 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005221 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005222 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005223 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005224 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005225
5226 return Op;
5227 }
5228 }
5229
Evan Cheng464dc9b2007-03-22 01:54:19 +00005230 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5231 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005232 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005233 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5234 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005235 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5236 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005237 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005238 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005239 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005240 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005241 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005242 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005243 }
5244
Chris Lattnera31f0a62006-09-21 06:00:20 +00005245 // fold (zext (truncate x)) -> (and x, mask)
5246 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005247 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005248
5249 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5250 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5251 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5252 if (NarrowLoad.getNode()) {
5253 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5254 if (NarrowLoad.getNode() != N0.getNode()) {
5255 CombineTo(N0.getNode(), NarrowLoad);
5256 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005257 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005258 }
5259 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5260 }
5261
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005262 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005263 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005264 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005265 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005266 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005267 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005268 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005269 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005270 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005271 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005272 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005273
Dan Gohmanad3e5492009-04-08 00:15:30 +00005274 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5275 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005276 if (N0.getOpcode() == ISD::AND &&
5277 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005278 N0.getOperand(1).getOpcode() == ISD::Constant &&
5279 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5280 N0.getValueType()) ||
5281 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005282 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005283 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005284 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005285 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005286 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005287 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005288 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005289 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005290 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005291 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005292 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005293
Evan Chengbce7c472005-12-14 02:19:23 +00005294 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005295 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005296 // on vectors in one instruction. We only perform this transformation on
5297 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005298 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005299 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005300 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005301 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005302 bool DoXform = true;
5303 SmallVector<SDNode*, 4> SetCCs;
5304 if (!N0.hasOneUse())
5305 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5306 if (DoXform) {
5307 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005308 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005309 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005310 LN0->getBasePtr(), N0.getValueType(),
5311 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005312 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005313 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005314 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005315 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005316
Andrew Trickef9de2a2013-05-25 02:42:55 +00005317 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005318 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005319 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005320 }
Evan Chengbce7c472005-12-14 02:19:23 +00005321 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005322
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005323 // fold (zext (and/or/xor (load x), cst)) ->
5324 // (and/or/xor (zextload x), (zext cst))
5325 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5326 N0.getOpcode() == ISD::XOR) &&
5327 isa<LoadSDNode>(N0.getOperand(0)) &&
5328 N0.getOperand(1).getOpcode() == ISD::Constant &&
5329 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5330 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5331 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005332 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005333 bool DoXform = true;
5334 SmallVector<SDNode*, 4> SetCCs;
5335 if (!N0.hasOneUse())
5336 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5337 SetCCs, TLI);
5338 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005339 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005340 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005341 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005342 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005343 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5344 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005345 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005346 ExtLoad, DAG.getConstant(Mask, VT));
5347 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005348 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005349 N0.getOperand(0).getValueType(), ExtLoad);
5350 CombineTo(N, And);
5351 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005352 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005353 ISD::ZERO_EXTEND);
5354 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5355 }
5356 }
5357 }
5358
Chris Lattner7dac1082005-12-14 19:05:06 +00005359 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5360 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005361 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5362 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005363 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005364 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005365 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005366 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005367 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005368 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005369 LN0->getBasePtr(), MemVT,
5370 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005371 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005372 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005373 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005374 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005375 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005376 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005377 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005378 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005379
Chris Lattner65786b02007-04-11 05:32:27 +00005380 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005381 if (!LegalOperations && VT.isVector() &&
5382 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005383 EVT N0VT = N0.getOperand(0).getValueType();
5384 if (getSetCCResultType(N0VT) == N0.getValueType())
5385 return SDValue();
5386
Evan Chengabd0ad52010-05-19 01:08:17 +00005387 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5388 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005389 EVT EltVT = VT.getVectorElementType();
5390 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5391 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005392 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005393 // We know that the # elements of the results is the same as the
5394 // # elements of the compare (and the # elements of the compare result
5395 // for that matter). Check to see that they are the same size. If so,
5396 // we know that the element size of the sext'd result matches the
5397 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005398 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5399 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005400 N0.getOperand(1),
5401 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005402 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005403 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005404
5405 // If the desired elements are smaller or larger than the source
5406 // elements we can use a matching integer vector type and then
5407 // truncate/sign extend
5408 EVT MatchingElementType =
5409 EVT::getIntegerVT(*DAG.getContext(),
5410 N0VT.getScalarType().getSizeInBits());
5411 EVT MatchingVectorType =
5412 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5413 N0VT.getVectorNumElements());
5414 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005415 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005416 N0.getOperand(1),
5417 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005418 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5419 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005420 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005421 }
5422
5423 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005424 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005425 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005426 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005427 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005428 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005429 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005430
Evan Cheng852c4862009-12-15 03:00:32 +00005431 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005432 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005433 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005434 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5435 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005436 SDValue ShAmt = N0.getOperand(1);
5437 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005438 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005439 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005440 // If the original shl may be shifting out bits, do not perform this
5441 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005442 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5443 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5444 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005445 return SDValue();
5446 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005447
Andrew Trickef9de2a2013-05-25 02:42:55 +00005448 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005449
5450 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005451 if (VT.getSizeInBits() >= 256)
5452 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005453
Chris Lattnere95d1952011-02-13 19:09:16 +00005454 return DAG.getNode(N0.getOpcode(), DL, VT,
5455 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5456 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005457 }
5458
Evan Chengf1005572010-04-28 07:10:39 +00005459 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005460}
5461
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005462SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5463 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005464 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005465
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005466 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5467 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005468 return SDValue(Res, 0);
5469
Chris Lattner812646a2006-05-05 05:58:59 +00005470 // fold (aext (aext x)) -> (aext x)
5471 // fold (aext (zext x)) -> (zext x)
5472 // fold (aext (sext x)) -> (sext x)
5473 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5474 N0.getOpcode() == ISD::ZERO_EXTEND ||
5475 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005476 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005477
Evan Cheng464dc9b2007-03-22 01:54:19 +00005478 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5479 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5480 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005481 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5482 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005483 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5484 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005485 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005486 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005487 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005488 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005489 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005490 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005491 }
5492
Chris Lattner8746e2c2006-09-20 06:29:17 +00005493 // fold (aext (truncate x))
5494 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005495 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005496 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005497 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005498 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005499 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5500 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005501 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005502
Dan Gohmanad3e5492009-04-08 00:15:30 +00005503 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5504 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005505 if (N0.getOpcode() == ISD::AND &&
5506 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005507 N0.getOperand(1).getOpcode() == ISD::Constant &&
5508 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5509 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005510 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005511 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005512 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005513 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005514 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005515 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005516 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005517 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005518 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005519 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005520 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005521
Chris Lattner812646a2006-05-05 05:58:59 +00005522 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005523 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005524 // on vectors in one instruction. We only perform this transformation on
5525 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005526 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005527 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005528 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005529 bool DoXform = true;
5530 SmallVector<SDNode*, 4> SetCCs;
5531 if (!N0.hasOneUse())
5532 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5533 if (DoXform) {
5534 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005535 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005536 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005537 LN0->getBasePtr(), N0.getValueType(),
5538 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005539 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005540 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005541 N0.getValueType(), ExtLoad);
5542 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005543 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005544 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005545 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5546 }
Chris Lattner812646a2006-05-05 05:58:59 +00005547 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005548
Chris Lattner812646a2006-05-05 05:58:59 +00005549 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5550 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5551 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005552 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005553 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005554 N0.hasOneUse()) {
5555 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005556 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005557 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005558 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5559 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5560 VT, LN0->getChain(), LN0->getBasePtr(),
5561 MemVT, LN0->getMemOperand());
5562 CombineTo(N, ExtLoad);
5563 CombineTo(N0.getNode(),
5564 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5565 N0.getValueType(), ExtLoad),
5566 ExtLoad.getValue(1));
5567 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5568 }
Chris Lattner812646a2006-05-05 05:58:59 +00005569 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005570
Chris Lattner65786b02007-04-11 05:32:27 +00005571 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005572 // For vectors:
5573 // aext(setcc) -> vsetcc
5574 // aext(setcc) -> truncate(vsetcc)
5575 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005576 // Only do this before legalize for now.
5577 if (VT.isVector() && !LegalOperations) {
5578 EVT N0VT = N0.getOperand(0).getValueType();
5579 // We know that the # elements of the results is the same as the
5580 // # elements of the compare (and the # elements of the compare result
5581 // for that matter). Check to see that they are the same size. If so,
5582 // we know that the element size of the sext'd result matches the
5583 // element size of the compare operands.
5584 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005585 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005586 N0.getOperand(1),
5587 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005588 // If the desired elements are smaller or larger than the source
5589 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005590 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005591 else {
Hao Liuc636d152014-04-22 09:57:06 +00005592 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005593 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005594 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005595 N0.getOperand(1),
5596 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005597 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005598 }
5599 }
5600
5601 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005602 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005603 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005604 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005605 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005606 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005607 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005608 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005609
Evan Chengf1005572010-04-28 07:10:39 +00005610 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005611}
5612
Chris Lattner5e6fe052007-10-13 06:35:54 +00005613/// GetDemandedBits - See if the specified operand can be simplified with the
5614/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005615/// simpler operand, otherwise return a null SDValue.
5616SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005617 switch (V.getOpcode()) {
5618 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005619 case ISD::Constant: {
5620 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005621 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005622 const APInt &CVal = CV->getAPIntValue();
5623 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005624 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005625 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005626 break;
5627 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005628 case ISD::OR:
5629 case ISD::XOR:
5630 // If the LHS or RHS don't contribute bits to the or, drop them.
5631 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5632 return V.getOperand(1);
5633 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5634 return V.getOperand(0);
5635 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005636 case ISD::SRL:
5637 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005638 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005639 break;
5640 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5641 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005642 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005643
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005644 // Watch out for shift count overflow though.
5645 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005646 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005647 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005648 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005649 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005650 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005651 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005652 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005653 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005654}
5655
Evan Cheng464dc9b2007-03-22 01:54:19 +00005656/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5657/// bits and then truncated to a narrower type and where N is a multiple
5658/// of number of bits of the narrower type, transform it to a narrower load
5659/// from address + N / num of bits of new type. If the result is to be
5660/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005661SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005662 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005663
Evan Cheng464dc9b2007-03-22 01:54:19 +00005664 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005665 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005666 EVT VT = N->getValueType(0);
5667 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005668
Dan Gohman550c9af2008-08-14 20:04:46 +00005669 // This transformation isn't valid for vector loads.
5670 if (VT.isVector())
5671 return SDValue();
5672
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005673 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005674 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005675 if (Opc == ISD::SIGN_EXTEND_INREG) {
5676 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005677 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005678 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005679 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005680 ExtType = ISD::ZEXTLOAD;
5681 N0 = SDValue(N, 0);
5682 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5683 if (!N01) return SDValue();
5684 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5685 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005686 }
Richard Osborne272e0842011-01-31 17:41:44 +00005687 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5688 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005689
Owen Anderson53aa7a92009-08-10 22:56:29 +00005690 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005691
Chris Lattner9a499e92010-12-22 08:01:44 +00005692 // Do not generate loads of non-round integer types since these can
5693 // be expensive (and would be wrong if the type is not byte sized).
5694 if (!ExtVT.isRound())
5695 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005696
Evan Cheng464dc9b2007-03-22 01:54:19 +00005697 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005698 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005699 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005700 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005701 // Is the shift amount a multiple of size of VT?
5702 if ((ShAmt & (EVTBits-1)) == 0) {
5703 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005704 // Is the load width a multiple of size of VT?
5705 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005706 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005707 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005708
Chris Lattnercafc1e62010-12-22 08:02:57 +00005709 // At this point, we must have a load or else we can't do the transform.
5710 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005711
Chandler Carruthb27041c2012-12-11 00:36:57 +00005712 // Because a SRL must be assumed to *need* to zero-extend the high bits
5713 // (as opposed to anyext the high bits), we can't combine the zextload
5714 // lowering of SRL and an sextload.
5715 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5716 return SDValue();
5717
Chris Lattnera2050552010-10-01 05:36:09 +00005718 // If the shift amount is larger than the input type then we're not
5719 // accessing any of the loaded bytes. If the load was a zextload/extload
5720 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005721 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005722 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005723 }
5724 }
5725
Dan Gohman68fb0042010-11-03 01:47:46 +00005726 // If the load is shifted left (and the result isn't shifted back right),
5727 // we can fold the truncate through the shift.
5728 unsigned ShLeftAmt = 0;
5729 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005730 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005731 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5732 ShLeftAmt = N01->getZExtValue();
5733 N0 = N0.getOperand(0);
5734 }
5735 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005736
Chris Lattner222374d2010-12-22 07:36:50 +00005737 // If we haven't found a load, we can't narrow it. Don't transform one with
5738 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005739 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5740 return SDValue();
5741
5742 // Don't change the width of a volatile load.
5743 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5744 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005745 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005746
Chris Lattner9a499e92010-12-22 08:01:44 +00005747 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005748 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005749 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005750
Bill Schmidtd006c692013-01-14 22:04:38 +00005751 // For the transform to be legal, the load must produce only two values
5752 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005753 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005754 // transformation is not equivalent, and the downstream logic to replace
5755 // uses gets things wrong.
5756 if (LN0->getNumValues() > 2)
5757 return SDValue();
5758
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005759 // If the load that we're shrinking is an extload and we're not just
5760 // discarding the extension we can't simply shrink the load. Bail.
5761 // TODO: It would be possible to merge the extensions in some cases.
5762 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5763 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5764 return SDValue();
5765
Chris Lattner222374d2010-12-22 07:36:50 +00005766 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005767
Evan Cheng4c6f9172012-06-26 01:19:33 +00005768 if (PtrType == MVT::Untyped || PtrType.isExtended())
5769 // It's not possible to generate a constant of extended or untyped type.
5770 return SDValue();
5771
Chris Lattner222374d2010-12-22 07:36:50 +00005772 // For big endian targets, we need to adjust the offset to the pointer to
5773 // load the correct bytes.
5774 if (TLI.isBigEndian()) {
5775 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5776 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5777 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005778 }
5779
Chris Lattner222374d2010-12-22 07:36:50 +00005780 uint64_t PtrOff = ShAmt / 8;
5781 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005782 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005783 PtrType, LN0->getBasePtr(),
5784 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005785 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00005786
Chris Lattner9a499e92010-12-22 08:01:44 +00005787 SDValue Load;
5788 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005789 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005790 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005791 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005792 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005793 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005794 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005795 LN0->getPointerInfo().getWithOffset(PtrOff),
5796 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005797 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005798
5799 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005800 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005801 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005802
5803 // Shift the result left, if we've swallowed a left shift.
5804 SDValue Result = Load;
5805 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005806 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005807 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5808 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005809 // If the shift amount is as large as the result size (but, presumably,
5810 // no larger than the source) then the useful bits of the result are
5811 // zero; we can't simply return the shortened shift, because the result
5812 // of that operation is undefined.
5813 if (ShLeftAmt >= VT.getSizeInBits())
5814 Result = DAG.getConstant(0, VT);
5815 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005816 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005817 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005818 }
5819
5820 // Return the new loaded value.
5821 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005822}
5823
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005824SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5825 SDValue N0 = N->getOperand(0);
5826 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005827 EVT VT = N->getValueType(0);
5828 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005829 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005830 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005831
Nate Begeman21158fc2005-09-01 00:19:25 +00005832 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005833 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005834 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005835
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005836 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005837 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005838 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005839
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005840 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5841 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005842 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005843 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005844 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005845
Dan Gohman345d63c2008-07-31 00:50:31 +00005846 // fold (sext_in_reg (sext x)) -> (sext x)
5847 // fold (sext_in_reg (aext x)) -> (sext x)
5848 // if x is small enough.
5849 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5850 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005851 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5852 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005853 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005854 }
5855
Chris Lattner9ad59152007-04-17 19:03:21 +00005856 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005857 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005858 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005859
Chris Lattner9ad59152007-04-17 19:03:21 +00005860 // fold operands of sext_in_reg based on knowledge that the top bits are not
5861 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005862 if (SimplifyDemandedBits(SDValue(N, 0)))
5863 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005864
Evan Cheng464dc9b2007-03-22 01:54:19 +00005865 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5866 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005867 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005868 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005869 return NarrowLoad;
5870
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005871 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005872 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005873 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5874 if (N0.getOpcode() == ISD::SRL) {
5875 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005876 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005877 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005878 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005879 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005880 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005881 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005882 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005883 }
5884 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005885
Nate Begeman02b23c62005-10-13 03:11:28 +00005886 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005887 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005888 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005889 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005890 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005891 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005892 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005893 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005894 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005895 LN0->getBasePtr(), EVT,
5896 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005897 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005898 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005899 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005900 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005901 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005902 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005903 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005904 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005905 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005906 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005907 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005908 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005909 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005910 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005911 LN0->getBasePtr(), EVT,
5912 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005913 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005914 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005915 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005916 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005917
5918 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5919 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5920 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5921 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005922 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005923 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005924 BSwap, N1);
5925 }
5926
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005927 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5928 // into a build_vector.
5929 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5930 SmallVector<SDValue, 8> Elts;
5931 unsigned NumElts = N0->getNumOperands();
5932 unsigned ShAmt = VTBits - EVTBits;
5933
5934 for (unsigned i = 0; i != NumElts; ++i) {
5935 SDValue Op = N0->getOperand(i);
5936 if (Op->getOpcode() == ISD::UNDEF) {
5937 Elts.push_back(Op);
5938 continue;
5939 }
5940
5941 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005942 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5943 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005944 Op.getValueType()));
5945 }
5946
Craig Topper48d114b2014-04-26 18:35:24 +00005947 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005948 }
5949
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005950 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005951}
5952
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005953SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5954 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005955 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005956 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005957
5958 // noop truncate
5959 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005960 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005961 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005962 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005963 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005964 // fold (truncate (truncate x)) -> (truncate x)
5965 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005966 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005967 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005968 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5969 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005970 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005971 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005972 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005973 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005974 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005975 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005976 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005977 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005978 // if the source and dest are the same type, we can drop both the extend
5979 // and the truncate.
5980 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005981 }
Evan Chengd63baea2007-03-21 20:14:05 +00005982
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005983 // Fold extract-and-trunc into a narrow extract. For example:
5984 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5985 // i32 y = TRUNCATE(i64 x)
5986 // -- becomes --
5987 // v16i8 b = BITCAST (v2i64 val)
5988 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5989 //
5990 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005991 // creates this pattern) and before operation legalization after which
5992 // we need to be more careful about the vector instructions that we generate.
5993 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005994 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005995
5996 EVT VecTy = N0.getOperand(0).getValueType();
5997 EVT ExTy = N0.getValueType();
5998 EVT TrTy = N->getValueType(0);
5999
6000 unsigned NumElem = VecTy.getVectorNumElements();
6001 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6002
6003 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6004 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6005
6006 SDValue EltNo = N0->getOperand(1);
6007 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6008 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006009 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006010 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6011
Andrew Trickef9de2a2013-05-25 02:42:55 +00006012 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006013 NVT, N0.getOperand(0));
6014
6015 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006016 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006017 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006018 }
6019 }
6020
Matt Arsenault3332b702014-07-10 18:21:04 +00006021 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6022 if (N0.getOpcode() == ISD::SELECT) {
6023 EVT SrcVT = N0.getValueType();
6024 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6025 TLI.isTruncateFree(SrcVT, VT)) {
6026 SDLoc SL(N0);
6027 SDValue Cond = N0.getOperand(0);
6028 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6029 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6030 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6031 }
6032 }
6033
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006034 // Fold a series of buildvector, bitcast, and truncate if possible.
6035 // For example fold
6036 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6037 // (2xi32 (buildvector x, y)).
6038 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6039 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6040 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6041 N0.getOperand(0).hasOneUse()) {
6042
6043 SDValue BuildVect = N0.getOperand(0);
6044 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6045 EVT TruncVecEltTy = VT.getVectorElementType();
6046
6047 // Check that the element types match.
6048 if (BuildVectEltTy == TruncVecEltTy) {
6049 // Now we only need to compute the offset of the truncated elements.
6050 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6051 unsigned TruncVecNumElts = VT.getVectorNumElements();
6052 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6053
6054 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6055 "Invalid number of elements");
6056
6057 SmallVector<SDValue, 8> Opnds;
6058 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6059 Opnds.push_back(BuildVect.getOperand(i));
6060
Craig Topper48d114b2014-04-26 18:35:24 +00006061 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006062 }
6063 }
6064
Chris Lattner5e6fe052007-10-13 06:35:54 +00006065 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006066 // only the low bits are being used.
6067 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006068 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006069 // may have different active low bits.
6070 if (!VT.isVector()) {
6071 SDValue Shorter =
6072 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6073 VT.getSizeInBits()));
6074 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006075 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006076 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006077 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006078 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006079 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6080 SDValue Reduced = ReduceLoadWidth(N);
6081 if (Reduced.getNode())
6082 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006083 // Handle the case where the load remains an extending load even
6084 // after truncation.
6085 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6086 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6087 if (!LN0->isVolatile() &&
6088 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6089 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6090 VT, LN0->getChain(), LN0->getBasePtr(),
6091 LN0->getMemoryVT(),
6092 LN0->getMemOperand());
6093 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6094 return NewLoad;
6095 }
6096 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006097 }
Michael Liao3ac82012012-10-17 23:45:54 +00006098 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6099 // where ... are all 'undef'.
6100 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6101 SmallVector<EVT, 8> VTs;
6102 SDValue V;
6103 unsigned Idx = 0;
6104 unsigned NumDefs = 0;
6105
6106 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6107 SDValue X = N0.getOperand(i);
6108 if (X.getOpcode() != ISD::UNDEF) {
6109 V = X;
6110 Idx = i;
6111 NumDefs++;
6112 }
6113 // Stop if more than one members are non-undef.
6114 if (NumDefs > 1)
6115 break;
6116 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6117 VT.getVectorElementType(),
6118 X.getValueType().getVectorNumElements()));
6119 }
6120
6121 if (NumDefs == 0)
6122 return DAG.getUNDEF(VT);
6123
6124 if (NumDefs == 1) {
6125 assert(V.getNode() && "The single defined operand is empty!");
6126 SmallVector<SDValue, 8> Opnds;
6127 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6128 if (i != Idx) {
6129 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6130 continue;
6131 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006132 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006133 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006134 Opnds.push_back(NV);
6135 }
Craig Topper48d114b2014-04-26 18:35:24 +00006136 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006137 }
6138 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006139
6140 // Simplify the operands using demanded-bits information.
6141 if (!VT.isVector() &&
6142 SimplifyDemandedBits(SDValue(N, 0)))
6143 return SDValue(N, 0);
6144
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006145 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006146}
6147
Evan Chengb980f6f2008-05-12 23:04:07 +00006148static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006149 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006150 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006151 return Elt.getNode();
6152 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006153}
6154
6155/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006156/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006157SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006158 assert(N->getOpcode() == ISD::BUILD_PAIR);
6159
Nate Begeman624690c2009-06-05 21:37:30 +00006160 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6161 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006162 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006163 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006164 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006165 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006166
Evan Chengb980f6f2008-05-12 23:04:07 +00006167 if (ISD::isNON_EXTLoad(LD2) &&
6168 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006169 // If both are volatile this would reduce the number of volatile loads.
6170 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006171 !LD1->isVolatile() &&
6172 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006173 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006174 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006175 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006176 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006177
Duncan Sands8651e9c2008-06-13 19:07:40 +00006178 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006179 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006180 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006181 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006182 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006183 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006185 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006186}
6187
Wesley Peck527da1b2010-11-23 03:31:01 +00006188SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006189 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006190 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006191
Dan Gohmana8665142007-06-25 16:23:39 +00006192 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6193 // Only do this before legalize, since afterward the target may be depending
6194 // on the bitconvert.
6195 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006196 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006197 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006198 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006199 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006200
Owen Anderson53aa7a92009-08-10 22:56:29 +00006201 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006202 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006203 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006204 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006205 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006206 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006207
Dan Gohman921ddd62008-09-05 01:58:21 +00006208 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006209 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006210 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006211 if (Res.getNode() != N) {
6212 if (!LegalOperations ||
6213 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6214 return Res;
6215
6216 // Folding it resulted in an illegal node, and it's too late to
6217 // do that. Clean up the old node and forego the transformation.
6218 // Ideally this won't happen very often, because instcombine
6219 // and the earlier dagcombine runs (where illegal nodes are
6220 // permitted) should have folded most of them already.
6221 DAG.DeleteNode(Res.getNode());
6222 }
Chris Lattnera1874602005-12-23 05:30:37 +00006223 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006224
Bill Wendling4e0a6152009-01-30 22:44:24 +00006225 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006226 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006227 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006228 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006229
Chris Lattner54560f62005-12-23 05:44:41 +00006230 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006231 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006232 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006233 // Do not change the width of a volatile load.
6234 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006235 // Do not remove the cast if the types differ in endian layout.
6236 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6237 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006238 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6239 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006240 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006241 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006242 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006243 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006244
Evan Chenga4cf58a2007-05-07 21:27:48 +00006245 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006246 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006247 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006248 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006249 LN0->isInvariant(), OrigAlign,
6250 LN0->getTBAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006251 AddToWorklist(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006252 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006253 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006254 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006255 Load.getValue(1));
6256 return Load;
6257 }
Chris Lattner54560f62005-12-23 05:44:41 +00006258 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006259
Bill Wendling4e0a6152009-01-30 22:44:24 +00006260 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6261 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006262 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006263 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6264 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006265 N0.getNode()->hasOneUse() && VT.isInteger() &&
6266 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006267 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006268 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006269 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006270
Duncan Sands13237ac2008-06-06 12:08:01 +00006271 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006272 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006273 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006274 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006275 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006276 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006277 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006278 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006279
Bill Wendling4e0a6152009-01-30 22:44:24 +00006280 // fold (bitconvert (fcopysign cst, x)) ->
6281 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6282 // Note that we don't handle (copysign x, cst) because this can always be
6283 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006284 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006285 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006286 VT.isInteger() && !VT.isVector()) {
6287 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006288 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006289 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006290 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006291 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006292 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006293
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006294 // If X has a different width than the result/lhs, sext it or truncate it.
6295 unsigned VTWidth = VT.getSizeInBits();
6296 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006297 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006298 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006299 } else if (OrigXWidth > VTWidth) {
6300 // To get the sign bit in the right place, we have to shift it right
6301 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006302 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006303 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006304 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006305 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006306 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006307 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006308 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006309
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006310 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006311 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006312 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006313 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006314
Andrew Trickef9de2a2013-05-25 02:42:55 +00006315 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006316 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006317 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006318 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006319 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006320
Andrew Trickef9de2a2013-05-25 02:42:55 +00006321 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006322 }
Chris Lattner888560d2008-01-27 17:42:27 +00006323 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006324
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006325 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006326 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006327 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6328 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006329 return CombineLD;
6330 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006331
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006332 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006333}
6334
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006335SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006336 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006337 return CombineConsecutiveLoads(N, VT);
6338}
6339
Wesley Peck527da1b2010-11-23 03:31:01 +00006340/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006341/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006342/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006343SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006344ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006345 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006346
Chris Lattnere4e64b62006-04-02 02:53:43 +00006347 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006348 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006349
Duncan Sands13237ac2008-06-06 12:08:01 +00006350 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6351 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006352
Chris Lattnere4e64b62006-04-02 02:53:43 +00006353 // If this is a conversion of N elements of one type to N elements of another
6354 // type, convert each element. This handles FP<->INT cases.
6355 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006356 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6357 BV->getValueType(0).getVectorNumElements());
6358
6359 // Due to the FP element handling below calling this routine recursively,
6360 // we can end up with a scalar-to-vector node here.
6361 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006362 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6363 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006364 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006365
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006366 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006367 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006368 SDValue Op = BV->getOperand(i);
6369 // If the vector element type is not legal, the BUILD_VECTOR operands
6370 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006371 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006372 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6373 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006374 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006375 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006376 }
Craig Topper48d114b2014-04-26 18:35:24 +00006377 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006378 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006379
Chris Lattnere4e64b62006-04-02 02:53:43 +00006380 // Otherwise, we're growing or shrinking the elements. To avoid having to
6381 // handle annoying details of growing/shrinking FP values, we convert them to
6382 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006383 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006384 // Convert the input float vector to a int vector where the elements are the
6385 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006386 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006387 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006388 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006389 SrcEltVT = IntVT;
6390 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006391
Chris Lattnere4e64b62006-04-02 02:53:43 +00006392 // Now we know the input is an integer vector. If the output is a FP type,
6393 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006394 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006395 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006396 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006397 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006398
Chris Lattnere4e64b62006-04-02 02:53:43 +00006399 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006400 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006401 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006402
Chris Lattnere4e64b62006-04-02 02:53:43 +00006403 // Okay, we know the src/dst types are both integers of differing types.
6404 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006405 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006406 if (SrcBitSize < DstBitSize) {
6407 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006408
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006409 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006410 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006411 i += NumInputsPerOutput) {
6412 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006413 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006414 bool EltIsUndef = true;
6415 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6416 // Shift the previously computed bits over.
6417 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006418 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006419 if (Op.getOpcode() == ISD::UNDEF) continue;
6420 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006421
Jay Foad583abbc2010-12-07 08:25:19 +00006422 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006423 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006424 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006425
Chris Lattnere4e64b62006-04-02 02:53:43 +00006426 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006427 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006428 else
6429 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6430 }
6431
Owen Anderson117c9e82009-08-12 00:36:31 +00006432 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006433 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006434 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006435
Chris Lattnere4e64b62006-04-02 02:53:43 +00006436 // Finally, this must be the case where we are shrinking elements: each input
6437 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006438 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006439 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006440 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6441 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006442 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006443
Dan Gohmana8665142007-06-25 16:23:39 +00006444 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006445 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6446 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006447 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006448 continue;
6449 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006450
Jay Foad583abbc2010-12-07 08:25:19 +00006451 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6452 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006453
Chris Lattnere4e64b62006-04-02 02:53:43 +00006454 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006455 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006456 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006457 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006458 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006459 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006460 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006461 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006462 }
6463
6464 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006465 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006466 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6467 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006468
Craig Topper48d114b2014-04-26 18:35:24 +00006469 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006470}
6471
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006472SDValue DAGCombiner::visitFADD(SDNode *N) {
6473 SDValue N0 = N->getOperand(0);
6474 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006475 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6476 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006477 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006478
Dan Gohmana8665142007-06-25 16:23:39 +00006479 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006480 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006481 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006482 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006483 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006484
Lang Hamesa33db652012-06-14 20:37:15 +00006485 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006486 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006487 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006488 // canonicalize constant to RHS
6489 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006490 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006491 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006492 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6493 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006494 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006495 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006496 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006497 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006498 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006499 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006500 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006501 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006502 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006503 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006504 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006505
Chris Lattner0199fd62007-01-08 23:04:05 +00006506 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006507 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6508 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6509 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006510 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6511 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006512 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006513
Shuxin Yang93b1f122013-03-25 22:52:29 +00006514 // No FP constant should be created after legalization as Instruction
6515 // Selection pass has hard time in dealing with FP constant.
6516 //
6517 // We don't need test this condition for transformation like following, as
6518 // the DAG being transformed implies it is legal to take FP constant as
6519 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006520 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006521 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006522 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006523 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6524
Owen Andersonb351c8d2012-11-01 02:00:53 +00006525 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006526 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006527 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006528 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006529
6530 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006531 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006532 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006533 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006534
Owen Andersoncc61f872012-08-30 23:35:16 +00006535 // In unsafe math mode, we can fold chains of FADD's of the same value
6536 // into multiplications. This transform is not safe in general because
6537 // we are reducing the number of rounding steps.
6538 if (DAG.getTarget().Options.UnsafeFPMath &&
6539 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6540 !N0CFP && !N1CFP) {
6541 if (N0.getOpcode() == ISD::FMUL) {
6542 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6543 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6544
Stephen Line31f2d22013-06-14 18:17:35 +00006545 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006546 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006547 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006548 SDValue(CFP00, 0),
6549 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006550 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006551 N1, NewCFP);
6552 }
6553
Stephen Line31f2d22013-06-14 18:17:35 +00006554 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006555 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006556 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006557 SDValue(CFP01, 0),
6558 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006559 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006560 N1, NewCFP);
6561 }
6562
Stephen Line31f2d22013-06-14 18:17:35 +00006563 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006564 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6565 N1.getOperand(0) == N1.getOperand(1) &&
6566 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006567 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006568 SDValue(CFP00, 0),
6569 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006570 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006571 N0.getOperand(1), NewCFP);
6572 }
6573
Stephen Line31f2d22013-06-14 18:17:35 +00006574 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006575 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6576 N1.getOperand(0) == N1.getOperand(1) &&
6577 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006578 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006579 SDValue(CFP01, 0),
6580 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006581 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006582 N0.getOperand(0), NewCFP);
6583 }
6584 }
6585
6586 if (N1.getOpcode() == ISD::FMUL) {
6587 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6588 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6589
Stephen Line31f2d22013-06-14 18:17:35 +00006590 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006591 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
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(CFP10, 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 N0, NewCFP);
6597 }
6598
Stephen Line31f2d22013-06-14 18:17:35 +00006599 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006600 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
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(CFP11, 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 N0, NewCFP);
6606 }
6607
Owen Andersoncc61f872012-08-30 23:35:16 +00006608
Stephen Line31f2d22013-06-14 18:17:35 +00006609 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6610 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6611 N0.getOperand(0) == N0.getOperand(1) &&
6612 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006613 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006614 SDValue(CFP10, 0),
6615 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006616 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006617 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006618 }
6619
Stephen Line31f2d22013-06-14 18:17:35 +00006620 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6621 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6622 N0.getOperand(0) == N0.getOperand(1) &&
6623 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006624 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006625 SDValue(CFP11, 0),
6626 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006627 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006628 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006629 }
6630 }
6631
Shuxin Yang93b1f122013-03-25 22:52:29 +00006632 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006633 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006634 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006635 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006636 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006637 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006638 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006639 }
6640
Shuxin Yang93b1f122013-03-25 22:52:29 +00006641 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006642 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006643 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006644 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006645 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006647 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006648 }
6649
Stephen Lin4e69d012013-06-14 21:33:58 +00006650 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006651 if (AllowNewFpConst &&
6652 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006653 N0.getOperand(0) == N0.getOperand(1) &&
6654 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006655 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006656 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006657 N0.getOperand(0),
6658 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006659 }
6660
Lang Hames39fb1d02012-06-19 22:51:23 +00006661 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006662 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006663 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006664 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6665 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006666
6667 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006668 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006669 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006670 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006671
Michael Liaoec3850122012-09-01 04:09:16 +00006672 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006673 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006674 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006675 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006676 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006677 }
6678
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006679 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006680}
6681
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006682SDValue DAGCombiner::visitFSUB(SDNode *N) {
6683 SDValue N0 = N->getOperand(0);
6684 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006685 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6686 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006687 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006688 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006689
Dan Gohmana8665142007-06-25 16:23:39 +00006690 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006691 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006692 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006693 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006694 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006695
Nate Begeman418c6e42005-10-18 00:28:13 +00006696 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006697 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006698 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006699 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006700 if (DAG.getTarget().Options.UnsafeFPMath &&
6701 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006702 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006703 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006704 if (DAG.getTarget().Options.UnsafeFPMath &&
6705 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006706 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006707 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006708 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006709 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006710 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006711 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006712 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006713 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006714 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006715
Bill Wendlingdf170db2012-03-15 05:12:00 +00006716 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006717 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006718 // (fsub x, (fadd x, y)) -> (fneg y) &
6719 // (fsub x, (fadd y, x)) -> (fneg y)
6720 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006721 if (N0 == N1)
6722 return DAG.getConstantFP(0.0f, VT);
6723
Bill Wendlingdf170db2012-03-15 05:12:00 +00006724 if (N1.getOpcode() == ISD::FADD) {
6725 SDValue N10 = N1->getOperand(0);
6726 SDValue N11 = N1->getOperand(1);
6727
6728 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6729 &DAG.getTarget().Options))
6730 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006731
Stephen Lin8e8424e2013-07-09 00:44:49 +00006732 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6733 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006734 return GetNegatedExpression(N10, DAG, LegalOperations);
6735 }
6736 }
6737
Lang Hames39fb1d02012-06-19 22:51:23 +00006738 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006739 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006740 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006741 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6742 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006743
6744 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006745 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006746 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006747 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006748 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006749
6750 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6751 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006752 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006753 return DAG.getNode(ISD::FMA, dl, VT,
6754 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006755 N1.getOperand(0)),
6756 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006757
Stephen Lin8e8424e2013-07-09 00:44:49 +00006758 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006759 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006760 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6761 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6762 SDValue N00 = N0.getOperand(0).getOperand(0);
6763 SDValue N01 = N0.getOperand(0).getOperand(1);
6764 return DAG.getNode(ISD::FMA, dl, VT,
6765 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6766 DAG.getNode(ISD::FNEG, dl, VT, N1));
6767 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006768 }
6769
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006770 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006771}
6772
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006773SDValue DAGCombiner::visitFMUL(SDNode *N) {
6774 SDValue N0 = N->getOperand(0);
6775 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006776 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6777 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006778 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006779 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006780
Dan Gohmana8665142007-06-25 16:23:39 +00006781 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006782 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006783 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006784 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006785 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006786
Nate Begemanec48a1b2005-10-17 20:40:11 +00006787 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006788 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006789 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006790 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006791 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006792 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006793 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006794 if (DAG.getTarget().Options.UnsafeFPMath &&
6795 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006796 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006797 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006798 if (DAG.getTarget().Options.UnsafeFPMath &&
6799 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006800 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006801 // fold (fmul A, 1.0) -> A
6802 if (N1CFP && N1CFP->isExactlyValue(1.0))
6803 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006804 // fold (fmul X, 2.0) -> (fadd X, X)
6805 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006806 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006807 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006808 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006809 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006810 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006811
Bill Wendling3dc5d242009-01-30 22:57:07 +00006812 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006813 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006814 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006815 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006816 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006817 // Both can be negated for free, check to see if at least one is cheaper
6818 // negated.
6819 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006820 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006821 GetNegatedExpression(N0, DAG, LegalOperations),
6822 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006823 }
6824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006825
Chris Lattner0199fd62007-01-08 23:04:05 +00006826 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006827 if (DAG.getTarget().Options.UnsafeFPMath &&
6828 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006829 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006830 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6831 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006832 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006833
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006834 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006835}
6836
Owen Anderson41b06652012-05-02 22:17:40 +00006837SDValue DAGCombiner::visitFMA(SDNode *N) {
6838 SDValue N0 = N->getOperand(0);
6839 SDValue N1 = N->getOperand(1);
6840 SDValue N2 = N->getOperand(2);
6841 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6842 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6843 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006844 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006845
Owen Andersonb351c8d2012-11-01 02:00:53 +00006846 if (DAG.getTarget().Options.UnsafeFPMath) {
6847 if (N0CFP && N0CFP->isZero())
6848 return N2;
6849 if (N1CFP && N1CFP->isZero())
6850 return N2;
6851 }
Owen Anderson41b06652012-05-02 22:17:40 +00006852 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006853 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006854 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006855 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006856
Owen Andersonc7aaf522012-05-30 18:50:39 +00006857 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006858 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006859 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006860
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006861 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6862 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6863 N2.getOpcode() == ISD::FMUL &&
6864 N0 == N2.getOperand(0) &&
6865 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6866 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6867 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6868 }
6869
6870
6871 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6872 if (DAG.getTarget().Options.UnsafeFPMath &&
6873 N0.getOpcode() == ISD::FMUL && N1CFP &&
6874 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6875 return DAG.getNode(ISD::FMA, dl, VT,
6876 N0.getOperand(0),
6877 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6878 N2);
6879 }
6880
6881 // (fma x, 1, y) -> (fadd x, y)
6882 // (fma x, -1, y) -> (fadd (fneg x), y)
6883 if (N1CFP) {
6884 if (N1CFP->isExactlyValue(1.0))
6885 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6886
6887 if (N1CFP->isExactlyValue(-1.0) &&
6888 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6889 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006890 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006891 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6892 }
6893 }
6894
6895 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006896 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6897 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006898 DAG.getNode(ISD::FADD, dl, VT,
6899 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006900
6901 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6902 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006903 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6904 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006905 DAG.getNode(ISD::FADD, dl, VT,
6906 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006907
6908
Owen Anderson41b06652012-05-02 22:17:40 +00006909 return SDValue();
6910}
6911
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006912SDValue DAGCombiner::visitFDIV(SDNode *N) {
6913 SDValue N0 = N->getOperand(0);
6914 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006915 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6916 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006917 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006918 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006919
Dan Gohmana8665142007-06-25 16:23:39 +00006920 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006921 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006922 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006923 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006924 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006925
Nate Begeman569c4392006-01-18 22:35:16 +00006926 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006927 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006928 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006929
Duncan Sands2f1dc382012-04-08 18:08:12 +00006930 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006931 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006932 // Compute the reciprocal 1.0 / c2.
6933 APFloat N1APF = N1CFP->getValueAPF();
6934 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6935 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006936 // Only do the transform if the reciprocal is a legal fp immediate that
6937 // isn't too nasty (eg NaN, denormal, ...).
6938 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006939 (!LegalOperations ||
6940 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6941 // backend)... we should handle this gracefully after Legalize.
6942 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6943 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6944 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006945 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006946 DAG.getConstantFP(Recip, VT));
6947 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006948
Bill Wendling3dc5d242009-01-30 22:57:07 +00006949 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006950 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006951 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006952 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006953 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006954 // Both can be negated for free, check to see if at least one is cheaper
6955 // negated.
6956 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006957 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006958 GetNegatedExpression(N0, DAG, LegalOperations),
6959 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006960 }
6961 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006962
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006963 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006964}
6965
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006966SDValue DAGCombiner::visitFREM(SDNode *N) {
6967 SDValue N0 = N->getOperand(0);
6968 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006969 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6970 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006971 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006972
Nate Begeman569c4392006-01-18 22:35:16 +00006973 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006974 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006975 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006976
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006977 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006978}
6979
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006980SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6981 SDValue N0 = N->getOperand(0);
6982 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006983 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6984 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006985 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006986
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006987 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006988 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006989
Chris Lattner3bc40502006-03-05 05:30:57 +00006990 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006991 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006992 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6993 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006994 if (!V.isNegative()) {
6995 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006996 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006997 } else {
6998 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006999 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7000 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007001 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007002 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007003
Chris Lattner3bc40502006-03-05 05:30:57 +00007004 // copysign(fabs(x), y) -> copysign(x, y)
7005 // copysign(fneg(x), y) -> copysign(x, y)
7006 // copysign(copysign(x,z), y) -> copysign(x, y)
7007 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7008 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007009 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007010 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007011
7012 // copysign(x, abs(y)) -> abs(x)
7013 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007014 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007015
Chris Lattner3bc40502006-03-05 05:30:57 +00007016 // copysign(x, copysign(y,z)) -> copysign(x, z)
7017 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007018 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007019 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007020
Chris Lattner3bc40502006-03-05 05:30:57 +00007021 // copysign(x, fp_extend(y)) -> copysign(x, y)
7022 // copysign(x, fp_round(y)) -> copysign(x, y)
7023 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007024 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007025 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007026
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007027 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007028}
7029
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007030SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7031 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007032 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007033 EVT VT = N->getValueType(0);
7034 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007035
Nate Begeman21158fc2005-09-01 00:19:25 +00007036 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007037 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007038 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007039 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007040 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007041 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007042
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007043 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7044 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007045 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7046 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007047 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007048 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007049 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007050 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007051
Alp Tokercb402912014-01-24 17:20:08 +00007052 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007053 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007054 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7055 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7056 !VT.isVector() &&
7057 (!LegalOperations ||
7058 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7059 SDValue Ops[] =
7060 { N0.getOperand(0), N0.getOperand(1),
7061 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7062 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007063 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007064 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007065
Nadav Rotem90560762012-07-23 07:59:50 +00007066 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7067 // (select_cc x, y, 1.0, 0.0,, cc)
7068 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7069 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7070 (!LegalOperations ||
7071 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7072 SDValue Ops[] =
7073 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7074 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7075 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007076 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007077 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007078 }
7079
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007080 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007081}
7082
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007083SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7084 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007085 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007086 EVT VT = N->getValueType(0);
7087 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007088
Nate Begeman21158fc2005-09-01 00:19:25 +00007089 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007090 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007091 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007092 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007093 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007094 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007095
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007096 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7097 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007098 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7099 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007100 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007101 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007102 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007103 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007104
Alp Tokercb402912014-01-24 17:20:08 +00007105 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007106 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007107 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007108
Nadav Rotem90560762012-07-23 07:59:50 +00007109 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7110 (!LegalOperations ||
7111 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7112 SDValue Ops[] =
7113 { N0.getOperand(0), N0.getOperand(1),
7114 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7115 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007116 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007117 }
7118 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007119
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007120 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007121}
7122
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007123SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7124 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007125 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007126 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007127
Nate Begeman21158fc2005-09-01 00:19:25 +00007128 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007129 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007130 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007131
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007132 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007133}
7134
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007135SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7136 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007137 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007138 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007139
Nate Begeman21158fc2005-09-01 00:19:25 +00007140 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007141 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007142 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007143
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007144 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007145}
7146
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007147SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7148 SDValue N0 = N->getOperand(0);
7149 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007150 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007151 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007152
Nate Begeman21158fc2005-09-01 00:19:25 +00007153 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007154 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007155 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007156
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007157 // fold (fp_round (fp_extend x)) -> x
7158 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7159 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007160
Chris Lattner0feb1b02008-01-24 06:45:35 +00007161 // fold (fp_round (fp_round x)) -> (fp_round x)
7162 if (N0.getOpcode() == ISD::FP_ROUND) {
7163 // This is a value preserving truncation if both round's are.
7164 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007165 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007166 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007167 DAG.getIntPtrConstant(IsTrunc));
7168 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007169
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007170 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007171 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007172 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007173 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007174 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007175 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007176 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007177 }
Scott Michelcf0da6c2009-02-17 22:15:04 +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_ROUND_INREG(SDNode *N) {
7183 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007184 EVT VT = N->getValueType(0);
7185 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007186 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007187
Nate Begeman21158fc2005-09-01 00:19:25 +00007188 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007189 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007190 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007191 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007192 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007193
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007194 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007195}
7196
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007197SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7198 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007199 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007200 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007201
Chris Lattner5919b482007-12-29 06:55:23 +00007202 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007203 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007204 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007205 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007206
Nate Begeman21158fc2005-09-01 00:19:25 +00007207 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007208 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007209 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007210
7211 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7212 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007213 if (N0.getOpcode() == ISD::FP_ROUND
7214 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007215 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007216 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007217 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007218 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007219 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007220 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007221 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007222
Chris Lattner72733e52008-01-17 07:00:52 +00007223 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007224 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007225 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007226 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007227 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007228 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007229 LN0->getBasePtr(), N0.getValueType(),
7230 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007231 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007232 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007233 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007234 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007235 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007236 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007237 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007238
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007239 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007240}
7241
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007242SDValue DAGCombiner::visitFNEG(SDNode *N) {
7243 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007244 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007245
Craig Topper82384612012-09-11 01:45:21 +00007246 if (VT.isVector()) {
7247 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7248 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007249 }
7250
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007251 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7252 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007253 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007254
Chris Lattner888560d2008-01-27 17:42:27 +00007255 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7256 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007257 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007258 !VT.isVector() &&
7259 N0.getNode()->hasOneUse() &&
7260 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007261 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007262 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007263 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007264 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007265 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007266 AddToWorklist(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007267 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007268 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007269 }
7270 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007271
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007272 // (fneg (fmul c, x)) -> (fmul -c, x)
7273 if (N0.getOpcode() == ISD::FMUL) {
7274 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007275 if (CFP1) {
7276 APFloat CVal = CFP1->getValueAPF();
7277 CVal.changeSign();
7278 if (Level >= AfterLegalizeDAG &&
7279 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7280 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7281 return DAG.getNode(
7282 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7283 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7284 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007285 }
7286
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007287 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007288}
7289
Owen Andersona40319b2012-08-13 23:32:49 +00007290SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7291 SDValue N0 = N->getOperand(0);
7292 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7293 EVT VT = N->getValueType(0);
7294
7295 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007296 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007297 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007298
7299 return SDValue();
7300}
7301
7302SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7303 SDValue N0 = N->getOperand(0);
7304 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7305 EVT VT = N->getValueType(0);
7306
7307 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007308 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007309 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007310
7311 return SDValue();
7312}
7313
7314SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7315 SDValue N0 = N->getOperand(0);
7316 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7317 EVT VT = N->getValueType(0);
7318
7319 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007320 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007321 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007322
7323 return SDValue();
7324}
7325
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007326SDValue DAGCombiner::visitFABS(SDNode *N) {
7327 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007328 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007329 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007330
Craig Topper82384612012-09-11 01:45:21 +00007331 if (VT.isVector()) {
7332 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7333 if (FoldedVOp.getNode()) return FoldedVOp;
7334 }
7335
Nate Begeman21158fc2005-09-01 00:19:25 +00007336 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007337 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007338 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007339 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007340 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007341 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007342 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007343 // fold (fabs (fcopysign x, y)) -> (fabs x)
7344 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007345 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007346
Chris Lattner888560d2008-01-27 17:42:27 +00007347 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7348 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007349 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007350 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007351 N0.getOperand(0).getValueType().isInteger() &&
7352 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007353 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007354 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007355 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007356 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007357 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007358 AddToWorklist(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007359 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007360 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007361 }
7362 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007363
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007364 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007365}
7366
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007367SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7368 SDValue Chain = N->getOperand(0);
7369 SDValue N1 = N->getOperand(1);
7370 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007371
Dan Gohman82e80012009-11-17 00:47:23 +00007372 // If N is a constant we could fold this into a fallthrough or unconditional
7373 // branch. However that doesn't happen very often in normal code, because
7374 // Instcombine/SimplifyCFG should have handled the available opportunities.
7375 // If we did this folding here, it would be necessary to update the
7376 // MachineBasicBlock CFG, which is awkward.
7377
Nate Begeman7e7f4392006-02-01 07:19:44 +00007378 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7379 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007380 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007381 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7382 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007383 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007384 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007385 N1.getOperand(0), N1.getOperand(1), N2);
7386 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007387
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007388 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7389 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7390 (N1.getOperand(0).hasOneUse() &&
7391 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007392 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007393 if (N1.getOpcode() == ISD::TRUNCATE) {
7394 // Look pass the truncate.
7395 Trunc = N1.getNode();
7396 N1 = N1.getOperand(0);
7397 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007398
Bill Wendlingaa28be62009-03-26 06:14:09 +00007399 // Match this pattern so that we can generate simpler code:
7400 //
7401 // %a = ...
7402 // %b = and i32 %a, 2
7403 // %c = srl i32 %b, 1
7404 // brcond i32 %c ...
7405 //
7406 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007407 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007408 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007409 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007410 // %c = setcc eq %b, 0
7411 // brcond %c ...
7412 //
7413 // This applies only when the AND constant value has one bit set and the
7414 // SRL constant is equal to the log2 of the AND constant. The back-end is
7415 // smart enough to convert the result into a TEST/JMP sequence.
7416 SDValue Op0 = N1.getOperand(0);
7417 SDValue Op1 = N1.getOperand(1);
7418
7419 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007420 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007421 SDValue AndOp1 = Op0.getOperand(1);
7422
7423 if (AndOp1.getOpcode() == ISD::Constant) {
7424 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7425
7426 if (AndConst.isPowerOf2() &&
7427 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7428 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007429 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007430 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007431 Op0, DAG.getConstant(0, Op0.getValueType()),
7432 ISD::SETNE);
7433
Andrew Trickef9de2a2013-05-25 02:42:55 +00007434 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007435 MVT::Other, Chain, SetCC, N2);
7436 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7437 // will convert it back to (X & C1) >> C2.
7438 CombineTo(N, NewBRCond, false);
7439 // Truncate is dead.
7440 if (Trunc) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007441 removeFromWorklist(Trunc);
Evan Cheng166a4e62010-01-06 19:38:29 +00007442 DAG.DeleteNode(Trunc);
7443 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007444 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007445 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007446 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007447 removeFromWorklist(N1.getNode());
Bill Wendlingaa28be62009-03-26 06:14:09 +00007448 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007449 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007450 }
7451 }
7452 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007453
7454 if (Trunc)
7455 // Restore N1 if the above transformation doesn't match.
7456 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007457 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007458
Evan Cheng228c31f2010-02-27 07:36:59 +00007459 // Transform br(xor(x, y)) -> br(x != y)
7460 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7461 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7462 SDNode *TheXor = N1.getNode();
7463 SDValue Op0 = TheXor->getOperand(0);
7464 SDValue Op1 = TheXor->getOperand(1);
7465 if (Op0.getOpcode() == Op1.getOpcode()) {
7466 // Avoid missing important xor optimizations.
7467 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007468 if (Tmp.getNode()) {
7469 if (Tmp.getNode() != TheXor) {
7470 DEBUG(dbgs() << "\nReplacing.8 ";
7471 TheXor->dump(&DAG);
7472 dbgs() << "\nWith: ";
7473 Tmp.getNode()->dump(&DAG);
7474 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007475 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007476 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007477 removeFromWorklist(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007478 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007479 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007480 MVT::Other, Chain, Tmp, N2);
7481 }
7482
Benjamin Kramer93354432013-03-30 21:28:18 +00007483 // visitXOR has changed XOR's operands or replaced the XOR completely,
7484 // bail out.
7485 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007486 }
7487 }
7488
7489 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7490 bool Equal = false;
7491 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7492 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7493 Op0.getOpcode() == ISD::XOR) {
7494 TheXor = Op0.getNode();
7495 Equal = true;
7496 }
7497
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007498 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007499 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007500 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007501 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007502 SetCCVT,
7503 Op0, Op1,
7504 Equal ? ISD::SETEQ : ISD::SETNE);
7505 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007506 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007507 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007508 removeFromWorklist(N1.getNode());
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007509 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007510 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007511 MVT::Other, Chain, SetCC, N2);
7512 }
7513 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007514
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007515 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007516}
7517
Chris Lattnera49e16f2005-10-05 06:47:48 +00007518// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7519//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007520SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007521 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007522 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007523
Dan Gohman82e80012009-11-17 00:47:23 +00007524 // If N is a constant we could fold this into a fallthrough or unconditional
7525 // branch. However that doesn't happen very often in normal code, because
7526 // Instcombine/SimplifyCFG should have handled the available opportunities.
7527 // If we did this folding here, it would be necessary to update the
7528 // MachineBasicBlock CFG, which is awkward.
7529
Duncan Sands93b66092008-06-09 11:32:28 +00007530 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007531 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007532 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007533 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007534 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007535
Nate Begemanbd7df032005-10-05 21:43:42 +00007536 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007537 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007538 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007539 N->getOperand(0), Simp.getOperand(2),
7540 Simp.getOperand(0), Simp.getOperand(1),
7541 N->getOperand(4));
7542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007543 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007544}
7545
Evan Chengfa832632012-01-13 01:37:24 +00007546/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7547/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007548/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007549static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7550 SelectionDAG &DAG,
7551 const TargetLowering &TLI) {
7552 EVT VT;
7553 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7554 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7555 return false;
7556 VT = Use->getValueType(0);
7557 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7558 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7559 return false;
7560 VT = ST->getValue().getValueType();
7561 } else
7562 return false;
7563
Chandler Carruth95f83e02013-01-07 15:14:13 +00007564 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007565 if (N->getOpcode() == ISD::ADD) {
7566 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7567 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007568 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007569 AM.BaseOffs = Offset->getSExtValue();
7570 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007571 // [reg +/- reg]
7572 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007573 } else if (N->getOpcode() == ISD::SUB) {
7574 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7575 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007576 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007577 AM.BaseOffs = -Offset->getSExtValue();
7578 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007579 // [reg +/- reg]
7580 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007581 } else
7582 return false;
7583
7584 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7585}
7586
Duncan Sands075293f2008-06-15 20:12:31 +00007587/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7588/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007589/// and it has other uses besides the load / store. After the
7590/// transformation, the new indexed load / store has effectively folded
7591/// the add / subtract in and all of its other uses are redirected to the
7592/// new load / store.
7593bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007594 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007595 return false;
7596
7597 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007598 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007599 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007600 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007601 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007602 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007603 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007604 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007605 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7606 return false;
7607 Ptr = LD->getBasePtr();
7608 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007609 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007610 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007611 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007612 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7613 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7614 return false;
7615 Ptr = ST->getBasePtr();
7616 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007617 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007618 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007619 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007620
Chris Lattnereabc15c2006-11-11 00:56:29 +00007621 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7622 // out. There is no reason to make this a preinc/predec.
7623 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007624 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007625 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007626
Chris Lattnereabc15c2006-11-11 00:56:29 +00007627 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007628 SDValue BasePtr;
7629 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007630 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7631 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7632 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007633
7634 // Backends without true r+i pre-indexed forms may need to pass a
7635 // constant base with a variable offset so that constant coercion
7636 // will work with the patterns in canonical form.
7637 bool Swapped = false;
7638 if (isa<ConstantSDNode>(BasePtr)) {
7639 std::swap(BasePtr, Offset);
7640 Swapped = true;
7641 }
7642
Evan Cheng044a0a82007-05-03 23:52:19 +00007643 // Don't create a indexed load / store with zero offset.
7644 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007645 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007646 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007647
Chris Lattnera0a80032006-11-11 01:00:15 +00007648 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007649 // 1) The new base ptr is a frame index.
7650 // 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 +00007651 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007652 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007653 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007654 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007655
Chris Lattnera0a80032006-11-11 01:00:15 +00007656 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7657 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007658 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007659 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007660
Chris Lattnera0a80032006-11-11 01:00:15 +00007661 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007662 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007663 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007664 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007665 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007666 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007667
Hal Finkel25819052013-02-08 21:35:47 +00007668 // If the offset is a constant, there may be other adds of constants that
7669 // can be folded with this one. We should do this to avoid having to keep
7670 // a copy of the original base pointer.
7671 SmallVector<SDNode *, 16> OtherUses;
7672 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007673 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007674 if (Use == Ptr.getNode())
7675 continue;
7676
7677 if (Use->isPredecessorOf(N))
7678 continue;
7679
7680 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7681 OtherUses.clear();
7682 break;
7683 }
7684
7685 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7686 if (Op1.getNode() == BasePtr.getNode())
7687 std::swap(Op0, Op1);
7688 assert(Op0.getNode() == BasePtr.getNode() &&
7689 "Use of ADD/SUB but not an operand");
7690
7691 if (!isa<ConstantSDNode>(Op1)) {
7692 OtherUses.clear();
7693 break;
7694 }
7695
7696 // FIXME: In some cases, we can be smarter about this.
7697 if (Op1.getValueType() != Offset.getValueType()) {
7698 OtherUses.clear();
7699 break;
7700 }
7701
7702 OtherUses.push_back(Use);
7703 }
7704
7705 if (Swapped)
7706 std::swap(BasePtr, Offset);
7707
Evan Chenga4d187b2007-05-24 02:35:39 +00007708 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007709 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007710
7711 // Caches for hasPredecessorHelper
7712 SmallPtrSet<const SDNode *, 32> Visited;
7713 SmallVector<const SDNode *, 16> Worklist;
7714
Jim Grosbache8160032014-04-11 01:13:13 +00007715 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007716 if (Use == N)
7717 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007718 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007719 return false;
7720
Evan Chengfa832632012-01-13 01:37:24 +00007721 // If Ptr may be folded in addressing mode of other use, then it's
7722 // not profitable to do this transformation.
7723 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007724 RealUse = true;
7725 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007726
Chris Lattnereabc15c2006-11-11 00:56:29 +00007727 if (!RealUse)
7728 return false;
7729
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007730 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007731 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007732 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007733 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007734 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007735 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007736 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007737 ++PreIndexedNodes;
7738 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007739 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007740 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007741 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007742 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007743 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007744 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007745 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007746 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7747 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007748 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007749 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007750 }
7751
Chris Lattnereabc15c2006-11-11 00:56:29 +00007752 // Finally, since the node is now dead, remove it from the graph.
7753 DAG.DeleteNode(N);
7754
Hal Finkel25819052013-02-08 21:35:47 +00007755 if (Swapped)
7756 std::swap(BasePtr, Offset);
7757
7758 // Replace other uses of BasePtr that can be updated to use Ptr
7759 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7760 unsigned OffsetIdx = 1;
7761 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7762 OffsetIdx = 0;
7763 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7764 BasePtr.getNode() && "Expected BasePtr operand");
7765
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007766 // We need to replace ptr0 in the following expression:
7767 // x0 * offset0 + y0 * ptr0 = t0
7768 // knowing that
7769 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007770 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007771 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7772 // indexed load/store and the expresion that needs to be re-written.
7773 //
7774 // Therefore, we have:
7775 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007776
7777 ConstantSDNode *CN =
7778 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007779 int X0, X1, Y0, Y1;
7780 APInt Offset0 = CN->getAPIntValue();
7781 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007782
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007783 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7784 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7785 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7786 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007787
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007788 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7789
7790 APInt CNV = Offset0;
7791 if (X0 < 0) CNV = -CNV;
7792 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7793 else CNV = CNV - Offset1;
7794
7795 // We can now generate the new expression.
7796 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7797 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7798
7799 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007800 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007801 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7802 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007803 removeFromWorklist(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00007804 DAG.DeleteNode(OtherUses[i]);
7805 }
7806
Chris Lattnereabc15c2006-11-11 00:56:29 +00007807 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007808 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007809 removeFromWorklist(Ptr.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00007810 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007811
7812 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007813}
7814
Duncan Sands075293f2008-06-15 20:12:31 +00007815/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007816/// add / sub of the base pointer node into a post-indexed load / store.
7817/// The transformation folded the add / subtract into the new indexed
7818/// load / store effectively and all of its uses are redirected to the
7819/// new load / store.
7820bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007821 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007822 return false;
7823
7824 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007825 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007826 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007827 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007828 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007829 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007830 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007831 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7832 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7833 return false;
7834 Ptr = LD->getBasePtr();
7835 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007836 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007837 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007838 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007839 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7840 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7841 return false;
7842 Ptr = ST->getBasePtr();
7843 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007844 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007845 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007846 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007847
Gabor Greiff304a7a2008-08-28 21:40:38 +00007848 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007849 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007850
Jim Grosbache8160032014-04-11 01:13:13 +00007851 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007852 if (Op == N ||
7853 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7854 continue;
7855
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007856 SDValue BasePtr;
7857 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007858 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7859 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007860 // Don't create a indexed load / store with zero offset.
7861 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007862 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007863 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007864
Chris Lattnereabc15c2006-11-11 00:56:29 +00007865 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007866 // 1) All uses are load / store ops that use it as base ptr (and
7867 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007868 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7869 // nor a successor of N. Otherwise, if Op is folded that would
7870 // create a cycle.
7871
Evan Chengcfc05132009-05-06 18:25:01 +00007872 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7873 continue;
7874
Chris Lattnereabc15c2006-11-11 00:56:29 +00007875 // Check for #1.
7876 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007877 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007878 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007879 continue;
7880
Chris Lattnereabc15c2006-11-11 00:56:29 +00007881 // If all the uses are load / store addresses, then don't do the
7882 // transformation.
7883 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7884 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007885 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007886 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007887 RealUse = true;
7888 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007889
Chris Lattnereabc15c2006-11-11 00:56:29 +00007890 if (!RealUse) {
7891 TryNext = true;
7892 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007893 }
7894 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007895 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007896
Chris Lattnereabc15c2006-11-11 00:56:29 +00007897 if (TryNext)
7898 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007899
Chris Lattnereabc15c2006-11-11 00:56:29 +00007900 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007901 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007902 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007903 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007904 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007905 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007906 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007907 ++PostIndexedNodes;
7908 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007909 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007910 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007911 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007912 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007913 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007914 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007915 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007916 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7917 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007918 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007919 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007920 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007921
Chris Lattnereabc15c2006-11-11 00:56:29 +00007922 // Finally, since the node is now dead, remove it from the graph.
7923 DAG.DeleteNode(N);
7924
7925 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007926 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007927 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007928 removeFromWorklist(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007929 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007930 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007931 }
7932 }
7933 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007934
Chris Lattnerffad2162006-11-11 00:39:41 +00007935 return false;
7936}
7937
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007938SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007939 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007940 SDValue Chain = LD->getChain();
7941 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007942
Evan Chenga684cd22007-05-01 00:38:21 +00007943 // If load is not volatile and there are no uses of the loaded value (and
7944 // the updated indexed value in case of indexed loads), change uses of the
7945 // chain value into uses of the chain input (i.e. delete the dead load).
7946 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007947 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007948 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007949 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007950 // It's not safe to use the two value CombineTo variant here. e.g.
7951 // v1, chain2 = load chain1, loc
7952 // v2, chain3 = load chain2, loc
7953 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007954 // Now we replace use of chain2 with chain1. This makes the second load
7955 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007956 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007957 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007958 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007959 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007960 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007961 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007962 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007963
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007964 if (N->use_empty()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007965 removeFromWorklist(N);
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007966 DAG.DeleteNode(N);
7967 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007968
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007969 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007970 }
Evan Chengb68343c2007-05-01 08:53:39 +00007971 } else {
7972 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007973 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel2c77fe52014-05-28 15:33:19 +00007974 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007975 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007976 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007977 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007978 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007979 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007980 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007981 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007982 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel2c77fe52014-05-28 15:33:19 +00007983 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7984 DAG.getUNDEF(N->getValueType(1)));
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007985 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007986 removeFromWorklist(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007987 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007989 }
Evan Chenga684cd22007-05-01 00:38:21 +00007990 }
7991 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007992
Chris Lattnere260ed82005-10-10 22:04:48 +00007993 // If this load is directly stored, replace the load value with the stored
7994 // value.
7995 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007996 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007997 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007998 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007999 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8000 if (PrevST->getBasePtr() == Ptr &&
8001 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008002 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008003 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008004 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008005
Evan Cheng43cd9e32010-04-01 06:04:33 +00008006 // Try to infer better alignment information than the load already has.
8007 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008008 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008009 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8010 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008011 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008012 LD->getValueType(0),
8013 Chain, Ptr, LD->getPointerInfo(),
8014 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008015 LD->isVolatile(), LD->isNonTemporal(), Align,
8016 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008017 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8018 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008019 }
8020 }
8021
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008022 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8023 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008024#ifndef NDEBUG
8025 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8026 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8027 UseAA = false;
8028#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008029 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008030 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008031 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008032
Jim Laskey708d0db2006-10-04 16:53:27 +00008033 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008034 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008035 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008036
Jim Laskeyd07be232006-09-25 16:29:54 +00008037 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008038 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008039 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008040 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008041 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008042 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008043 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008044 BetterChain, Ptr, LD->getMemoryVT(),
8045 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008046 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008047
Jim Laskey708d0db2006-10-04 16:53:27 +00008048 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008049 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008050 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008051
Nate Begeman879d8f12009-09-15 00:18:30 +00008052 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008053 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008054
Jim Laskeydcf983c2006-10-13 23:32:28 +00008055 // Replace uses with load result and token factor. Don't add users
8056 // to work list.
8057 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008058 }
8059 }
8060
Evan Cheng357017f2006-11-03 03:06:21 +00008061 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008062 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008063 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008064
Quentin Colombetde0e0622013-10-11 18:29:42 +00008065 // Try to slice up N to more direct loads if the slices are mapped to
8066 // different register banks or pairing can take place.
8067 if (SliceUpLoad(N))
8068 return SDValue(N, 0);
8069
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008070 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008071}
8072
Quentin Colombetde0e0622013-10-11 18:29:42 +00008073namespace {
8074/// \brief Helper structure used to slice a load in smaller loads.
8075/// Basically a slice is obtained from the following sequence:
8076/// Origin = load Ty1, Base
8077/// Shift = srl Ty1 Origin, CstTy Amount
8078/// Inst = trunc Shift to Ty2
8079///
8080/// Then, it will be rewriten into:
8081/// Slice = load SliceTy, Base + SliceOffset
8082/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8083///
8084/// SliceTy is deduced from the number of bits that are actually used to
8085/// build Inst.
8086struct LoadedSlice {
8087 /// \brief Helper structure used to compute the cost of a slice.
8088 struct Cost {
8089 /// Are we optimizing for code size.
8090 bool ForCodeSize;
8091 /// Various cost.
8092 unsigned Loads;
8093 unsigned Truncates;
8094 unsigned CrossRegisterBanksCopies;
8095 unsigned ZExts;
8096 unsigned Shift;
8097
8098 Cost(bool ForCodeSize = false)
8099 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8100 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8101
8102 /// \brief Get the cost of one isolated slice.
8103 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8104 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8105 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8106 EVT TruncType = LS.Inst->getValueType(0);
8107 EVT LoadedType = LS.getLoadedType();
8108 if (TruncType != LoadedType &&
8109 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8110 ZExts = 1;
8111 }
8112
8113 /// \brief Account for slicing gain in the current cost.
8114 /// Slicing provide a few gains like removing a shift or a
8115 /// truncate. This method allows to grow the cost of the original
8116 /// load with the gain from this slice.
8117 void addSliceGain(const LoadedSlice &LS) {
8118 // Each slice saves a truncate.
8119 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8120 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8121 LS.Inst->getOperand(0).getValueType()))
8122 ++Truncates;
8123 // If there is a shift amount, this slice gets rid of it.
8124 if (LS.Shift)
8125 ++Shift;
8126 // If this slice can merge a cross register bank copy, account for it.
8127 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8128 ++CrossRegisterBanksCopies;
8129 }
8130
8131 Cost &operator+=(const Cost &RHS) {
8132 Loads += RHS.Loads;
8133 Truncates += RHS.Truncates;
8134 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8135 ZExts += RHS.ZExts;
8136 Shift += RHS.Shift;
8137 return *this;
8138 }
8139
8140 bool operator==(const Cost &RHS) const {
8141 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8142 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8143 ZExts == RHS.ZExts && Shift == RHS.Shift;
8144 }
8145
8146 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8147
8148 bool operator<(const Cost &RHS) const {
8149 // Assume cross register banks copies are as expensive as loads.
8150 // FIXME: Do we want some more target hooks?
8151 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8152 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8153 // Unless we are optimizing for code size, consider the
8154 // expensive operation first.
8155 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8156 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8157 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8158 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8159 }
8160
8161 bool operator>(const Cost &RHS) const { return RHS < *this; }
8162
8163 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8164
8165 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8166 };
8167 // The last instruction that represent the slice. This should be a
8168 // truncate instruction.
8169 SDNode *Inst;
8170 // The original load instruction.
8171 LoadSDNode *Origin;
8172 // The right shift amount in bits from the original load.
8173 unsigned Shift;
8174 // The DAG from which Origin came from.
8175 // This is used to get some contextual information about legal types, etc.
8176 SelectionDAG *DAG;
8177
Craig Topperc0196b12014-04-14 00:51:57 +00008178 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8179 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008180 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8181
8182 LoadedSlice(const LoadedSlice &LS)
8183 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8184
8185 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8186 /// \return Result is \p BitWidth and has used bits set to 1 and
8187 /// not used bits set to 0.
8188 APInt getUsedBits() const {
8189 // Reproduce the trunc(lshr) sequence:
8190 // - Start from the truncated value.
8191 // - Zero extend to the desired bit width.
8192 // - Shift left.
8193 assert(Origin && "No original load to compare against.");
8194 unsigned BitWidth = Origin->getValueSizeInBits(0);
8195 assert(Inst && "This slice is not bound to an instruction");
8196 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8197 "Extracted slice is bigger than the whole type!");
8198 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8199 UsedBits.setAllBits();
8200 UsedBits = UsedBits.zext(BitWidth);
8201 UsedBits <<= Shift;
8202 return UsedBits;
8203 }
8204
8205 /// \brief Get the size of the slice to be loaded in bytes.
8206 unsigned getLoadedSize() const {
8207 unsigned SliceSize = getUsedBits().countPopulation();
8208 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8209 return SliceSize / 8;
8210 }
8211
8212 /// \brief Get the type that will be loaded for this slice.
8213 /// Note: This may not be the final type for the slice.
8214 EVT getLoadedType() const {
8215 assert(DAG && "Missing context");
8216 LLVMContext &Ctxt = *DAG->getContext();
8217 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8218 }
8219
8220 /// \brief Get the alignment of the load used for this slice.
8221 unsigned getAlignment() const {
8222 unsigned Alignment = Origin->getAlignment();
8223 unsigned Offset = getOffsetFromBase();
8224 if (Offset != 0)
8225 Alignment = MinAlign(Alignment, Alignment + Offset);
8226 return Alignment;
8227 }
8228
8229 /// \brief Check if this slice can be rewritten with legal operations.
8230 bool isLegal() const {
8231 // An invalid slice is not legal.
8232 if (!Origin || !Inst || !DAG)
8233 return false;
8234
8235 // Offsets are for indexed load only, we do not handle that.
8236 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8237 return false;
8238
8239 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8240
8241 // Check that the type is legal.
8242 EVT SliceType = getLoadedType();
8243 if (!TLI.isTypeLegal(SliceType))
8244 return false;
8245
8246 // Check that the load is legal for this type.
8247 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8248 return false;
8249
8250 // Check that the offset can be computed.
8251 // 1. Check its type.
8252 EVT PtrType = Origin->getBasePtr().getValueType();
8253 if (PtrType == MVT::Untyped || PtrType.isExtended())
8254 return false;
8255
8256 // 2. Check that it fits in the immediate.
8257 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8258 return false;
8259
8260 // 3. Check that the computation is legal.
8261 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8262 return false;
8263
8264 // Check that the zext is legal if it needs one.
8265 EVT TruncateType = Inst->getValueType(0);
8266 if (TruncateType != SliceType &&
8267 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8268 return false;
8269
8270 return true;
8271 }
8272
8273 /// \brief Get the offset in bytes of this slice in the original chunk of
8274 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008275 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008276 uint64_t getOffsetFromBase() const {
8277 assert(DAG && "Missing context.");
8278 bool IsBigEndian =
8279 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8280 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8281 uint64_t Offset = Shift / 8;
8282 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8283 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8284 "The size of the original loaded type is not a multiple of a"
8285 " byte.");
8286 // If Offset is bigger than TySizeInBytes, it means we are loading all
8287 // zeros. This should have been optimized before in the process.
8288 assert(TySizeInBytes > Offset &&
8289 "Invalid shift amount for given loaded size");
8290 if (IsBigEndian)
8291 Offset = TySizeInBytes - Offset - getLoadedSize();
8292 return Offset;
8293 }
8294
8295 /// \brief Generate the sequence of instructions to load the slice
8296 /// represented by this object and redirect the uses of this slice to
8297 /// this new sequence of instructions.
8298 /// \pre this->Inst && this->Origin are valid Instructions and this
8299 /// object passed the legal check: LoadedSlice::isLegal returned true.
8300 /// \return The last instruction of the sequence used to load the slice.
8301 SDValue loadSlice() const {
8302 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8303 const SDValue &OldBaseAddr = Origin->getBasePtr();
8304 SDValue BaseAddr = OldBaseAddr;
8305 // Get the offset in that chunk of bytes w.r.t. the endianess.
8306 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8307 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8308 if (Offset) {
8309 // BaseAddr = BaseAddr + Offset.
8310 EVT ArithType = BaseAddr.getValueType();
8311 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8312 DAG->getConstant(Offset, ArithType));
8313 }
8314
8315 // Create the type of the loaded slice according to its size.
8316 EVT SliceType = getLoadedType();
8317
8318 // Create the load for the slice.
8319 SDValue LastInst = DAG->getLoad(
8320 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8321 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8322 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8323 // If the final type is not the same as the loaded type, this means that
8324 // we have to pad with zero. Create a zero extend for that.
8325 EVT FinalType = Inst->getValueType(0);
8326 if (SliceType != FinalType)
8327 LastInst =
8328 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8329 return LastInst;
8330 }
8331
8332 /// \brief Check if this slice can be merged with an expensive cross register
8333 /// bank copy. E.g.,
8334 /// i = load i32
8335 /// f = bitcast i32 i to float
8336 bool canMergeExpensiveCrossRegisterBankCopy() const {
8337 if (!Inst || !Inst->hasOneUse())
8338 return false;
8339 SDNode *Use = *Inst->use_begin();
8340 if (Use->getOpcode() != ISD::BITCAST)
8341 return false;
8342 assert(DAG && "Missing context");
8343 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8344 EVT ResVT = Use->getValueType(0);
8345 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8346 const TargetRegisterClass *ArgRC =
8347 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8348 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8349 return false;
8350
8351 // At this point, we know that we perform a cross-register-bank copy.
8352 // Check if it is expensive.
8353 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8354 // Assume bitcasts are cheap, unless both register classes do not
8355 // explicitly share a common sub class.
8356 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8357 return false;
8358
8359 // Check if it will be merged with the load.
8360 // 1. Check the alignment constraint.
8361 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8362 ResVT.getTypeForEVT(*DAG->getContext()));
8363
8364 if (RequiredAlignment > getAlignment())
8365 return false;
8366
8367 // 2. Check that the load is a legal operation for that type.
8368 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8369 return false;
8370
8371 // 3. Check that we do not have a zext in the way.
8372 if (Inst->getValueType(0) != getLoadedType())
8373 return false;
8374
8375 return true;
8376 }
8377};
8378}
8379
Quentin Colombetde0e0622013-10-11 18:29:42 +00008380/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8381/// \p UsedBits looks like 0..0 1..1 0..0.
8382static bool areUsedBitsDense(const APInt &UsedBits) {
8383 // If all the bits are one, this is dense!
8384 if (UsedBits.isAllOnesValue())
8385 return true;
8386
8387 // Get rid of the unused bits on the right.
8388 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8389 // Get rid of the unused bits on the left.
8390 if (NarrowedUsedBits.countLeadingZeros())
8391 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8392 // Check that the chunk of bits is completely used.
8393 return NarrowedUsedBits.isAllOnesValue();
8394}
8395
8396/// \brief Check whether or not \p First and \p Second are next to each other
8397/// in memory. This means that there is no hole between the bits loaded
8398/// by \p First and the bits loaded by \p Second.
8399static bool areSlicesNextToEachOther(const LoadedSlice &First,
8400 const LoadedSlice &Second) {
8401 assert(First.Origin == Second.Origin && First.Origin &&
8402 "Unable to match different memory origins.");
8403 APInt UsedBits = First.getUsedBits();
8404 assert((UsedBits & Second.getUsedBits()) == 0 &&
8405 "Slices are not supposed to overlap.");
8406 UsedBits |= Second.getUsedBits();
8407 return areUsedBitsDense(UsedBits);
8408}
8409
8410/// \brief Adjust the \p GlobalLSCost according to the target
8411/// paring capabilities and the layout of the slices.
8412/// \pre \p GlobalLSCost should account for at least as many loads as
8413/// there is in the slices in \p LoadedSlices.
8414static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8415 LoadedSlice::Cost &GlobalLSCost) {
8416 unsigned NumberOfSlices = LoadedSlices.size();
8417 // If there is less than 2 elements, no pairing is possible.
8418 if (NumberOfSlices < 2)
8419 return;
8420
8421 // Sort the slices so that elements that are likely to be next to each
8422 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008423 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8424 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8425 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8426 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8427 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008428 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8429 // First (resp. Second) is the first (resp. Second) potentially candidate
8430 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008431 const LoadedSlice *First = nullptr;
8432 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008433 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8434 // Set the beginning of the pair.
8435 First = Second) {
8436
8437 Second = &LoadedSlices[CurrSlice];
8438
8439 // If First is NULL, it means we start a new pair.
8440 // Get to the next slice.
8441 if (!First)
8442 continue;
8443
8444 EVT LoadedType = First->getLoadedType();
8445
8446 // If the types of the slices are different, we cannot pair them.
8447 if (LoadedType != Second->getLoadedType())
8448 continue;
8449
8450 // Check if the target supplies paired loads for this type.
8451 unsigned RequiredAlignment = 0;
8452 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8453 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008454 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008455 continue;
8456 }
8457 // Check if we meet the alignment requirement.
8458 if (RequiredAlignment > First->getAlignment())
8459 continue;
8460
8461 // Check that both loads are next to each other in memory.
8462 if (!areSlicesNextToEachOther(*First, *Second))
8463 continue;
8464
8465 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8466 --GlobalLSCost.Loads;
8467 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008468 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008469 }
8470}
8471
8472/// \brief Check the profitability of all involved LoadedSlice.
8473/// Currently, it is considered profitable if there is exactly two
8474/// involved slices (1) which are (2) next to each other in memory, and
8475/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8476///
8477/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8478/// the elements themselves.
8479///
8480/// FIXME: When the cost model will be mature enough, we can relax
8481/// constraints (1) and (2).
8482static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8483 const APInt &UsedBits, bool ForCodeSize) {
8484 unsigned NumberOfSlices = LoadedSlices.size();
8485 if (StressLoadSlicing)
8486 return NumberOfSlices > 1;
8487
8488 // Check (1).
8489 if (NumberOfSlices != 2)
8490 return false;
8491
8492 // Check (2).
8493 if (!areUsedBitsDense(UsedBits))
8494 return false;
8495
8496 // Check (3).
8497 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8498 // The original code has one big load.
8499 OrigCost.Loads = 1;
8500 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8501 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8502 // Accumulate the cost of all the slices.
8503 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8504 GlobalSlicingCost += SliceCost;
8505
8506 // Account as cost in the original configuration the gain obtained
8507 // with the current slices.
8508 OrigCost.addSliceGain(LS);
8509 }
8510
8511 // If the target supports paired load, adjust the cost accordingly.
8512 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8513 return OrigCost > GlobalSlicingCost;
8514}
8515
8516/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8517/// operations, split it in the various pieces being extracted.
8518///
8519/// This sort of thing is introduced by SROA.
8520/// This slicing takes care not to insert overlapping loads.
8521/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8522bool DAGCombiner::SliceUpLoad(SDNode *N) {
8523 if (Level < AfterLegalizeDAG)
8524 return false;
8525
8526 LoadSDNode *LD = cast<LoadSDNode>(N);
8527 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8528 !LD->getValueType(0).isInteger())
8529 return false;
8530
8531 // Keep track of already used bits to detect overlapping values.
8532 // In that case, we will just abort the transformation.
8533 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8534
8535 SmallVector<LoadedSlice, 4> LoadedSlices;
8536
8537 // Check if this load is used as several smaller chunks of bits.
8538 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8539 // of computation for each trunc.
8540 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8541 UI != UIEnd; ++UI) {
8542 // Skip the uses of the chain.
8543 if (UI.getUse().getResNo() != 0)
8544 continue;
8545
8546 SDNode *User = *UI;
8547 unsigned Shift = 0;
8548
8549 // Check if this is a trunc(lshr).
8550 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8551 isa<ConstantSDNode>(User->getOperand(1))) {
8552 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8553 User = *User->use_begin();
8554 }
8555
8556 // At this point, User is a Truncate, iff we encountered, trunc or
8557 // trunc(lshr).
8558 if (User->getOpcode() != ISD::TRUNCATE)
8559 return false;
8560
8561 // The width of the type must be a power of 2 and greater than 8-bits.
8562 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008563 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008564 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008565 unsigned Width = User->getValueSizeInBits(0);
8566 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8567 return 0;
8568
8569 // Build the slice for this chain of computations.
8570 LoadedSlice LS(User, LD, Shift, &DAG);
8571 APInt CurrentUsedBits = LS.getUsedBits();
8572
8573 // Check if this slice overlaps with another.
8574 if ((CurrentUsedBits & UsedBits) != 0)
8575 return false;
8576 // Update the bits used globally.
8577 UsedBits |= CurrentUsedBits;
8578
8579 // Check if the new slice would be legal.
8580 if (!LS.isLegal())
8581 return false;
8582
8583 // Record the slice.
8584 LoadedSlices.push_back(LS);
8585 }
8586
8587 // Abort slicing if it does not seem to be profitable.
8588 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8589 return false;
8590
8591 ++SlicedLoads;
8592
8593 // Rewrite each chain to use an independent load.
8594 // By construction, each chain can be represented by a unique load.
8595
8596 // Prepare the argument for the new token factor for all the slices.
8597 SmallVector<SDValue, 8> ArgChains;
8598 for (SmallVectorImpl<LoadedSlice>::const_iterator
8599 LSIt = LoadedSlices.begin(),
8600 LSItEnd = LoadedSlices.end();
8601 LSIt != LSItEnd; ++LSIt) {
8602 SDValue SliceInst = LSIt->loadSlice();
8603 CombineTo(LSIt->Inst, SliceInst, true);
8604 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8605 SliceInst = SliceInst.getOperand(0);
8606 assert(SliceInst->getOpcode() == ISD::LOAD &&
8607 "It takes more than a zext to get to the loaded slice!!");
8608 ArgChains.push_back(SliceInst.getValue(1));
8609 }
8610
8611 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008612 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008613 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8614 return true;
8615}
8616
Chris Lattner4041ab62010-04-15 04:48:01 +00008617/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8618/// load is having specific bytes cleared out. If so, return the byte size
8619/// being masked out and the shift amount.
8620static std::pair<unsigned, unsigned>
8621CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8622 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008623
Chris Lattner4041ab62010-04-15 04:48:01 +00008624 // Check for the structure we're looking for.
8625 if (V->getOpcode() != ISD::AND ||
8626 !isa<ConstantSDNode>(V->getOperand(1)) ||
8627 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8628 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008629
Chris Lattner3245afd2010-04-15 06:10:49 +00008630 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008631 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008632 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008633
Chris Lattner3245afd2010-04-15 06:10:49 +00008634 // The store should be chained directly to the load or be an operand of a
8635 // tokenfactor.
8636 if (LD == Chain.getNode())
8637 ; // ok.
8638 else if (Chain->getOpcode() != ISD::TokenFactor)
8639 return Result; // Fail.
8640 else {
8641 bool isOk = false;
8642 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8643 if (Chain->getOperand(i).getNode() == LD) {
8644 isOk = true;
8645 break;
8646 }
8647 if (!isOk) return Result;
8648 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008649
Chris Lattner4041ab62010-04-15 04:48:01 +00008650 // This only handles simple types.
8651 if (V.getValueType() != MVT::i16 &&
8652 V.getValueType() != MVT::i32 &&
8653 V.getValueType() != MVT::i64)
8654 return Result;
8655
8656 // Check the constant mask. Invert it so that the bits being masked out are
8657 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8658 // follow the sign bit for uniformity.
8659 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008660 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008661 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008662 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008663 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8664 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008665
Chris Lattner4041ab62010-04-15 04:48:01 +00008666 // See if we have a continuous run of bits. If so, we have 0*1+0*
8667 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8668 return Result;
8669
8670 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8671 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8672 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008673
Chris Lattner4041ab62010-04-15 04:48:01 +00008674 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8675 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008676 case 1:
8677 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008678 case 4: break;
8679 default: return Result; // All one mask, or 5-byte mask.
8680 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008681
Chris Lattner4041ab62010-04-15 04:48:01 +00008682 // Verify that the first bit starts at a multiple of mask so that the access
8683 // is aligned the same as the access width.
8684 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008685
Chris Lattner4041ab62010-04-15 04:48:01 +00008686 Result.first = MaskedBytes;
8687 Result.second = NotMaskTZ/8;
8688 return Result;
8689}
8690
8691
8692/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8693/// provides a value as specified by MaskInfo. If so, replace the specified
8694/// store with a narrower store of truncated IVal.
8695static SDNode *
8696ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8697 SDValue IVal, StoreSDNode *St,
8698 DAGCombiner *DC) {
8699 unsigned NumBytes = MaskInfo.first;
8700 unsigned ByteShift = MaskInfo.second;
8701 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008702
Chris Lattner4041ab62010-04-15 04:48:01 +00008703 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8704 // that uses this. If not, this is not a replacement.
8705 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8706 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008707 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008708
Chris Lattner4041ab62010-04-15 04:48:01 +00008709 // Check that it is legal on the target to do this. It is legal if the new
8710 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8711 // legalization.
8712 MVT VT = MVT::getIntegerVT(NumBytes*8);
8713 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008714 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008715
Chris Lattner4041ab62010-04-15 04:48:01 +00008716 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8717 // shifted by ByteShift and truncated down to NumBytes.
8718 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008719 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008720 DAG.getConstant(ByteShift*8,
8721 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008722
8723 // Figure out the offset for the store and the alignment of the access.
8724 unsigned StOffset;
8725 unsigned NewAlign = St->getAlignment();
8726
8727 if (DAG.getTargetLoweringInfo().isLittleEndian())
8728 StOffset = ByteShift;
8729 else
8730 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008731
Chris Lattner4041ab62010-04-15 04:48:01 +00008732 SDValue Ptr = St->getBasePtr();
8733 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008734 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008735 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8736 NewAlign = MinAlign(NewAlign, StOffset);
8737 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008738
Chris Lattner4041ab62010-04-15 04:48:01 +00008739 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008740 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008741
Chris Lattner4041ab62010-04-15 04:48:01 +00008742 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008743 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008744 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008745 false, false, NewAlign).getNode();
8746}
8747
Evan Chenga9cda8a2009-05-28 00:35:15 +00008748
8749/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8750/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8751/// of the loaded bits, try narrowing the load and store if it would end up
8752/// being a win for performance or code size.
8753SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8754 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008755 if (ST->isVolatile())
8756 return SDValue();
8757
Evan Chenga9cda8a2009-05-28 00:35:15 +00008758 SDValue Chain = ST->getChain();
8759 SDValue Value = ST->getValue();
8760 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008761 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008762
8763 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008764 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008765
8766 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008767
Chris Lattner4041ab62010-04-15 04:48:01 +00008768 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8769 // is a byte mask indicating a consecutive number of bytes, check to see if
8770 // Y is known to provide just those bytes. If so, we try to replace the
8771 // load + replace + store sequence with a single (narrower) store, which makes
8772 // the load dead.
8773 if (Opc == ISD::OR) {
8774 std::pair<unsigned, unsigned> MaskedLoad;
8775 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8776 if (MaskedLoad.first)
8777 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8778 Value.getOperand(1), ST,this))
8779 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008780
Chris Lattner4041ab62010-04-15 04:48:01 +00008781 // Or is commutative, so try swapping X and Y.
8782 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8783 if (MaskedLoad.first)
8784 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8785 Value.getOperand(0), ST,this))
8786 return SDValue(NewST, 0);
8787 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008788
Evan Chenga9cda8a2009-05-28 00:35:15 +00008789 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8790 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008791 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008792
8793 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008794 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8795 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008796 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008797 if (LD->getBasePtr() != Ptr ||
8798 LD->getPointerInfo().getAddrSpace() !=
8799 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008800 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008801
8802 // Find the type to narrow it the load / op / store to.
8803 SDValue N1 = Value.getOperand(1);
8804 unsigned BitWidth = N1.getValueSizeInBits();
8805 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8806 if (Opc == ISD::AND)
8807 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008808 if (Imm == 0 || Imm.isAllOnesValue())
8809 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008810 unsigned ShAmt = Imm.countTrailingZeros();
8811 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8812 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008813 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008814 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008815 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008816 TLI.isNarrowingProfitable(VT, NewVT))) {
8817 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008818 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008819 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008820 if (NewBW >= BitWidth)
8821 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008822
8823 // If the lsb changed does not start at the type bitwidth boundary,
8824 // start at the previous one.
8825 if (ShAmt % NewBW)
8826 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008827 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8828 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008829 if ((Imm & Mask) == Imm) {
8830 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8831 if (Opc == ISD::AND)
8832 NewImm ^= APInt::getAllOnesValue(NewBW);
8833 uint64_t PtrOff = ShAmt / 8;
8834 // For big endian targets, we need to adjust the offset to the pointer to
8835 // load the correct bytes.
8836 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008837 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008838
8839 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008840 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008841 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008842 return SDValue();
8843
Andrew Trickef9de2a2013-05-25 02:42:55 +00008844 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008845 Ptr.getValueType(), Ptr,
8846 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008847 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008848 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008849 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008850 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008851 LD->isInvariant(), NewAlign,
8852 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008853 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008854 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008855 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008856 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008857 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008858 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008859
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008860 AddToWorklist(NewPtr.getNode());
8861 AddToWorklist(NewLD.getNode());
8862 AddToWorklist(NewVal.getNode());
8863 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008864 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008865 ++OpsNarrowed;
8866 return NewST;
8867 }
8868 }
8869
Evan Cheng6673ff02009-05-28 18:41:02 +00008870 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008871}
8872
Evan Chengd42641c2011-02-02 01:06:55 +00008873/// TransformFPLoadStorePair - For a given floating point load / store pair,
8874/// if the load value isn't used by any other operations, then consider
8875/// transforming the pair to integer load / store operations if the target
8876/// deems the transformation profitable.
8877SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8878 StoreSDNode *ST = cast<StoreSDNode>(N);
8879 SDValue Chain = ST->getChain();
8880 SDValue Value = ST->getValue();
8881 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8882 Value.hasOneUse() &&
8883 Chain == SDValue(Value.getNode(), 1)) {
8884 LoadSDNode *LD = cast<LoadSDNode>(Value);
8885 EVT VT = LD->getMemoryVT();
8886 if (!VT.isFloatingPoint() ||
8887 VT != ST->getMemoryVT() ||
8888 LD->isNonTemporal() ||
8889 ST->isNonTemporal() ||
8890 LD->getPointerInfo().getAddrSpace() != 0 ||
8891 ST->getPointerInfo().getAddrSpace() != 0)
8892 return SDValue();
8893
8894 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8895 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8896 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8897 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8898 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8899 return SDValue();
8900
8901 unsigned LDAlign = LD->getAlignment();
8902 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008903 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008904 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008905 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8906 return SDValue();
8907
Andrew Trickef9de2a2013-05-25 02:42:55 +00008908 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008909 LD->getChain(), LD->getBasePtr(),
8910 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008911 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008912
Andrew Trickef9de2a2013-05-25 02:42:55 +00008913 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008914 NewLD, ST->getBasePtr(),
8915 ST->getPointerInfo(),
8916 false, false, STAlign);
8917
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008918 AddToWorklist(NewLD.getNode());
8919 AddToWorklist(NewST.getNode());
8920 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008921 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008922 ++LdStFP2Int;
8923 return NewST;
8924 }
8925
8926 return SDValue();
8927}
8928
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008929/// Helper struct to parse and store a memory address as base + index + offset.
8930/// We ignore sign extensions when it is safe to do so.
8931/// The following two expressions are not equivalent. To differentiate we need
8932/// to store whether there was a sign extension involved in the index
8933/// computation.
8934/// (load (i64 add (i64 copyfromreg %c)
8935/// (i64 signextend (add (i8 load %index)
8936/// (i8 1))))
8937/// vs
8938///
8939/// (load (i64 add (i64 copyfromreg %c)
8940/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8941/// (i32 1)))))
8942struct BaseIndexOffset {
8943 SDValue Base;
8944 SDValue Index;
8945 int64_t Offset;
8946 bool IsIndexSignExt;
8947
8948 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8949
8950 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8951 bool IsIndexSignExt) :
8952 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8953
8954 bool equalBaseIndex(const BaseIndexOffset &Other) {
8955 return Other.Base == Base && Other.Index == Index &&
8956 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008957 }
8958
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008959 /// Parses tree in Ptr for base, index, offset addresses.
8960 static BaseIndexOffset match(SDValue Ptr) {
8961 bool IsIndexSignExt = false;
8962
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008963 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8964 // instruction, then it could be just the BASE or everything else we don't
8965 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008966 if (Ptr->getOpcode() != ISD::ADD)
8967 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8968
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008969 // We know that we have at least an ADD instruction. Try to pattern match
8970 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008971 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8972 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8973 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8974 IsIndexSignExt);
8975 }
8976
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008977 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008978 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008979 // (i64 add (i64 %array_ptr)
8980 // (i64 mul (i64 %induction_var)
8981 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008982 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008983 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008984
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008985 // Look at Base + Index + Offset cases.
8986 SDValue Base = Ptr->getOperand(0);
8987 SDValue IndexOffset = Ptr->getOperand(1);
8988
8989 // Skip signextends.
8990 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8991 IndexOffset = IndexOffset->getOperand(0);
8992 IsIndexSignExt = true;
8993 }
8994
8995 // Either the case of Base + Index (no offset) or something else.
8996 if (IndexOffset->getOpcode() != ISD::ADD)
8997 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8998
8999 // Now we have the case of Base + Index + offset.
9000 SDValue Index = IndexOffset->getOperand(0);
9001 SDValue Offset = IndexOffset->getOperand(1);
9002
9003 if (!isa<ConstantSDNode>(Offset))
9004 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9005
9006 // Ignore signextends.
9007 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9008 Index = Index->getOperand(0);
9009 IsIndexSignExt = true;
9010 } else IsIndexSignExt = false;
9011
9012 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9013 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9014 }
9015};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009016
9017/// Holds a pointer to an LSBaseSDNode as well as information on where it
9018/// is located in a sequence of memory operations connected by a chain.
9019struct MemOpLink {
9020 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9021 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9022 // Ptr to the mem node.
9023 LSBaseSDNode *MemNode;
9024 // Offset from the base ptr.
9025 int64_t OffsetFromBase;
9026 // What is the sequence number of this mem node.
9027 // Lowest mem operand in the DAG starts at zero.
9028 unsigned SequenceNum;
9029};
9030
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009031bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9032 EVT MemVT = St->getMemoryVT();
9033 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009034 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9035 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009036
9037 // Don't merge vectors into wider inputs.
9038 if (MemVT.isVector() || !MemVT.isSimple())
9039 return false;
9040
9041 // Perform an early exit check. Do not bother looking at stored values that
9042 // are not constants or loads.
9043 SDValue StoredVal = St->getValue();
9044 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9045 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9046 !IsLoadSrc)
9047 return false;
9048
9049 // Only look at ends of store sequences.
9050 SDValue Chain = SDValue(St, 1);
9051 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9052 return false;
9053
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009054 // This holds the base pointer, index, and the offset in bytes from the base
9055 // pointer.
9056 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009057
9058 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009059 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009060 return false;
9061
9062 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009063 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009064 return false;
9065
Nadav Rotem307d7672012-11-29 00:00:08 +00009066 // Save the LoadSDNodes that we find in the chain.
9067 // We need to make sure that these nodes do not interfere with
9068 // any of the store nodes.
9069 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9070
9071 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009072 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009073
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009074 // Walk up the chain and look for nodes with offsets from the same
9075 // base pointer. Stop when reaching an instruction with a different kind
9076 // or instruction which has a different base pointer.
9077 unsigned Seq = 0;
9078 StoreSDNode *Index = St;
9079 while (Index) {
9080 // If the chain has more than one use, then we can't reorder the mem ops.
9081 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9082 break;
9083
9084 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009085 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009086
9087 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009088 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009089 break;
9090
9091 // Check that the alignment is the same.
9092 if (Index->getAlignment() != St->getAlignment())
9093 break;
9094
9095 // The memory operands must not be volatile.
9096 if (Index->isVolatile() || Index->isIndexed())
9097 break;
9098
9099 // No truncation.
9100 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9101 if (St->isTruncatingStore())
9102 break;
9103
9104 // The stored memory type must be the same.
9105 if (Index->getMemoryVT() != MemVT)
9106 break;
9107
9108 // We do not allow unaligned stores because we want to prevent overriding
9109 // stores.
9110 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9111 break;
9112
9113 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009114 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009115
Nadav Rotem307d7672012-11-29 00:00:08 +00009116 // Find the next memory operand in the chain. If the next operand in the
9117 // chain is a store then move up and continue the scan with the next
9118 // memory operand. If the next operand is a load save it and use alias
9119 // information to check if it interferes with anything.
9120 SDNode *NextInChain = Index->getChain().getNode();
9121 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009122 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009123 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009124 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009125 break;
9126 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009127 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009128 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009129 break;
9130 }
9131
Nadav Rotem307d7672012-11-29 00:00:08 +00009132 // Save the load node for later. Continue the scan.
9133 AliasLoadNodes.push_back(Ldn);
9134 NextInChain = Ldn->getChain().getNode();
9135 continue;
9136 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009137 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009138 break;
9139 }
9140 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009141 }
9142
9143 // Check if there is anything to merge.
9144 if (StoreNodes.size() < 2)
9145 return false;
9146
9147 // Sort the memory operands according to their distance from the base pointer.
9148 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009149 [](MemOpLink LHS, MemOpLink RHS) {
9150 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9151 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9152 LHS.SequenceNum > RHS.SequenceNum);
9153 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009154
9155 // Scan the memory operations on the chain and find the first non-consecutive
9156 // store memory address.
9157 unsigned LastConsecutiveStore = 0;
9158 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009159 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9160
9161 // Check that the addresses are consecutive starting from the second
9162 // element in the list of stores.
9163 if (i > 0) {
9164 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9165 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9166 break;
9167 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009168
Nadav Rotem307d7672012-11-29 00:00:08 +00009169 bool Alias = false;
9170 // Check if this store interferes with any of the loads that we found.
9171 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9172 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9173 Alias = true;
9174 break;
9175 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009176 // We found a load that alias with this store. Stop the sequence.
9177 if (Alias)
9178 break;
9179
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009180 // Mark this node as useful.
9181 LastConsecutiveStore = i;
9182 }
9183
9184 // The node with the lowest store address.
9185 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9186
9187 // Store the constants into memory as one consecutive store.
9188 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009189 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009190 unsigned LastLegalVectorType = 0;
9191 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009192 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9193 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9194 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009195
9196 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009197 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009198 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009199 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009200 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009201 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009202 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009203 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009204
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009205 // Find a legal type for the constant store.
9206 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9207 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9208 if (TLI.isTypeLegal(StoreTy))
9209 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009210 // Or check whether a truncstore is legal.
9211 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9212 TargetLowering::TypePromoteInteger) {
9213 EVT LegalizedStoredValueTy =
9214 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9215 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9216 LastLegalType = i+1;
9217 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009218
9219 // Find a legal type for the vector store.
9220 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9221 if (TLI.isTypeLegal(Ty))
9222 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009223 }
9224
Bob Wilson3365b802012-12-20 01:36:20 +00009225 // We only use vectors if the constant is known to be zero and the
9226 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009227 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009228 LastLegalVectorType = 0;
9229
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009230 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009231 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009232 return false;
9233
Nadav Rotem495b1a42013-02-14 18:28:52 +00009234 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009235 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9236
9237 // Make sure we have something to merge.
9238 if (NumElem < 2)
9239 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009240
9241 unsigned EarliestNodeUsed = 0;
9242 for (unsigned i=0; i < NumElem; ++i) {
9243 // Find a chain for the new wide-store operand. Notice that some
9244 // of the store nodes that we found may not be selected for inclusion
9245 // in the wide store. The chain we use needs to be the chain of the
9246 // earliest store node which is *used* and replaced by the wide store.
9247 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9248 EarliestNodeUsed = i;
9249 }
9250
9251 // The earliest Node in the DAG.
9252 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009253 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009254
Nadav Rotemb27777f2012-10-04 22:35:15 +00009255 SDValue StoredVal;
9256 if (UseVector) {
9257 // Find a legal type for the vector store.
9258 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9259 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9260 StoredVal = DAG.getConstant(0, Ty);
9261 } else {
9262 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9263 APInt StoreInt(StoreBW, 0);
9264
9265 // Construct a single integer constant which is made of the smaller
9266 // constant inputs.
9267 bool IsLE = TLI.isLittleEndian();
9268 for (unsigned i = 0; i < NumElem ; ++i) {
9269 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9270 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9271 SDValue Val = St->getValue();
9272 StoreInt<<=ElementSizeBytes*8;
9273 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9274 StoreInt|=C->getAPIntValue().zext(StoreBW);
9275 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9276 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9277 } else {
9278 assert(false && "Invalid constant element type");
9279 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009280 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009281
9282 // Create the new Load and Store operations.
9283 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9284 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009285 }
9286
Nadav Rotemb27777f2012-10-04 22:35:15 +00009287 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009288 FirstInChain->getBasePtr(),
9289 FirstInChain->getPointerInfo(),
9290 false, false,
9291 FirstInChain->getAlignment());
9292
9293 // Replace the first store with the new store
9294 CombineTo(EarliestOp, NewStore);
9295 // Erase all other stores.
9296 for (unsigned i = 0; i < NumElem ; ++i) {
9297 if (StoreNodes[i].MemNode == EarliestOp)
9298 continue;
9299 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009300 // ReplaceAllUsesWith will replace all uses that existed when it was
9301 // called, but graph optimizations may cause new ones to appear. For
9302 // example, the case in pr14333 looks like
9303 //
9304 // St's chain -> St -> another store -> X
9305 //
9306 // And the only difference from St to the other store is the chain.
9307 // When we change it's chain to be St's chain they become identical,
9308 // get CSEed and the net result is that X is now a use of St.
9309 // Since we know that St is redundant, just iterate.
9310 while (!St->use_empty())
9311 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009312 removeFromWorklist(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009313 DAG.DeleteNode(St);
9314 }
9315
9316 return true;
9317 }
9318
9319 // Below we handle the case of multiple consecutive stores that
9320 // come from multiple consecutive loads. We merge them into a single
9321 // wide load and a single wide store.
9322
9323 // Look for load nodes which are used by the stored values.
9324 SmallVector<MemOpLink, 8> LoadNodes;
9325
9326 // Find acceptable loads. Loads need to have the same chain (token factor),
9327 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009328 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009329 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9330 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9331 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9332 if (!Ld) break;
9333
9334 // Loads must only have one use.
9335 if (!Ld->hasNUsesOfValue(1, 0))
9336 break;
9337
9338 // Check that the alignment is the same as the stores.
9339 if (Ld->getAlignment() != St->getAlignment())
9340 break;
9341
9342 // The memory operands must not be volatile.
9343 if (Ld->isVolatile() || Ld->isIndexed())
9344 break;
9345
9346 // We do not accept ext loads.
9347 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9348 break;
9349
9350 // The stored memory type must be the same.
9351 if (Ld->getMemoryVT() != MemVT)
9352 break;
9353
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009354 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009355 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009356 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009357 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009358 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009359 break;
9360 } else {
9361 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009362 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009363 }
9364
9365 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009366 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009367 }
9368
9369 if (LoadNodes.size() < 2)
9370 return false;
9371
9372 // Scan the memory operations on the chain and find the first non-consecutive
9373 // load memory address. These variables hold the index in the store node
9374 // array.
9375 unsigned LastConsecutiveLoad = 0;
9376 // This variable refers to the size and not index in the array.
9377 unsigned LastLegalVectorType = 0;
9378 unsigned LastLegalIntegerType = 0;
9379 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009380 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9381 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9382 // All loads much share the same chain.
9383 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9384 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009385
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009386 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9387 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9388 break;
9389 LastConsecutiveLoad = i;
9390
9391 // Find a legal type for the vector store.
9392 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9393 if (TLI.isTypeLegal(StoreTy))
9394 LastLegalVectorType = i + 1;
9395
9396 // Find a legal type for the integer store.
9397 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9398 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9399 if (TLI.isTypeLegal(StoreTy))
9400 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009401 // Or check whether a truncstore and extload is legal.
9402 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9403 TargetLowering::TypePromoteInteger) {
9404 EVT LegalizedStoredValueTy =
9405 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9406 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9407 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9408 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9409 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9410 LastLegalIntegerType = i+1;
9411 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009412 }
9413
9414 // Only use vector types if the vector type is larger than the integer type.
9415 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009416 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009417 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9418
9419 // We add +1 here because the LastXXX variables refer to location while
9420 // the NumElem refers to array/index size.
9421 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9422 NumElem = std::min(LastLegalType, NumElem);
9423
9424 if (NumElem < 2)
9425 return false;
9426
9427 // The earliest Node in the DAG.
9428 unsigned EarliestNodeUsed = 0;
9429 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9430 for (unsigned i=1; i<NumElem; ++i) {
9431 // Find a chain for the new wide-store operand. Notice that some
9432 // of the store nodes that we found may not be selected for inclusion
9433 // in the wide store. The chain we use needs to be the chain of the
9434 // earliest store node which is *used* and replaced by the wide store.
9435 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9436 EarliestNodeUsed = i;
9437 }
9438
9439 // Find if it is better to use vectors or integers to load and store
9440 // to memory.
9441 EVT JointMemOpVT;
9442 if (UseVectorTy) {
9443 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9444 } else {
9445 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9446 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9447 }
9448
Andrew Trickef9de2a2013-05-25 02:42:55 +00009449 SDLoc LoadDL(LoadNodes[0].MemNode);
9450 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009451
9452 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9453 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9454 FirstLoad->getChain(),
9455 FirstLoad->getBasePtr(),
9456 FirstLoad->getPointerInfo(),
9457 false, false, false,
9458 FirstLoad->getAlignment());
9459
9460 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9461 FirstInChain->getBasePtr(),
9462 FirstInChain->getPointerInfo(), false, false,
9463 FirstInChain->getAlignment());
9464
Nadav Rotemac920662012-10-03 19:30:31 +00009465 // Replace one of the loads with the new load.
9466 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9467 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9468 SDValue(NewLoad.getNode(), 1));
9469
9470 // Remove the rest of the load chains.
9471 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009472 // Replace all chain users of the old load nodes with the chain of the new
9473 // load node.
9474 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009475 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9476 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009477
Nadav Rotemac920662012-10-03 19:30:31 +00009478 // Replace the first store with the new store.
9479 CombineTo(EarliestOp, NewStore);
9480 // Erase all other stores.
9481 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009482 // Remove all Store nodes.
9483 if (StoreNodes[i].MemNode == EarliestOp)
9484 continue;
9485 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9486 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009487 removeFromWorklist(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009488 DAG.DeleteNode(St);
9489 }
9490
9491 return true;
9492}
9493
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009494SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009495 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009496 SDValue Chain = ST->getChain();
9497 SDValue Value = ST->getValue();
9498 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009499
Evan Chenga4cf58a2007-05-07 21:27:48 +00009500 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009501 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009502 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009503 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009504 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009505 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009506 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009507 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009508 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009509 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009510 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009511 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009512 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009513 ST->isNonTemporal(), OrigAlign,
9514 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009515 }
Owen Andersona5192842011-04-14 17:30:49 +00009516
Chris Lattner41c80e82011-04-09 02:32:02 +00009517 // Turn 'store undef, Ptr' -> nothing.
9518 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9519 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009520
Nate Begeman8e20c762006-12-11 02:23:46 +00009521 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009522 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009523 // NOTE: If the original store is volatile, this transform must not increase
9524 // the number of stores. For example, on x86-32 an f64 can be stored in one
9525 // processor operation but an i64 (which is not legal) requires two. So the
9526 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009527 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009528 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009529 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009530 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009531 case MVT::f16: // We don't do this for these yet.
9532 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009533 case MVT::f128:
9534 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009535 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009536 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009537 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009538 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009539 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009540 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009541 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009542 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009543 }
9544 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009545 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009546 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009547 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009548 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009549 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009550 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009551 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009552 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009553 }
Owen Andersona5192842011-04-14 17:30:49 +00009554
Chris Lattner41c80e82011-04-09 02:32:02 +00009555 if (!ST->isVolatile() &&
9556 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009557 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009558 // argument passing. Since this is so common, custom legalize the
9559 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009560 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009561 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9562 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009563 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009564
Dan Gohman2af30632007-07-09 22:18:38 +00009565 unsigned Alignment = ST->getAlignment();
9566 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009567 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009568 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009569
Andrew Trickef9de2a2013-05-25 02:42:55 +00009570 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009571 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009572 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009573 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009574 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009575 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009576 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009577 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009578 Ptr, ST->getPointerInfo().getWithOffset(4),
9579 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009580 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009581 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009582 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009583 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009584
Chris Lattnerb7524b62006-12-12 04:16:14 +00009585 break;
Evan Cheng21836982006-12-11 17:25:19 +00009586 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009587 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009588 }
9589
Evan Cheng43cd9e32010-04-01 06:04:33 +00009590 // Try to infer better alignment information than the store already has.
9591 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009592 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9593 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009594 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009595 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009596 ST->isVolatile(), ST->isNonTemporal(), Align,
9597 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009598 }
9599 }
9600
Evan Chengd42641c2011-02-02 01:06:55 +00009601 // Try transforming a pair floating point load / store ops to integer
9602 // load / store ops.
9603 SDValue NewST = TransformFPLoadStorePair(N);
9604 if (NewST.getNode())
9605 return NewST;
9606
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009607 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9608 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009609#ifndef NDEBUG
9610 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9611 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9612 UseAA = false;
9613#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009614 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009615 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009616 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009617
Jim Laskey708d0db2006-10-04 16:53:27 +00009618 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009619 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009620 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009621
9622 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009623 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009624 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009625 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009626 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009627 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009628 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009629 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009630
Jim Laskeyd07be232006-09-25 16:29:54 +00009631 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009632 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009633 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009634
Nate Begeman879d8f12009-09-15 00:18:30 +00009635 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009636 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +00009637
Jim Laskeydcf983c2006-10-13 23:32:28 +00009638 // Don't add users to work list.
9639 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009640 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009641 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009642
Evan Cheng33157702006-11-05 09:31:14 +00009643 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009644 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009645 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009646
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009647 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009648 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009649 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009650 // See if we can simplify the input to this truncstore with knowledge that
9651 // only the low bits are being used. For example:
9652 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009653 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009654 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009655 APInt::getLowBitsSet(
9656 Value.getValueType().getScalarType().getSizeInBits(),
9657 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009658 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00009659 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009660 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009661 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009662
Chris Lattnerf47e3062007-10-13 06:58:48 +00009663 // Otherwise, see if we can simplify the operation with
9664 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009665 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009666 APInt::getLowBitsSet(
9667 Value.getValueType().getScalarType().getSizeInBits(),
9668 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009669 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009670 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009671
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009672 // If this is a load followed by a store to the same location, then the store
9673 // is dead/noop.
9674 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009675 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009676 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009677 // There can't be any side effects between the load and store, such as
9678 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009679 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009680 // The store is dead, remove it.
9681 return Chain;
9682 }
9683 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009684
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009685 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9686 // truncating store. We can do this even if this is already a truncstore.
9687 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009688 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009689 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009690 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009691 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009692 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009693 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009694
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009695 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009696 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009697 if (!LegalTypes) {
9698 bool EverChanged = false;
9699
9700 do {
9701 // There can be multiple store sequences on the same chain.
9702 // Keep trying to merge store sequences until we are unable to do so
9703 // or until we merge the last store on the chain.
9704 bool Changed = MergeConsecutiveStores(ST);
9705 EverChanged |= Changed;
9706 if (!Changed) break;
9707 } while (ST->getOpcode() != ISD::DELETED_NODE);
9708
9709 if (EverChanged)
9710 return SDValue(N, 0);
9711 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009712
Evan Chenga9cda8a2009-05-28 00:35:15 +00009713 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009714}
9715
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009716SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9717 SDValue InVec = N->getOperand(0);
9718 SDValue InVal = N->getOperand(1);
9719 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009720 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009721
Bob Wilson42603952010-05-19 23:42:58 +00009722 // If the inserted element is an UNDEF, just use the input vector.
9723 if (InVal.getOpcode() == ISD::UNDEF)
9724 return InVec;
9725
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009726 EVT VT = InVec.getValueType();
9727
Owen Andersonb2c80da2011-02-25 21:41:48 +00009728 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009729 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9730 return SDValue();
9731
Eli Friedmanb7910b72011-09-09 21:04:06 +00009732 // Check that we know which element is being inserted
9733 if (!isa<ConstantSDNode>(EltNo))
9734 return SDValue();
9735 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009736
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009737 // Canonicalize insert_vector_elt dag nodes.
9738 // Example:
9739 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9740 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9741 //
9742 // Do this only if the child insert_vector node has one use; also
9743 // do this only if indices are both constants and Idx1 < Idx0.
9744 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9745 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9746 unsigned OtherElt =
9747 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9748 if (Elt < OtherElt) {
9749 // Swap nodes.
9750 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9751 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009752 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009753 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9754 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9755 }
9756 }
9757
Eli Friedmanb7910b72011-09-09 21:04:06 +00009758 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9759 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9760 // vector elements.
9761 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009762 // Do not combine these two vectors if the output vector will not replace
9763 // the input vector.
9764 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009765 Ops.append(InVec.getNode()->op_begin(),
9766 InVec.getNode()->op_end());
9767 } else if (InVec.getOpcode() == ISD::UNDEF) {
9768 unsigned NElts = VT.getVectorNumElements();
9769 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9770 } else {
9771 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009772 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009773
9774 // Insert the element
9775 if (Elt < Ops.size()) {
9776 // All the operands of BUILD_VECTOR must have the same type;
9777 // we enforce that here.
9778 EVT OpVT = Ops[0].getValueType();
9779 if (InVal.getValueType() != OpVT)
9780 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9781 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9782 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9783 Ops[Elt] = InVal;
9784 }
9785
9786 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009787 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009788}
9789
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009790SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009791 // (vextract (scalar_to_vector val, 0) -> val
9792 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009793 EVT VT = InVec.getValueType();
9794 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009795
Duncan Sands6be291a2011-05-09 08:03:33 +00009796 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9797 // Check if the result type doesn't match the inserted element type. A
9798 // SCALAR_TO_VECTOR may truncate the inserted element and the
9799 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9800 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009801 if (InOp.getValueType() != NVT) {
9802 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009803 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009804 }
9805 return InOp;
9806 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009807
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009808 SDValue EltNo = N->getOperand(1);
9809 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9810
9811 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9812 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009813 // we may introduce new vector instructions which are not backed by TD
9814 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009815 // without using extract_subvector. However, if we can find an underlying
9816 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009817 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009818 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009819 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9820 int NumElem = VT.getVectorNumElements();
9821 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9822 // Find the new index to extract from.
9823 int OrigElt = SVOp->getMaskElt(Elt);
9824
9825 // Extracting an undef index is undef.
9826 if (OrigElt == -1)
9827 return DAG.getUNDEF(NVT);
9828
9829 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009830 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009831 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009832 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009833 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009834 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009835 OrigElt -= NumElem;
9836 }
9837
Hal Finkel02807592014-03-31 11:43:19 +00009838 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9839 SDValue InOp = SVInVec.getOperand(OrigElt);
9840 if (InOp.getValueType() != NVT) {
9841 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9842 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9843 }
9844
9845 return InOp;
9846 }
9847
9848 // FIXME: We should handle recursing on other vector shuffles and
9849 // scalar_to_vector here as well.
9850
9851 if (!LegalOperations) {
9852 EVT IndexTy = TLI.getVectorIdxTy();
9853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9854 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9855 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009856 }
9857
Evan Cheng1120279a2008-05-13 08:35:03 +00009858 // Perform only after legalization to ensure build_vector / vector_shuffle
9859 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009860 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009861
Mon P Wangca6d6de2009-01-17 00:07:25 +00009862 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9863 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9864 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009865
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009866 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009867 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Michael J. Spencer1eb02302014-07-18 00:15:50 +00009868 bool NewLoad = false;
9869 bool BCNumEltsChanged = false;
9870 EVT ExtVT = VT.getVectorElementType();
9871 EVT LVT = ExtVT;
9872
9873 // If the result of load has to be truncated, then it's not necessarily
9874 // profitable.
9875 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9876 return SDValue();
9877
9878 if (InVec.getOpcode() == ISD::BITCAST) {
9879 // Don't duplicate a load with other uses.
9880 if (!InVec.hasOneUse())
9881 return SDValue();
9882
9883 EVT BCVT = InVec.getOperand(0).getValueType();
9884 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9885 return SDValue();
9886 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9887 BCNumEltsChanged = true;
9888 InVec = InVec.getOperand(0);
9889 ExtVT = BCVT.getVectorElementType();
9890 NewLoad = true;
9891 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009892
Craig Topperc0196b12014-04-14 00:51:57 +00009893 LoadSDNode *LN0 = nullptr;
9894 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009895 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009896 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009897 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009898 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009899 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009900 // Don't duplicate a load with other uses.
9901 if (!InVec.hasOneUse())
9902 return SDValue();
9903
Evan Cheng1120279a2008-05-13 08:35:03 +00009904 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009905 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009906 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9907 // =>
9908 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009909
Eli Friedmane96286c2011-12-26 22:49:32 +00009910 // Don't duplicate a load with other uses.
9911 if (!InVec.hasOneUse())
9912 return SDValue();
9913
Mon P Wangb5eb7202008-12-11 00:26:16 +00009914 // If the bit convert changed the number of elements, it is unsafe
9915 // to examine the mask.
9916 if (BCNumEltsChanged)
9917 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009918
9919 // Select the input vector, guarding against out of range extract vector.
9920 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009921 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009922 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9923
Eli Friedmane96286c2011-12-26 22:49:32 +00009924 if (InVec.getOpcode() == ISD::BITCAST) {
9925 // Don't duplicate a load with other uses.
9926 if (!InVec.hasOneUse())
9927 return SDValue();
9928
Evan Cheng1120279a2008-05-13 08:35:03 +00009929 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009930 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009931 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009932 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009933 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009934 }
9935 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009936
Eli Friedmane96286c2011-12-26 22:49:32 +00009937 // Make sure we found a non-volatile load and the extractelement is
9938 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009939 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009940 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009941
Eric Christopherc6418b12010-11-03 20:44:42 +00009942 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9943 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009944 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009945
Michael J. Spencer1eb02302014-07-18 00:15:50 +00009946 unsigned Align = LN0->getAlignment();
9947 if (NewLoad) {
9948 // Check the resultant load doesn't need a higher alignment than the
9949 // original load.
9950 unsigned NewAlign =
9951 TLI.getDataLayout()
9952 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9953
9954 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9955 return SDValue();
9956
9957 Align = NewAlign;
9958 }
9959
9960 SDValue NewPtr = LN0->getBasePtr();
9961 unsigned PtrOff = 0;
9962
9963 if (Elt) {
9964 PtrOff = LVT.getSizeInBits() * Elt / 8;
9965 EVT PtrType = NewPtr.getValueType();
9966 if (TLI.isBigEndian())
9967 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9968 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9969 DAG.getConstant(PtrOff, PtrType));
9970 }
9971
9972 // The replacement we need to do here is a little tricky: we need to
9973 // replace an extractelement of a load with a load.
9974 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9975 // Note that this replacement assumes that the extractvalue is the only
9976 // use of the load; that's okay because we don't want to perform this
9977 // transformation in other cases anyway.
9978 SDValue Load;
9979 SDValue Chain;
9980 if (NVT.bitsGT(LVT)) {
9981 // If the result type of vextract is wider than the load, then issue an
9982 // extending load instead.
9983 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9984 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9985 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9986 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9987 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9988 Align, LN0->getTBAAInfo());
9989 Chain = Load.getValue(1);
9990 } else {
9991 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9992 LN0->getPointerInfo().getWithOffset(PtrOff),
9993 LN0->isVolatile(), LN0->isNonTemporal(),
9994 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9995 Chain = Load.getValue(1);
9996 if (NVT.bitsLT(LVT))
9997 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9998 else
9999 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10000 }
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010001 WorklistRemover DeadNodes(*this);
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010002 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10003 SDValue To[] = { Load, Chain };
10004 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10005 // Since we're explcitly calling ReplaceAllUses, add the new node to the
10006 // worklist explicitly as well.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010007 AddToWorklist(Load.getNode());
10008 AddUsersToWorklist(Load.getNode()); // Add users too
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010009 // Make sure to revisit this node to clean it up; it will usually be dead.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010010 AddToWorklist(N);
Michael J. Spencer1eb02302014-07-18 00:15:50 +000010011 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010012 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010013
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010014 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010015}
Evan Cheng0de312d2007-10-06 08:19:55 +000010016
Michael Liao6d106b72012-10-23 23:06:52 +000010017// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10018SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10019 // We perform this optimization post type-legalization because
10020 // the type-legalizer often scalarizes integer-promoted vectors.
10021 // Performing this optimization before may create bit-casts which
10022 // will be type-legalized to complex code sequences.
10023 // We perform this optimization only before the operation legalizer because we
10024 // may introduce illegal operations.
10025 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10026 return SDValue();
10027
Dan Gohmana8665142007-06-25 16:23:39 +000010028 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010029 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010030 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010031
Nadav Rotembf6568b2011-10-29 21:23:04 +000010032 // Check to see if this is a BUILD_VECTOR of a bunch of values
10033 // which come from any_extend or zero_extend nodes. If so, we can create
10034 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010035 // optimizations. We do not handle sign-extend because we can't fill the sign
10036 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010037 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010038 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010039
Craig Topper02cb0fb2012-01-17 09:09:48 +000010040 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010041 SDValue In = N->getOperand(i);
10042 // Ignore undef inputs.
10043 if (In.getOpcode() == ISD::UNDEF) continue;
10044
10045 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10046 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10047
Nadav Rotemf3103612011-10-31 20:08:25 +000010048 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010049 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010050 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010051 break;
10052 }
10053
10054 // The input is a ZeroExt or AnyExt. Check the original type.
10055 EVT InTy = In.getOperand(0).getValueType();
10056
10057 // Check that all of the widened source types are the same.
10058 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010059 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010060 SourceType = InTy;
10061 else if (InTy != SourceType) {
10062 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010063 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010064 break;
10065 }
10066
10067 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010068 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010069 }
10070
Nadav Rotemf3103612011-10-31 20:08:25 +000010071 // In order to have valid types, all of the inputs must be extended from the
10072 // same source type and all of the inputs must be any or zero extend.
10073 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010074 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010075 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010076 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10077 isPowerOf2_32(SourceType.getSizeInBits());
10078
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010079 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10080 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010081 if (!ValidTypes)
10082 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010083
Michael Liao6d106b72012-10-23 23:06:52 +000010084 bool isLE = TLI.isLittleEndian();
10085 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10086 assert(ElemRatio > 1 && "Invalid element size ratio");
10087 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10088 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010089
Michael Liao6d106b72012-10-23 23:06:52 +000010090 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10091 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010092
Michael Liao6d106b72012-10-23 23:06:52 +000010093 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010094 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010095 SDValue Cast = N->getOperand(i);
10096 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10097 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10098 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10099 SDValue In;
10100 if (Cast.getOpcode() == ISD::UNDEF)
10101 In = DAG.getUNDEF(SourceType);
10102 else
10103 In = Cast->getOperand(0);
10104 unsigned Index = isLE ? (i * ElemRatio) :
10105 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010106
Michael Liao6d106b72012-10-23 23:06:52 +000010107 assert(Index < Ops.size() && "Invalid index");
10108 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010109 }
Chris Lattner5336a592006-03-19 01:27:56 +000010110
Michael Liao6d106b72012-10-23 23:06:52 +000010111 // The type of the new BUILD_VECTOR node.
10112 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10113 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10114 "Invalid vector size");
10115 // Check if the new vector type is legal.
10116 if (!isTypeLegal(VecVT)) return SDValue();
10117
10118 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010119 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010120
10121 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010122 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010123 // Bitcast to the desired type.
10124 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10125}
10126
Michael Liao59229792012-10-24 04:14:18 +000010127SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10128 EVT VT = N->getValueType(0);
10129
10130 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010131 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010132
10133 EVT SrcVT = MVT::Other;
10134 unsigned Opcode = ISD::DELETED_NODE;
10135 unsigned NumDefs = 0;
10136
10137 for (unsigned i = 0; i != NumInScalars; ++i) {
10138 SDValue In = N->getOperand(i);
10139 unsigned Opc = In.getOpcode();
10140
10141 if (Opc == ISD::UNDEF)
10142 continue;
10143
10144 // If all scalar values are floats and converted from integers.
10145 if (Opcode == ISD::DELETED_NODE &&
10146 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10147 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010148 }
Tom Stellard567f8862013-01-02 22:13:01 +000010149
Michael Liao59229792012-10-24 04:14:18 +000010150 if (Opc != Opcode)
10151 return SDValue();
10152
10153 EVT InVT = In.getOperand(0).getValueType();
10154
10155 // If all scalar values are typed differently, bail out. It's chosen to
10156 // simplify BUILD_VECTOR of integer types.
10157 if (SrcVT == MVT::Other)
10158 SrcVT = InVT;
10159 if (SrcVT != InVT)
10160 return SDValue();
10161 NumDefs++;
10162 }
10163
10164 // If the vector has just one element defined, it's not worth to fold it into
10165 // a vectorized one.
10166 if (NumDefs < 2)
10167 return SDValue();
10168
10169 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10170 && "Should only handle conversion from integer to float.");
10171 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10172
10173 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010174
10175 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10176 return SDValue();
10177
Michael Liao59229792012-10-24 04:14:18 +000010178 SmallVector<SDValue, 8> Opnds;
10179 for (unsigned i = 0; i != NumInScalars; ++i) {
10180 SDValue In = N->getOperand(i);
10181
10182 if (In.getOpcode() == ISD::UNDEF)
10183 Opnds.push_back(DAG.getUNDEF(SrcVT));
10184 else
10185 Opnds.push_back(In.getOperand(0));
10186 }
Craig Topper48d114b2014-04-26 18:35:24 +000010187 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010188 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010189
10190 return DAG.getNode(Opcode, dl, VT, BV);
10191}
10192
Michael Liao6d106b72012-10-23 23:06:52 +000010193SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10194 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010195 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010196 EVT VT = N->getValueType(0);
10197
10198 // A vector built entirely of undefs is undef.
10199 if (ISD::allOperandsUndef(N))
10200 return DAG.getUNDEF(VT);
10201
10202 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10203 if (V.getNode())
10204 return V;
10205
Michael Liao59229792012-10-24 04:14:18 +000010206 V = reduceBuildVecConvertToConvertBuildVec(N);
10207 if (V.getNode())
10208 return V;
10209
Dan Gohmana8665142007-06-25 16:23:39 +000010210 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10211 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10212 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010213
10214 // May only combine to shuffle after legalize if shuffle is legal.
10215 if (LegalOperations &&
10216 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10217 return SDValue();
10218
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010219 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010220 for (unsigned i = 0; i != NumInScalars; ++i) {
10221 // Ignore undef inputs.
10222 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010223
Dan Gohmana8665142007-06-25 16:23:39 +000010224 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010225 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010226 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010227 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010228 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010229 break;
10230 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010231
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010232 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010233 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010234 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10235 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010236
Craig Topperc0196b12014-04-14 00:51:57 +000010237 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010238 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010239 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010240 VecIn2 = ExtractedFromVec;
10241 } else {
10242 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010243 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010244 break;
10245 }
10246 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010247
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010248 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010249 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010250 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010251 for (unsigned i = 0; i != NumInScalars; ++i) {
10252 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010253 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010254 continue;
10255 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010256
Rafael Espindolab93db662009-04-24 12:40:33 +000010257 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010258 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010259 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010260 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010261 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10262 if (ExtIndex > VT.getVectorNumElements())
10263 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010264
Nate Begeman5f829d82009-04-29 05:20:52 +000010265 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010266 continue;
10267 }
10268
10269 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010270 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010271 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010272 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010273
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010274 // We can't generate a shuffle node with mismatched input and output types.
10275 // Attempt to transform a single input vector to the correct type.
10276 if ((VT != VecIn1.getValueType())) {
10277 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010278 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010279 return SDValue();
10280
10281 // We only support widening of vectors which are half the size of the
10282 // output registers. For example XMM->YMM widening on X86 with AVX.
10283 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10284 return SDValue();
10285
James Molloy1e5c6112012-09-10 14:01:21 +000010286 // If the input vector type has a different base type to the output
10287 // vector type, bail out.
10288 if (VecIn1.getValueType().getVectorElementType() !=
10289 VT.getVectorElementType())
10290 return SDValue();
10291
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010292 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010293 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010294 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010295 }
10296
10297 // If VecIn2 is unused then change it to undef.
10298 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10299
Nadav Rotem841c9a82012-09-20 08:53:31 +000010300 // Check that we were able to transform all incoming values to the same
10301 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010302 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10303 VecIn1.getValueType() != VT)
10304 return SDValue();
10305
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010306 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010307 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010308 return SDValue();
10309
Dan Gohmana8665142007-06-25 16:23:39 +000010310 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010311 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010312 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010313 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010314 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010315 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010317 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010318}
10319
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010320SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010321 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10322 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10323 // inputs come from at most two distinct vectors, turn this into a shuffle
10324 // node.
10325
10326 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010327 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010328 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010329
Nadav Rotem01892102012-07-14 21:30:27 +000010330 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010331 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010332 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010333 return DAG.getUNDEF(VT);
10334
10335 // Optimize concat_vectors where one of the vectors is undef.
10336 if (N->getNumOperands() == 2 &&
10337 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10338 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010339 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010340
10341 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10342 if (In->getOpcode() == ISD::BITCAST &&
10343 !In->getOperand(0)->getValueType(0).isVector()) {
10344 SDValue Scalar = In->getOperand(0);
10345 EVT SclTy = Scalar->getValueType(0);
10346
10347 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10348 return SDValue();
10349
10350 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10351 VT.getSizeInBits() / SclTy.getSizeInBits());
10352 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10353 return SDValue();
10354
10355 SDLoc dl = SDLoc(N);
10356 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10357 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10358 }
10359 }
Nadav Rotem01892102012-07-14 21:30:27 +000010360
Robert Lougher7d9084f2014-02-11 15:42:46 +000010361 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10362 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10363 if (N->getNumOperands() == 2 &&
10364 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10365 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10366 EVT VT = N->getValueType(0);
10367 SDValue N0 = N->getOperand(0);
10368 SDValue N1 = N->getOperand(1);
10369 SmallVector<SDValue, 8> Opnds;
10370 unsigned BuildVecNumElts = N0.getNumOperands();
10371
Hao Liu71224b02014-07-10 03:41:50 +000010372 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10373 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10374 if (SclTy0.isFloatingPoint()) {
10375 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10376 Opnds.push_back(N0.getOperand(i));
10377 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10378 Opnds.push_back(N1.getOperand(i));
10379 } else {
10380 // If BUILD_VECTOR are from built from integer, they may have different
10381 // operand types. Get the smaller type and truncate all operands to it.
10382 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10383 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10384 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10385 N0.getOperand(i)));
10386 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10387 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10388 N1.getOperand(i)));
10389 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010390
Craig Topper48d114b2014-04-26 18:35:24 +000010391 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010392 }
10393
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010394 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10395 // nodes often generate nop CONCAT_VECTOR nodes.
10396 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10397 // place the incoming vectors at the exact same location.
10398 SDValue SingleSource = SDValue();
10399 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10400
10401 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10402 SDValue Op = N->getOperand(i);
10403
10404 if (Op.getOpcode() == ISD::UNDEF)
10405 continue;
10406
10407 // Check if this is the identity extract:
10408 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10409 return SDValue();
10410
10411 // Find the single incoming vector for the extract_subvector.
10412 if (SingleSource.getNode()) {
10413 if (Op.getOperand(0) != SingleSource)
10414 return SDValue();
10415 } else {
10416 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010417
10418 // Check the source type is the same as the type of the result.
10419 // If not, this concat may extend the vector, so we can not
10420 // optimize it away.
10421 if (SingleSource.getValueType() != N->getValueType(0))
10422 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010423 }
10424
10425 unsigned IdentityIndex = i * PartNumElem;
10426 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10427 // The extract index must be constant.
10428 if (!CS)
10429 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010430
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010431 // Check that we are reading from the identity index.
10432 if (CS->getZExtValue() != IdentityIndex)
10433 return SDValue();
10434 }
10435
10436 if (SingleSource.getNode())
10437 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010438
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010439 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010440}
10441
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010442SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10443 EVT NVT = N->getValueType(0);
10444 SDValue V = N->getOperand(0);
10445
Michael Liao7a442c802012-10-17 20:48:33 +000010446 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10447 // Combine:
10448 // (extract_subvec (concat V1, V2, ...), i)
10449 // Into:
10450 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010451 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10452 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010453 if (V->getOperand(0).getValueType() != NVT)
10454 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010455 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10456 unsigned NumElems = NVT.getVectorNumElements();
10457 assert((Idx % NumElems) == 0 &&
10458 "IDX in concat is not a multiple of the result vector length.");
10459 return V->getOperand(Idx / NumElems);
10460 }
10461
Michael Liaobb05a1d2013-03-25 23:47:35 +000010462 // Skip bitcasting
10463 if (V->getOpcode() == ISD::BITCAST)
10464 V = V.getOperand(0);
10465
10466 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010467 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010468 // Handle only simple case where vector being inserted and vector
10469 // being extracted are of same type, and are half size of larger vectors.
10470 EVT BigVT = V->getOperand(0).getValueType();
10471 EVT SmallVT = V->getOperand(1).getValueType();
10472 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10473 return SDValue();
10474
10475 // Only handle cases where both indexes are constants with the same type.
10476 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10477 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10478
10479 if (InsIdx && ExtIdx &&
10480 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10481 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10482 // Combine:
10483 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10484 // Into:
10485 // indices are equal or bit offsets are equal => V1
10486 // otherwise => (extract_subvec V1, ExtIdx)
10487 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10488 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10489 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10490 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10491 DAG.getNode(ISD::BITCAST, dl,
10492 N->getOperand(0).getValueType(),
10493 V->getOperand(0)), N->getOperand(1));
10494 }
10495 }
10496
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010497 return SDValue();
10498}
10499
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010500// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10501static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10502 EVT VT = N->getValueType(0);
10503 unsigned NumElts = VT.getVectorNumElements();
10504
10505 SDValue N0 = N->getOperand(0);
10506 SDValue N1 = N->getOperand(1);
10507 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10508
10509 SmallVector<SDValue, 4> Ops;
10510 EVT ConcatVT = N0.getOperand(0).getValueType();
10511 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10512 unsigned NumConcats = NumElts / NumElemsPerConcat;
10513
10514 // Look at every vector that's inserted. We're looking for exact
10515 // subvector-sized copies from a concatenated vector
10516 for (unsigned I = 0; I != NumConcats; ++I) {
10517 // Make sure we're dealing with a copy.
10518 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010519 bool AllUndef = true, NoUndef = true;
10520 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10521 if (SVN->getMaskElt(J) >= 0)
10522 AllUndef = false;
10523 else
10524 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010525 }
10526
Hao Liubc601962013-05-13 02:07:05 +000010527 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010528 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10529 return SDValue();
10530
10531 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10532 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10533 return SDValue();
10534
10535 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10536 if (FirstElt < N0.getNumOperands())
10537 Ops.push_back(N0.getOperand(FirstElt));
10538 else
10539 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10540
10541 } else if (AllUndef) {
10542 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10543 } else { // Mixed with general masks and undefs, can't do optimization.
10544 return SDValue();
10545 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010546 }
10547
Craig Topper48d114b2014-04-26 18:35:24 +000010548 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010549}
10550
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010551SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010552 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010553 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010554
Mon P Wang25f01062008-11-10 04:46:22 +000010555 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010556 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010557
Craig Topper5894fe42012-04-09 05:16:56 +000010558 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010559
Craig Topper279c77b2012-01-04 08:07:43 +000010560 // Canonicalize shuffle undef, undef -> undef
10561 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10562 return DAG.getUNDEF(VT);
10563
10564 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10565
10566 // Canonicalize shuffle v, v -> v, undef
10567 if (N0 == N1) {
10568 SmallVector<int, 8> NewMask;
10569 for (unsigned i = 0; i != NumElts; ++i) {
10570 int Idx = SVN->getMaskElt(i);
10571 if (Idx >= (int)NumElts) Idx -= NumElts;
10572 NewMask.push_back(Idx);
10573 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010574 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010575 &NewMask[0]);
10576 }
10577
10578 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10579 if (N0.getOpcode() == ISD::UNDEF) {
10580 SmallVector<int, 8> NewMask;
10581 for (unsigned i = 0; i != NumElts; ++i) {
10582 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010583 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010584 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010585 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010586 else
10587 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010588 }
10589 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010590 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010591 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010592 &NewMask[0]);
10593 }
10594
10595 // Remove references to rhs if it is undef
10596 if (N1.getOpcode() == ISD::UNDEF) {
10597 bool Changed = false;
10598 SmallVector<int, 8> NewMask;
10599 for (unsigned i = 0; i != NumElts; ++i) {
10600 int Idx = SVN->getMaskElt(i);
10601 if (Idx >= (int)NumElts) {
10602 Idx = -1;
10603 Changed = true;
10604 }
10605 NewMask.push_back(Idx);
10606 }
10607 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010608 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010609 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010610
Bob Wilsonf63da122010-10-28 17:06:14 +000010611 // If it is a splat, check if the argument vector is another splat or a
10612 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010613 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010614 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010615
Dan Gohmana8665142007-06-25 16:23:39 +000010616 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010617 // not the number of vector elements, look through it. Be careful not to
10618 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010619 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010620 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010621 if (ConvInput.getValueType().isVector() &&
10622 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010623 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010624 }
10625
Dan Gohmana8665142007-06-25 16:23:39 +000010626 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010627 assert(V->getNumOperands() == NumElts &&
10628 "BUILD_VECTOR has wrong number of operands");
10629 SDValue Base;
10630 bool AllSame = true;
10631 for (unsigned i = 0; i != NumElts; ++i) {
10632 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10633 Base = V->getOperand(i);
10634 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010635 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010636 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010637 // Splat of <u, u, u, u>, return <u, u, u, u>
10638 if (!Base.getNode())
10639 return N0;
10640 for (unsigned i = 0; i != NumElts; ++i) {
10641 if (V->getOperand(i) != Base) {
10642 AllSame = false;
10643 break;
10644 }
10645 }
10646 // Splat of <x, x, x, x>, return <x, x, x, x>
10647 if (AllSame)
10648 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010649 }
10650 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010651
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010652 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10653 Level < AfterLegalizeVectorOps &&
10654 (N1.getOpcode() == ISD::UNDEF ||
10655 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10656 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10657 SDValue V = partitionShuffleOfConcats(N, DAG);
10658
10659 if (V.getNode())
10660 return V;
10661 }
10662
Nadav Rotemb0783502012-04-01 19:31:22 +000010663 // If this shuffle node is simply a swizzle of another shuffle node,
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010664 // then try to simplify it.
Nadav Rotemb0783502012-04-01 19:31:22 +000010665 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10666 N1.getOpcode() == ISD::UNDEF) {
10667
Nadav Rotemb0783502012-04-01 19:31:22 +000010668 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10669
Craig Topper5894fe42012-04-09 05:16:56 +000010670 // The incoming shuffle must be of the same type as the result of the
10671 // current shuffle.
10672 assert(OtherSV->getOperand(0).getValueType() == VT &&
10673 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010674
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010675 SmallVector<int, 4> Mask;
10676 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010677 for (unsigned i = 0; i != NumElts; ++i) {
10678 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010679 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010680 // Next, this index comes from the first value, which is the incoming
10681 // shuffle. Adopt the incoming index.
10682 if (Idx >= 0)
10683 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010684 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010685 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010686
10687 bool CommuteOperands = false;
10688 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10689 // To be valid, the combine shuffle mask should only reference elements
10690 // from one of the two vectors in input to the inner shufflevector.
10691 bool IsValidMask = true;
10692 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10693 // See if the combined mask only reference undefs or elements coming
10694 // from the first shufflevector operand.
10695 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010696
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010697 if (!IsValidMask) {
10698 IsValidMask = true;
10699 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10700 // Check that all the elements come from the second shuffle operand.
10701 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10702 CommuteOperands = IsValidMask;
10703 }
10704
10705 // Early exit if the combined shuffle mask is not valid.
10706 if (!IsValidMask)
10707 return SDValue();
10708 }
10709
10710 // See if this pair of shuffles can be safely folded according to either
10711 // of the following rules:
10712 // shuffle(shuffle(x, y), undef) -> x
10713 // shuffle(shuffle(x, undef), undef) -> x
10714 // shuffle(shuffle(x, y), undef) -> y
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010715 bool IsIdentityMask = true;
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010716 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010717 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10718 // Skip Undefs.
10719 if (Mask[i] < 0)
10720 continue;
10721
10722 // The combined shuffle must map each index to itself.
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010723 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010724 }
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010725
10726 if (IsIdentityMask) {
10727 if (CommuteOperands)
10728 // optimize shuffle(shuffle(x, y), undef) -> y.
10729 return OtherSV->getOperand(1);
10730
10731 // optimize shuffle(shuffle(x, undef), undef) -> x
10732 // optimize shuffle(shuffle(x, y), undef) -> x
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010733 return OtherSV->getOperand(0);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010734 }
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010735
10736 // It may still be beneficial to combine the two shuffles if the
10737 // resulting shuffle is legal.
Andrea Di Biagio67d8b2e2014-07-13 21:02:14 +000010738 if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010739 if (!CommuteOperands)
10740 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10741 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10742 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10743 &Mask[0]);
10744
10745 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10746 return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010747 &Mask[0]);
Andrea Di Biagiob2921c72014-07-10 18:04:55 +000010748 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010749 }
10750
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000010751 // Canonicalize shuffles according to rules:
10752 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10753 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10754 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10755 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10756 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10757 TLI.isTypeLegal(VT)) {
10758 // The incoming shuffle must be of the same type as the result of the
10759 // current shuffle.
10760 assert(N1->getOperand(0).getValueType() == VT &&
10761 "Shuffle types don't match");
10762
10763 SDValue SV0 = N1->getOperand(0);
10764 SDValue SV1 = N1->getOperand(1);
10765 bool HasSameOp0 = N0 == SV0;
10766 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10767 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10768 // Commute the operands of this shuffle so that next rule
10769 // will trigger.
10770 return DAG.getCommutedVectorShuffle(*SVN);
10771 }
10772
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010773 // Try to fold according to rules:
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010774 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10775 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10776 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10777 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010778 // Don't try to fold shuffles with illegal type.
10779 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010780 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010781 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10782
10783 // The incoming shuffle must be of the same type as the result of the
10784 // current shuffle.
10785 assert(OtherSV->getOperand(0).getValueType() == VT &&
10786 "Shuffle types don't match");
10787
10788 SDValue SV0 = OtherSV->getOperand(0);
10789 SDValue SV1 = OtherSV->getOperand(1);
10790 bool HasSameOp0 = N1 == SV0;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010791 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10792 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010793 // Early exit.
10794 return SDValue();
10795
10796 SmallVector<int, 4> Mask;
10797 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10798 // operand, and SV1 as the second operand.
10799 for (unsigned i = 0; i != NumElts; ++i) {
10800 int Idx = SVN->getMaskElt(i);
10801 if (Idx < 0) {
10802 // Propagate Undef.
10803 Mask.push_back(Idx);
10804 continue;
10805 }
10806
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010807 if (Idx < (int)NumElts) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010808 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010809 if (IsSV1Undef && Idx >= (int) NumElts)
10810 Idx = -1; // Propagate Undef.
10811 } else
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010812 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10813
10814 Mask.push_back(Idx);
10815 }
10816
10817 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010818 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10819 if (IsSV1Undef)
10820 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10821 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10822 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010823 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000010824 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000010825 }
10826
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010827 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010828}
10829
Manman Ren413a6cb2014-01-31 01:10:35 +000010830SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10831 SDValue N0 = N->getOperand(0);
10832 SDValue N2 = N->getOperand(2);
10833
10834 // If the input vector is a concatenation, and the insert replaces
10835 // one of the halves, we can optimize into a single concat_vectors.
10836 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10837 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10838 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10839 EVT VT = N->getValueType(0);
10840
10841 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10842 // (concat_vectors Z, Y)
10843 if (InsIdx == 0)
10844 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10845 N->getOperand(1), N0.getOperand(1));
10846
10847 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10848 // (concat_vectors X, Z)
10849 if (InsIdx == VT.getVectorNumElements()/2)
10850 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10851 N0.getOperand(0), N->getOperand(1));
10852 }
10853
10854 return SDValue();
10855}
10856
Evan Chenga320abc2006-04-20 08:56:16 +000010857/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010858/// an AND to a vector_shuffle with the destination vector and a zero vector.
10859/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010860/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010861SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010862 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010863 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010864 SDValue LHS = N->getOperand(0);
10865 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010866 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010867 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010868 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010869 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010870 SmallVector<int, 8> Indices;
10871 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010872 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010873 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010874 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010875 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010876
10877 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010878 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010879 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010880 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010881 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010882 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010883 }
10884
10885 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010886 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010887 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010888 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010889
Dan Gohmana8665142007-06-25 16:23:39 +000010890 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010891 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010892 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010893 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000010894 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000010895 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010896 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010897 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010898 }
10899 }
Bill Wendling31b50992009-01-30 23:59:18 +000010900
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010901 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010902}
10903
Dan Gohmana8665142007-06-25 16:23:39 +000010904/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010905SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010906 assert(N->getValueType(0).isVector() &&
10907 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010908
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010909 SDValue LHS = N->getOperand(0);
10910 SDValue RHS = N->getOperand(1);
10911 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010912 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010913
Dan Gohmana8665142007-06-25 16:23:39 +000010914 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010915 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010916 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010917 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010918 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010919 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10920 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010921 return SDValue();
10922
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010923 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010924 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010925 SDValue LHSOp = LHS.getOperand(i);
10926 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010927
Evan Cheng64d28462006-05-31 06:08:35 +000010928 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010929 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10930 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010931 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010932 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010933 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010934 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010935 break;
10936 }
Bill Wendling31b50992009-01-30 23:59:18 +000010937
Bob Wilson54081442010-12-17 23:06:49 +000010938 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010939 EVT RVT = RHSOp.getValueType();
10940 if (RVT != VT) {
10941 // Integer BUILD_VECTOR operands may have types larger than the element
10942 // size (e.g., when the element type is not legal). Prior to type
10943 // legalization, the types may not match between the two BUILD_VECTORS.
10944 // Truncate one of the operands to make them match.
10945 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010946 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010947 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010948 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010949 VT = RVT;
10950 }
10951 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010952 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010953 LHSOp, RHSOp);
10954 if (FoldOp.getOpcode() != ISD::UNDEF &&
10955 FoldOp.getOpcode() != ISD::Constant &&
10956 FoldOp.getOpcode() != ISD::ConstantFP)
10957 break;
10958 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010959 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010960 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010961
Bob Wilson54081442010-12-17 23:06:49 +000010962 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000010963 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000010964 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010965
Andrea Di Biagio446a5272014-05-30 23:17:53 +000010966 // Type legalization might introduce new shuffles in the DAG.
10967 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10968 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10969 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10970 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10971 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10972 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10973 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10974 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10975
10976 if (SVN0->getMask().equals(SVN1->getMask())) {
10977 EVT VT = N->getValueType(0);
10978 SDValue UndefVector = LHS.getOperand(1);
10979 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10980 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010981 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000010982 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10983 &SVN0->getMask()[0]);
10984 }
10985 }
10986
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010987 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010988}
10989
Craig Topper82384612012-09-11 01:45:21 +000010990/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10991SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010992 assert(N->getValueType(0).isVector() &&
10993 "SimplifyVUnaryOp only works on vectors!");
10994
10995 SDValue N0 = N->getOperand(0);
10996
10997 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10998 return SDValue();
10999
11000 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11001 SmallVector<SDValue, 8> Ops;
11002 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11003 SDValue Op = N0.getOperand(i);
11004 if (Op.getOpcode() != ISD::UNDEF &&
11005 Op.getOpcode() != ISD::ConstantFP)
11006 break;
11007 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011008 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011009 if (FoldOp.getOpcode() != ISD::UNDEF &&
11010 FoldOp.getOpcode() != ISD::ConstantFP)
11011 break;
11012 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011013 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011014 }
11015
11016 if (Ops.size() != N0.getNumOperands())
11017 return SDValue();
11018
Craig Topper48d114b2014-04-26 18:35:24 +000011019 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011020}
11021
Andrew Trickef9de2a2013-05-25 02:42:55 +000011022SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011023 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011024 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011025
Bill Wendling31b50992009-01-30 23:59:18 +000011026 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011027 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011028
Nate Begeman2042aa52005-10-08 00:29:44 +000011029 // If we got a simplified select_cc node back from SimplifySelectCC, then
11030 // break it down into a new SETCC node, and a new SELECT node, and then return
11031 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011032 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011033 // Check to see if we got a select_cc back (to turn into setcc/select).
11034 // Otherwise, just return whatever node we got back, like fabs.
11035 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011036 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011037 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011038 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011039 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011040 AddToWorklist(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011041 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11042 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011043 }
Bill Wendling31b50992009-01-30 23:59:18 +000011044
Nate Begeman2042aa52005-10-08 00:29:44 +000011045 return SCC;
11046 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011047 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011048}
11049
Chris Lattner6c14c352005-10-18 06:04:22 +000011050/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11051/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000011052/// select. Callers of this should assume that TheSelect is deleted if this
11053/// returns true. As such, they should return the appropriate thing (e.g. the
11054/// node) back to the top-level of the DAG combiner loop to avoid it being
11055/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011056bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011057 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011058
Nadav Rotema49a02a2011-02-11 19:57:47 +000011059 // Cannot simplify select with vector condition
11060 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11061
Chris Lattner6c14c352005-10-18 06:04:22 +000011062 // If this is a select from two identical things, try to pull the operation
11063 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011064 if (LHS.getOpcode() != RHS.getOpcode() ||
11065 !LHS.hasOneUse() || !RHS.hasOneUse())
11066 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011067
Chris Lattner254c4452010-09-21 15:46:59 +000011068 // If this is a load and the token chain is identical, replace the select
11069 // of two loads with a load through a select of the address to load from.
11070 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11071 // constants have been dropped into the constant pool.
11072 if (LHS.getOpcode() == ISD::LOAD) {
11073 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11074 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011075
Chris Lattner254c4452010-09-21 15:46:59 +000011076 // Token chains must be identical.
11077 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011078 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011079 LLD->isVolatile() || RLD->isVolatile() ||
11080 // If this is an EXTLOAD, the VT's must match.
11081 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011082 // If this is an EXTLOAD, the kind of extension must match.
11083 (LLD->getExtensionType() != RLD->getExtensionType() &&
11084 // The only exception is if one of the extensions is anyext.
11085 LLD->getExtensionType() != ISD::EXTLOAD &&
11086 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011087 // FIXME: this discards src value information. This is
11088 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011089 // both potential memory locations. Since we are discarding
11090 // src value info, don't do the transformation if the memory
11091 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011092 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011093 RLD->getPointerInfo().getAddrSpace() != 0 ||
11094 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11095 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011096 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011097
Chris Lattnere3267522010-09-21 15:58:55 +000011098 // Check that the select condition doesn't reach either load. If so,
11099 // folding this will induce a cycle into the DAG. If not, this is safe to
11100 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011101 SDValue Addr;
11102 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011103 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11104 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11105 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11106 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011107 // The loads must not depend on one another.
11108 if (LLD->isPredecessorOf(RLD) ||
11109 RLD->isPredecessorOf(LLD))
11110 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011111 Addr = DAG.getSelect(SDLoc(TheSelect),
11112 LLD->getBasePtr().getValueType(),
11113 TheSelect->getOperand(0), LLD->getBasePtr(),
11114 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011115 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011116 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11117 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11118
11119 if ((LLD->hasAnyUseOfValue(1) &&
11120 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011121 (RLD->hasAnyUseOfValue(1) &&
11122 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011123 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011124
Andrew Trickef9de2a2013-05-25 02:42:55 +000011125 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011126 LLD->getBasePtr().getValueType(),
11127 TheSelect->getOperand(0),
11128 TheSelect->getOperand(1),
11129 LLD->getBasePtr(), RLD->getBasePtr(),
11130 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011131 }
11132
Chris Lattnere3267522010-09-21 15:58:55 +000011133 SDValue Load;
11134 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11135 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011136 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011137 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011138 LLD->getChain(), Addr, MachinePointerInfo(),
11139 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000011140 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011141 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011142 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11143 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011144 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011145 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011146 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011147 LLD->getChain(), Addr, MachinePointerInfo(),
11148 LLD->getMemoryVT(), LLD->isVolatile(),
11149 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000011150 }
Chris Lattnere3267522010-09-21 15:58:55 +000011151
11152 // Users of the select now use the result of the load.
11153 CombineTo(TheSelect, Load);
11154
11155 // Users of the old loads now use the new load's chain. We know the
11156 // old-load value is dead now.
11157 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11158 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11159 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011160 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011161
Chris Lattner6c14c352005-10-18 06:04:22 +000011162 return false;
11163}
11164
Chris Lattner43d63772009-03-11 05:08:08 +000011165/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11166/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011167SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011168 SDValue N2, SDValue N3,
11169 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011170 // (x ? y : y) -> y.
11171 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011172
Owen Anderson53aa7a92009-08-10 22:56:29 +000011173 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011174 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11175 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11176 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011177
11178 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011179 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011180 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011181 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011182 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011183
11184 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011185 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011186 return N2;
11187 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011188 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011189 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011190
Nate Begeman2042aa52005-10-08 00:29:44 +000011191 // Check to see if we can simplify the select into an fabs node
11192 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11193 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011194 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011195 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11196 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11197 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11198 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011199 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011200
Nate Begeman2042aa52005-10-08 00:29:44 +000011201 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11202 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11203 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11204 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011205 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011206 }
11207 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011208
Chris Lattner43d63772009-03-11 05:08:08 +000011209 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11210 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11211 // in it. This is a win when the constant is not otherwise available because
11212 // it replaces two constant pool loads with one. We only do this if the FP
11213 // type is known to be legal, because if it isn't, then we are before legalize
11214 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011215 // messing with soft float) and if the ConstantFP is not legal, because if
11216 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011217 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11218 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11219 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011220 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011221 TargetLowering::Legal &&
11222 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11223 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011224 // If both constants have multiple uses, then we won't need to do an
11225 // extra load, they are likely around in registers for other users.
11226 (TV->hasOneUse() || FV->hasOneUse())) {
11227 Constant *Elts[] = {
11228 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11229 const_cast<ConstantFP*>(TV->getConstantFPValue())
11230 };
Chris Lattner229907c2011-07-18 04:54:35 +000011231 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011232 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011233
Chris Lattner43d63772009-03-11 05:08:08 +000011234 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011235 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011236 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11237 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011238 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011239
11240 // Get the offsets to the 0 and 1 element of the array so that we can
11241 // select between them.
11242 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011243 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011244 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011245
Chris Lattner43d63772009-03-11 05:08:08 +000011246 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011247 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011248 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011249 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011250 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11251 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011252 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011253 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011254 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011255 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011256 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011257 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011258 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011259
11260 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011261 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011262
Nate Begeman2042aa52005-10-08 00:29:44 +000011263 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011264 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011265 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011266 (N1C->isNullValue() || // (a < 0) ? b : 0
11267 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011268 EVT XType = N0.getValueType();
11269 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011270 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011271 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011272 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011273 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11274 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011275 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011276 SDValue ShCt = DAG.getConstant(ShCtV,
11277 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011278 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011279 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011280 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011281
Duncan Sands11dd4242008-06-08 20:54:56 +000011282 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011283 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011284 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011285 }
Bill Wendling31b50992009-01-30 23:59:18 +000011286
11287 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011288 }
Bill Wendling31b50992009-01-30 23:59:18 +000011289
Andrew Trickef9de2a2013-05-25 02:42:55 +000011290 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011291 XType, N0,
11292 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011293 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011294 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011295
Duncan Sands11dd4242008-06-08 20:54:56 +000011296 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011297 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011298 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011299 }
Bill Wendling31b50992009-01-30 23:59:18 +000011300
11301 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011302 }
11303 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011304
Owen Anderson3231d132010-09-22 22:58:22 +000011305 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11306 // where y is has a single bit set.
11307 // A plaintext description would be, we can turn the SELECT_CC into an AND
11308 // when the condition can be materialized as an all-ones register. Any
11309 // single bit-test can be materialized as an all-ones register with
11310 // shift-left and shift-right-arith.
11311 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11312 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011313 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011314 N2C && N2C->isNullValue()) {
11315 SDValue AndLHS = N0->getOperand(0);
11316 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11317 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11318 // Shift the tested bit over the sign bit.
11319 APInt AndMask = ConstAndRHS->getAPIntValue();
11320 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011321 DAG.getConstant(AndMask.countLeadingZeros(),
11322 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011323 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011324
Owen Anderson3231d132010-09-22 22:58:22 +000011325 // Now arithmetic right shift it all the way over, so the result is either
11326 // all-ones, or zero.
11327 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011328 DAG.getConstant(AndMask.getBitWidth()-1,
11329 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011330 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011331
Owen Anderson3231d132010-09-22 22:58:22 +000011332 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11333 }
11334 }
11335
Nate Begeman6828ed92005-10-10 21:26:48 +000011336 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011337 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011338 TLI.getBooleanContents(N0.getValueType()) ==
11339 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011340
Chris Lattnera083ffc2007-04-11 06:50:51 +000011341 // If the caller doesn't want us to simplify this into a zext of a compare,
11342 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011343 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011344 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011345
Nate Begeman6828ed92005-10-10 21:26:48 +000011346 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011347 // NOTE: Don't create a SETCC if it's not legal on this target.
11348 if (!LegalOperations ||
11349 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011350 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011351 SDValue Temp, SCC;
11352 // cast from setcc result type to select result type
11353 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011354 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011355 N0, N1, CC);
11356 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011357 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011358 N2.getValueType());
11359 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011360 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011361 N2.getValueType(), SCC);
11362 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011363 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11364 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011365 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011366 }
11367
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011368 AddToWorklist(SCC.getNode());
11369 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011370
11371 if (N2C->getAPIntValue() == 1)
11372 return Temp;
11373
11374 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011375 return DAG.getNode(
11376 ISD::SHL, DL, N2.getValueType(), Temp,
11377 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11378 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011379 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011380 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011381
Nate Begeman2042aa52005-10-08 00:29:44 +000011382 // Check to see if this is the equivalent of setcc
11383 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11384 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011385 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011386 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011387 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011388 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11389 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011390 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011391 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011392 return Res;
11393 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011394
Bill Wendling31b50992009-01-30 23:59:18 +000011395 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011396 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011397 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011398 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011399 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011400 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011401 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011402 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011403 }
Bill Wendling31b50992009-01-30 23:59:18 +000011404 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011405 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011406 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011407 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011408 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011409 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011410 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011411 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011412 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011413 }
Bill Wendling31b50992009-01-30 23:59:18 +000011414 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011415 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011416 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011417 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011418 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011419 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011420 }
11421 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011422
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011423 // Check to see if this is an integer abs.
11424 // select_cc setg[te] X, 0, X, -X ->
11425 // select_cc setgt X, -1, X, -X ->
11426 // select_cc setl[te] X, 0, -X, X ->
11427 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011428 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011429 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011430 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011431 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11432 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11433 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11434 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11435 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11436 (N1C->isOne() && CC == ISD::SETLT)) &&
11437 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11438 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11439
Owen Anderson53aa7a92009-08-10 22:56:29 +000011440 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011441 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011442 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011443 N0,
11444 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011445 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011446 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011447 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011448 AddToWorklist(Shift.getNode());
11449 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011450 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011451 }
11452 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011453
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011454 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011455}
11456
Evan Cheng92658d52007-02-08 22:13:59 +000011457/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011458SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011459 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011460 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011461 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011462 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011463 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011464}
11465
Nate Begemanc6f067a2005-10-20 02:15:44 +000011466/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11467/// return a DAG expression to select that will generate the same value by
11468/// multiplying by a magic number. See:
11469/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011470SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011471 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11472 if (!C)
11473 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011474
11475 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011476 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011477 return SDValue();
11478
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011479 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011480 SDValue S =
11481 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011482
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011483 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011484 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011485 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011486}
11487
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011488/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begemanc6f067a2005-10-20 02:15:44 +000011489/// return a DAG expression to select that will generate the same value by
11490/// multiplying by a magic number. See:
11491/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011492SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011493 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11494 if (!C)
11495 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011496
11497 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011498 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011499 return SDValue();
11500
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011501 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011502 SDValue S =
11503 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011504
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011505 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011506 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011507 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011508}
11509
Nate Begeman18150d52009-09-25 06:05:26 +000011510/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011511// to alias with anything but itself. Provides base object and offset as
11512// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011513static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011514 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011515 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011516 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011517
Jim Laskey0463e082006-10-07 23:37:56 +000011518 // If it's an adding a simple constant then integrate the offset.
11519 if (Base.getOpcode() == ISD::ADD) {
11520 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11521 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011522 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011523 }
11524 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011525
Nate Begeman18150d52009-09-25 06:05:26 +000011526 // Return the underlying GlobalValue, and update the Offset. Return false
11527 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11528 // by multiple nodes with different offsets.
11529 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11530 GV = G->getGlobal();
11531 Offset += G->getOffset();
11532 return false;
11533 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011534
Nate Begeman18150d52009-09-25 06:05:26 +000011535 // Return the underlying Constant value, and update the Offset. Return false
11536 // for ConstantSDNodes since the same constant pool entry may be represented
11537 // by multiple nodes with different offsets.
11538 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011539 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11540 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011541 Offset += C->getOffset();
11542 return false;
11543 }
Jim Laskey0463e082006-10-07 23:37:56 +000011544 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011545 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011546}
11547
11548/// isAlias - Return true if there is any possibility that the two addresses
11549/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011550bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011551 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011552 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011553
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011554 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011555 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011556
Jim Laskey0463e082006-10-07 23:37:56 +000011557 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011558 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011559 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011560 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011561 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011562 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11563 Base1, Offset1, GV1, CV1);
11564 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11565 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011566
Nate Begeman18150d52009-09-25 06:05:26 +000011567 // If they have a same base address then check to see if they overlap.
11568 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011569 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11570 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011571
Owen Anderson272ff942010-09-20 20:39:59 +000011572 // It is possible for different frame indices to alias each other, mostly
11573 // when tail call optimization reuses return address slots for arguments.
11574 // To catch this case, look up the actual index of frame indices to compute
11575 // the real alias relationship.
11576 if (isFrameIndex1 && isFrameIndex2) {
11577 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11578 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11579 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011580 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11581 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011582 }
11583
Wesley Peck527da1b2010-11-23 03:31:01 +000011584 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011585 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011586 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11587 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011588
Nate Begeman879d8f12009-09-15 00:18:30 +000011589 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11590 // compared to the size and offset of the access, we may be able to prove they
11591 // do not alias. This check is conservative for now to catch cases created by
11592 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011593 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11594 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11595 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11596 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11597 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11598 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11599 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011600
Nate Begeman879d8f12009-09-15 00:18:30 +000011601 // There is no overlap between these relatively aligned accesses of similar
11602 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011603 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11604 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011605 return false;
11606 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011607
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011608 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11609 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011610#ifndef NDEBUG
11611 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11612 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11613 UseAA = false;
11614#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011615 if (UseAA &&
11616 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011617 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011618 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11619 Op1->getSrcValueOffset());
11620 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11621 Op0->getSrcValueOffset() - MinOffset;
11622 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11623 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011624 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011625 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11626 Overlap1,
11627 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11628 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11629 Overlap2,
11630 UseTBAA ? Op1->getTBAAInfo() : nullptr));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011631 if (AAResult == AliasAnalysis::NoAlias)
11632 return false;
11633 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011634
11635 // Otherwise we have to assume they alias.
11636 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011637}
11638
Jim Laskey708d0db2006-10-04 16:53:27 +000011639/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11640/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011641void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011642 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011643 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011644 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011645
Jim Laskeyd07be232006-09-25 16:29:54 +000011646 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011647 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011648
Jim Laskey708d0db2006-10-04 16:53:27 +000011649 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011650 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011651 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011652
Jim Laskey6549d222006-10-05 15:07:25 +000011653 // Look at each chain and determine if it is an alias. If so, add it to the
11654 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011655 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011656 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011657 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011658 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011659
11660 // For TokenFactor nodes, look at each operand and only continue up the
11661 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011662 // find more and revert to original chain since the xform is unlikely to be
11663 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011664 //
11665 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011666 // chain we found before we hit a tokenfactor rather than the original
11667 // chain.
11668 if (Depth > 6 || Aliases.size() == 2) {
11669 Aliases.clear();
11670 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011671 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011672 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011673
Nate Begeman879d8f12009-09-15 00:18:30 +000011674 // Don't bother if we've been before.
11675 if (!Visited.insert(Chain.getNode()))
11676 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011677
Jim Laskey6549d222006-10-05 15:07:25 +000011678 switch (Chain.getOpcode()) {
11679 case ISD::EntryToken:
11680 // Entry token is ideal chain operand, but handled in FindBetterChain.
11681 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011682
Jim Laskey6549d222006-10-05 15:07:25 +000011683 case ISD::LOAD:
11684 case ISD::STORE: {
11685 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011686 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11687 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011688
Jim Laskey6549d222006-10-05 15:07:25 +000011689 // If chain is alias then stop here.
11690 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011691 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011692 Aliases.push_back(Chain);
11693 } else {
11694 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011695 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011696 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011697 }
Jim Laskey6549d222006-10-05 15:07:25 +000011698 break;
11699 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011700
Jim Laskey6549d222006-10-05 15:07:25 +000011701 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011702 // We have to check each of the operands of the token factor for "small"
11703 // token factors, so we queue them up. Adding the operands to the queue
11704 // (stack) in reverse order maintains the original order and increases the
11705 // likelihood that getNode will find a matching token factor (CSE.)
11706 if (Chain.getNumOperands() > 16) {
11707 Aliases.push_back(Chain);
11708 break;
11709 }
Jim Laskey6549d222006-10-05 15:07:25 +000011710 for (unsigned n = Chain.getNumOperands(); n;)
11711 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011712 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011713 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011714
Jim Laskey6549d222006-10-05 15:07:25 +000011715 default:
11716 // For all other instructions we will just have to take what we can get.
11717 Aliases.push_back(Chain);
11718 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011719 }
11720 }
Hal Finkel51a98382014-01-24 20:12:02 +000011721
11722 // We need to be careful here to also search for aliases through the
11723 // value operand of a store, etc. Consider the following situation:
11724 // Token1 = ...
11725 // L1 = load Token1, %52
11726 // S1 = store Token1, L1, %51
11727 // L2 = load Token1, %52+8
11728 // S2 = store Token1, L2, %51+8
11729 // Token2 = Token(S1, S2)
11730 // L3 = load Token2, %53
11731 // S3 = store Token2, L3, %52
11732 // L4 = load Token2, %53+8
11733 // S4 = store Token2, L4, %52+8
11734 // If we search for aliases of S3 (which loads address %52), and we look
11735 // only through the chain, then we'll miss the trivial dependence on L1
11736 // (which also loads from %52). We then might change all loads and
11737 // stores to use Token1 as their chain operand, which could result in
11738 // copying %53 into %52 before copying %52 into %51 (which should
11739 // happen first).
11740 //
11741 // The problem is, however, that searching for such data dependencies
11742 // can become expensive, and the cost is not directly related to the
11743 // chain depth. Instead, we'll rule out such configurations here by
11744 // insisting that we've visited all chain users (except for users
11745 // of the original chain, which is not necessary). When doing this,
11746 // we need to look through nodes we don't care about (otherwise, things
11747 // like register copies will interfere with trivial cases).
11748
11749 SmallVector<const SDNode *, 16> Worklist;
11750 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11751 IE = Visited.end(); I != IE; ++I)
11752 if (*I != OriginalChain.getNode())
11753 Worklist.push_back(*I);
11754
11755 while (!Worklist.empty()) {
11756 const SDNode *M = Worklist.pop_back_val();
11757
11758 // We have already visited M, and want to make sure we've visited any uses
11759 // of M that we care about. For uses that we've not visisted, and don't
11760 // care about, queue them to the worklist.
11761
11762 for (SDNode::use_iterator UI = M->use_begin(),
11763 UIE = M->use_end(); UI != UIE; ++UI)
11764 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11765 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11766 // We've not visited this use, and we care about it (it could have an
11767 // ordering dependency with the original node).
11768 Aliases.clear();
11769 Aliases.push_back(OriginalChain);
11770 return;
11771 }
11772
11773 // We've not visited this use, but we don't care about it. Mark it as
11774 // visited and enqueue it to the worklist.
11775 Worklist.push_back(*UI);
11776 }
11777 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011778}
11779
11780/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11781/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011782SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11783 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011784
Jim Laskey708d0db2006-10-04 16:53:27 +000011785 // Accumulate all the aliases to this node.
11786 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011787
Dan Gohman4298df62011-05-17 22:20:36 +000011788 // If no operands then chain to entry token.
11789 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011790 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011791
11792 // If a single operand then chain to it. We don't need to revisit it.
11793 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011794 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011795
Jim Laskey708d0db2006-10-04 16:53:27 +000011796 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011797 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011798}
11799
Nate Begeman21158fc2005-09-01 00:19:25 +000011800// SelectionDAG::Combine - This is the entry point for the file.
11801//
Bill Wendling084669a2009-04-29 00:15:41 +000011802void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011803 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011804 /// run - This is the main entry point to this class.
11805 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011806 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011807}