blob: a52dacf5216b293e217d2865e35f4ead35186953 [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).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramere1e549d2012-03-10 00:23:58 +0000108 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
Nate Begeman21158fc2005-09-01 00:19:25 +0000113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
115 /// now.
116 ///
117 void AddUsersToWorkList(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000118 for (SDNode *Node : N->uses())
119 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:
James Molloy920ae8c2012-02-16 09:48:07 +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.)
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000129 void AddToWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000132 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000133
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000134 /// removeFromWorkList - remove all instances of N from the worklist.
135 ///
136 void removeFromWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000137 WorkListContents.erase(N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000138 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000139
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000141 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000142
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000144 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000145 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000146
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000148 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000149 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000150 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000151 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000152
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000154
155 private:
156
Chris Lattner375e1a72006-02-17 21:58:01 +0000157 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000158 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000159 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000160 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000163 return SimplifyDemandedBits(Op, Demanded);
164 }
165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000167
Chris Lattnerffad2162006-11-11 00:39:41 +0000168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000170 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000171
Evan Cheng0abb54d2010-04-24 04:43:44 +0000172 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
173 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
174 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
175 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000176 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000177 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000178 SDValue PromoteExtend(SDValue Op);
179 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000180
Craig Toppere0b71182013-07-13 07:43:40 +0000181 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000182 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000183 ISD::NodeType ExtType);
184
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000185 /// combine - call the node-specific routine that knows how to fold each
186 /// particular type of node. If that doesn't do anything, try the
187 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000188 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000189
190 // Visitation implementation - Implement dag node combining for different
191 // node types. The semantics are as follows:
192 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000193 // SDValue.getNode() == 0 - No change was made
194 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
195 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000196 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000197 SDValue visitTokenFactor(SDNode *N);
198 SDValue visitMERGE_VALUES(SDNode *N);
199 SDValue visitADD(SDNode *N);
200 SDValue visitSUB(SDNode *N);
201 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000202 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000203 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000204 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000205 SDValue visitMUL(SDNode *N);
206 SDValue visitSDIV(SDNode *N);
207 SDValue visitUDIV(SDNode *N);
208 SDValue visitSREM(SDNode *N);
209 SDValue visitUREM(SDNode *N);
210 SDValue visitMULHU(SDNode *N);
211 SDValue visitMULHS(SDNode *N);
212 SDValue visitSMUL_LOHI(SDNode *N);
213 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000214 SDValue visitSMULO(SDNode *N);
215 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000216 SDValue visitSDIVREM(SDNode *N);
217 SDValue visitUDIVREM(SDNode *N);
218 SDValue visitAND(SDNode *N);
219 SDValue visitOR(SDNode *N);
220 SDValue visitXOR(SDNode *N);
221 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000222 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000223 SDValue visitSHL(SDNode *N);
224 SDValue visitSRA(SDNode *N);
225 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000226 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000228 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000229 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000230 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000231 SDValue visitCTPOP(SDNode *N);
232 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000233 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000234 SDValue visitSELECT_CC(SDNode *N);
235 SDValue visitSETCC(SDNode *N);
236 SDValue visitSIGN_EXTEND(SDNode *N);
237 SDValue visitZERO_EXTEND(SDNode *N);
238 SDValue visitANY_EXTEND(SDNode *N);
239 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
240 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000241 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000242 SDValue visitBUILD_PAIR(SDNode *N);
243 SDValue visitFADD(SDNode *N);
244 SDValue visitFSUB(SDNode *N);
245 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000246 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000247 SDValue visitFDIV(SDNode *N);
248 SDValue visitFREM(SDNode *N);
249 SDValue visitFCOPYSIGN(SDNode *N);
250 SDValue visitSINT_TO_FP(SDNode *N);
251 SDValue visitUINT_TO_FP(SDNode *N);
252 SDValue visitFP_TO_SINT(SDNode *N);
253 SDValue visitFP_TO_UINT(SDNode *N);
254 SDValue visitFP_ROUND(SDNode *N);
255 SDValue visitFP_ROUND_INREG(SDNode *N);
256 SDValue visitFP_EXTEND(SDNode *N);
257 SDValue visitFNEG(SDNode *N);
258 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000259 SDValue visitFCEIL(SDNode *N);
260 SDValue visitFTRUNC(SDNode *N);
261 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000262 SDValue visitBRCOND(SDNode *N);
263 SDValue visitBR_CC(SDNode *N);
264 SDValue visitLOAD(SDNode *N);
265 SDValue visitSTORE(SDNode *N);
266 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
267 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
268 SDValue visitBUILD_VECTOR(SDNode *N);
269 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000270 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000271 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000272 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000273
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000274 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000275 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000276
Matt Arsenault985b9de2014-03-17 18:58:01 +0000277 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000278
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000279 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
280 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000281 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
282 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000283 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000284 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000285 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000286 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000287
288 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
289 SDValue &CC) const;
290 bool isOneUseSetCC(SDValue N) const;
291
Scott Michelcf0da6c2009-02-17 22:15:04 +0000292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000293 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000296 SDValue BuildSDIV(SDNode *N);
297 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299 bool DemandHighBits = true);
300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302 SDValue InnerPos, SDValue InnerNeg,
303 unsigned PosOpcode, unsigned NegOpcode,
304 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000306 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000307 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000308 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000311
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000312 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000313
Jim Laskey708d0db2006-10-04 16:53:27 +0000314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000316 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000317 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000318
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000319 /// isAlias - Return true if there is any possibility that the two addresses
320 /// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000321 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000322
Jim Laskeyd07be232006-09-25 16:29:54 +0000323 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000324 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000325 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000326
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000327 /// Merge consecutive store operations into a wide store.
328 /// This optimization uses wide integers or vectors when possible.
329 /// \return True if some memory operations were changed.
330 bool MergeConsecutiveStores(StoreSDNode *N);
331
Adam Nemet67483892014-03-04 23:28:31 +0000332 /// \brief Try to transform a truncation where C is a constant:
333 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
334 ///
335 /// \p N needs to be a truncation and its first operand an AND. Other
336 /// requirements are checked by the function (e.g. that trunc is
337 /// single-use) and if missed an empty SDValue is returned.
338 SDValue distributeTruncateThroughAnd(SDNode *N);
339
Chris Lattner4041ab62010-04-15 04:48:01 +0000340 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000341 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000342 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
343 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
344 AttributeSet FnAttrs =
345 DAG.getMachineFunction().getFunction()->getAttributes();
346 ForCodeSize =
347 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
348 Attribute::OptimizeForSize) ||
349 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
350 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000351
Nate Begeman21158fc2005-09-01 00:19:25 +0000352 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000353 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000354
Chris Lattner4041ab62010-04-15 04:48:01 +0000355 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000356
Chris Lattner4041ab62010-04-15 04:48:01 +0000357 /// getShiftAmountTy - Returns a type large enough to hold any valid
358 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000359 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000360 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
361 if (LHSTy.isVector())
362 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000363 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
364 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000365 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000366
Chris Lattner4041ab62010-04-15 04:48:01 +0000367 /// isTypeLegal - This method returns true if we are running before type
368 /// legalization or if the specified VT is legal.
369 bool isTypeLegal(const EVT &VT) {
370 if (!LegalTypes) return true;
371 return TLI.isTypeLegal(VT);
372 }
Matt Arsenault758659232013-05-18 00:21:46 +0000373
374 /// getSetCCResultType - Convenience wrapper around
375 /// TargetLowering::getSetCCResultType
376 EVT getSetCCResultType(EVT VT) const {
377 return TLI.getSetCCResultType(*DAG.getContext(), VT);
378 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000379 };
380}
381
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000382
383namespace {
384/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
385/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000386class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000387 DAGCombiner &DC;
388public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000389 explicit WorkListRemover(DAGCombiner &dc)
390 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000391
Craig Topper7b883b32014-03-08 06:31:39 +0000392 void NodeDeleted(SDNode *N, SDNode *E) override {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000393 DC.removeFromWorkList(N);
394 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000395};
396}
397
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000398//===----------------------------------------------------------------------===//
399// TargetLowering::DAGCombinerInfo implementation
400//===----------------------------------------------------------------------===//
401
402void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
403 ((DAGCombiner*)DC)->AddToWorkList(N);
404}
405
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000406void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
407 ((DAGCombiner*)DC)->removeFromWorkList(N);
408}
409
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000410SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000411CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
412 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000413}
414
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000415SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000416CombineTo(SDNode *N, SDValue Res, bool AddTo) {
417 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000418}
419
420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000421SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000422CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
423 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000424}
425
Dan Gohmane58ab792009-01-29 01:59:02 +0000426void TargetLowering::DAGCombinerInfo::
427CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
428 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
429}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000430
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000431//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000432// Helper Functions
433//===----------------------------------------------------------------------===//
434
435/// isNegatibleForFree - Return 1 if we can compute the negated form of the
436/// specified expression for the same cost as the expression itself, or 2 if we
437/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000438static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000439 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000440 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000441 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000442 // fneg is removable even if it has multiple uses.
443 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000444
Chris Lattnere49c9742007-05-14 22:04:50 +0000445 // Don't allow anything with multiple uses.
446 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000447
Chris Lattner46980832007-05-25 02:19:06 +0000448 // Don't recurse exponentially.
449 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000450
Chris Lattnere49c9742007-05-14 22:04:50 +0000451 switch (Op.getOpcode()) {
452 default: return false;
453 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000454 // Don't invert constant FP values after legalize. The negated constant
455 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000456 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000457 case ISD::FADD:
458 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000459 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000460
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000461 // After operation legalization, it might not be legal to create new FSUBs.
462 if (LegalOperations &&
463 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
464 return 0;
465
Craig Topper03f39772012-09-09 22:58:45 +0000466 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000467 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
468 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000469 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000470 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000471 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000472 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000473 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000474 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000475 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000476
Bill Wendling6fbf5492009-01-30 23:10:18 +0000477 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000478 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000479
Chris Lattnere49c9742007-05-14 22:04:50 +0000480 case ISD::FMUL:
481 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000482 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000483
Bill Wendling6fbf5492009-01-30 23:10:18 +0000484 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000485 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
486 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000487 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000488
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000489 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000490 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000491
Chris Lattnere49c9742007-05-14 22:04:50 +0000492 case ISD::FP_EXTEND:
493 case ISD::FP_ROUND:
494 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000495 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000496 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000497 }
498}
499
500/// GetNegatedExpression - If isNegatibleForFree returns true, this function
501/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000502static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000503 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000504 // fneg is removable even if it has multiple uses.
505 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000506
Chris Lattnere49c9742007-05-14 22:04:50 +0000507 // Don't allow anything with multiple uses.
508 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000509
Chris Lattner46980832007-05-25 02:19:06 +0000510 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000511 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000512 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000513 case ISD::ConstantFP: {
514 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
515 V.changeSign();
516 return DAG.getConstantFP(V, Op.getValueType());
517 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000518 case ISD::FADD:
519 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000520 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000521
Bill Wendling6fbf5492009-01-30 23:10:18 +0000522 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000523 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000524 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000525 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000526 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000527 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000528 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000529 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000530 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
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(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000533 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000534 Op.getOperand(0));
535 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000536 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000537 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000538
Bill Wendling6fbf5492009-01-30 23:10:18 +0000539 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000540 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000541 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000542 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000543
Bill Wendling6fbf5492009-01-30 23:10:18 +0000544 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000545 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000546 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000547
Chris Lattnere49c9742007-05-14 22:04:50 +0000548 case ISD::FMUL:
549 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000550 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000551
Bill Wendling6fbf5492009-01-30 23:10:18 +0000552 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000553 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000554 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000555 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000556 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000557 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000558 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000559 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000560
Bill Wendling6fbf5492009-01-30 23:10:18 +0000561 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000562 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000563 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000564 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000565 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000566
Chris Lattnere49c9742007-05-14 22:04:50 +0000567 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000568 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000569 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000570 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000571 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000572 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000573 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000574 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000575 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000576 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000577 }
578}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000579
Nate Begeman2504fe22005-09-01 23:24:04 +0000580// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000581// that selects between the target values used for true and false, making it
582// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
583// the appropriate nodes based on the type of node we are checking. This
584// simplifies life a bit for the callers.
585bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
586 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000587 if (N.getOpcode() == ISD::SETCC) {
588 LHS = N.getOperand(0);
589 RHS = N.getOperand(1);
590 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000591 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000592 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000593
594 if (N.getOpcode() != ISD::SELECT_CC ||
595 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
596 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
597 return false;
598
599 LHS = N.getOperand(0);
600 RHS = N.getOperand(1);
601 CC = N.getOperand(4);
602 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000603}
604
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000605// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
606// one use. If this is true, it allows the users to invert the operation for
607// free when it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000608bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000609 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000610 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000611 return true;
612 return false;
613}
614
Matt Arsenault985b9de2014-03-17 18:58:01 +0000615/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
616/// elements are all the same constant or undefined.
617static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
618 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
619 if (!C)
620 return false;
621
622 APInt SplatUndef;
623 unsigned SplatBitSize;
624 bool HasAnyUndefs;
625 EVT EltVT = N->getValueType(0).getVectorElementType();
626 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
627 HasAnyUndefs) &&
628 EltVT.getSizeInBits() >= SplatBitSize);
629}
630
631// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000632static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
633 if (isa<ConstantSDNode>(N))
634 return N.getNode();
635 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
636 if(BV && BV->isConstant())
637 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000638 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000639}
640
Matt Arsenault985b9de2014-03-17 18:58:01 +0000641// \brief Returns the SDNode if it is a constant splat BuildVector or constant
642// int.
643static ConstantSDNode *isConstOrConstSplat(SDValue N) {
644 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
645 return CN;
646
647 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
Andrea Di Biagio5b0aacf2014-03-22 01:47:22 +0000648 return BV->getConstantSplatValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +0000649
650 return nullptr;
651}
652
Andrew Trickef9de2a2013-05-25 02:42:55 +0000653SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000654 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000655 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000656 if (N0.getOpcode() == Opc) {
657 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
658 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
659 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
660 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
661 if (!OpNode.getNode())
662 return SDValue();
663 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000664 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000665 if (N0.hasOneUse()) {
666 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
667 // use
668 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
669 if (!OpNode.getNode())
670 return SDValue();
671 AddToWorkList(OpNode.getNode());
672 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000673 }
674 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000675 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000676
Juergen Ributzka68402822014-01-13 21:49:25 +0000677 if (N1.getOpcode() == Opc) {
678 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
679 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
680 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
681 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
682 if (!OpNode.getNode())
683 return SDValue();
684 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
685 }
686 if (N1.hasOneUse()) {
687 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
688 // use
689 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
690 if (!OpNode.getNode())
691 return SDValue();
692 AddToWorkList(OpNode.getNode());
693 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
694 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000695 }
696 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000697
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000698 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000699}
700
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000701SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
702 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000703 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
704 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000705 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000706 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000707 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000708 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000709 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000710 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000711 assert((!To[i].getNode() ||
712 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000713 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000714 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000715 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000716 if (AddTo) {
717 // Push the new nodes and any users onto the worklist
718 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000719 if (To[i].getNode()) {
720 AddToWorkList(To[i].getNode());
721 AddUsersToWorkList(To[i].getNode());
722 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000723 }
724 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000725
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000726 // Finally, if the node is now dead, remove it from the graph. The node
727 // may not be dead if the replacement process recursively simplified to
728 // something else needing this node.
729 if (N->use_empty()) {
730 // Nodes can be reintroduced into the worklist. Make sure we do not
731 // process a node that has been replaced.
732 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000733
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000734 // Finally, since the node is now dead, remove it from the graph.
735 DAG.DeleteNode(N);
736 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000737 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000738}
739
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000740void DAGCombiner::
741CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000742 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000743 // are deleted, make sure to remove them from our worklist.
744 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000745 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000746
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000747 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000748 AddToWorkList(TLO.New.getNode());
749 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000750
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000751 // Finally, if the node is now dead, remove it from the graph. The node
752 // may not be dead if the replacement process recursively simplified to
753 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000754 if (TLO.Old.getNode()->use_empty()) {
755 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000756
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000757 // If the operands of this node are only used by the node, they will now
758 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000759 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
760 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
761 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000762
Gabor Greiff304a7a2008-08-28 21:40:38 +0000763 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000764 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000765}
766
767/// SimplifyDemandedBits - Check the specified integer node value to see if
768/// it can be simplified or if things it uses can be simplified by bit
769/// propagation. If so, return true.
770bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000771 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000772 APInt KnownZero, KnownOne;
773 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
774 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000775
Dan Gohmane58ab792009-01-29 01:59:02 +0000776 // Revisit the node.
777 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000778
Dan Gohmane58ab792009-01-29 01:59:02 +0000779 // Replace the old value with the new one.
780 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000781 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000782 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000783 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000784 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000785 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000786
Dan Gohmane58ab792009-01-29 01:59:02 +0000787 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000788 return true;
789}
790
Evan Cheng0abb54d2010-04-24 04:43:44 +0000791void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000792 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000793 EVT VT = Load->getValueType(0);
794 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000795
Evan Cheng0abb54d2010-04-24 04:43:44 +0000796 DEBUG(dbgs() << "\nReplacing.9 ";
797 Load->dump(&DAG);
798 dbgs() << "\nWith: ";
799 Trunc.getNode()->dump(&DAG);
800 dbgs() << '\n');
801 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000802 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
803 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000804 removeFromWorkList(Load);
805 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000806 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000807}
808
809SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
810 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000811 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000812 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000813 EVT MemVT = LD->getMemoryVT();
814 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000815 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000816 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000817 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000818 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000819 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000820 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000821 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000822 }
823
Evan Chenge19aa5c2010-04-19 19:29:22 +0000824 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000825 switch (Opc) {
826 default: break;
827 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000828 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000829 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000830 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000831 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000832 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000833 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000834 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000835 case ISD::Constant: {
836 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000837 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000838 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000839 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000840 }
841
842 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000843 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000844 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000845}
846
Evan Cheng0abb54d2010-04-24 04:43:44 +0000847SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000848 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
849 return SDValue();
850 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000851 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000852 bool Replace = false;
853 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000854 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000855 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000856 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000857
858 if (Replace)
859 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
860 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000861 DAG.getValueType(OldVT));
862}
863
Evan Cheng0abb54d2010-04-24 04:43:44 +0000864SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000865 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000866 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000867 bool Replace = false;
868 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000869 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000870 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000871 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000872
873 if (Replace)
874 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
875 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000876}
877
Evan Chengaf56fac2010-04-16 06:14:10 +0000878/// PromoteIntBinOp - Promote the specified integer binary operation if the
879/// target indicates it is beneficial. e.g. On x86, it's usually better to
880/// promote i16 operations to i32 since i16 instructions are longer.
881SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
882 if (!LegalOperations)
883 return SDValue();
884
885 EVT VT = Op.getValueType();
886 if (VT.isVector() || !VT.isInteger())
887 return SDValue();
888
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000889 // If operation type is 'undesirable', e.g. i16 on x86, consider
890 // promoting it.
891 unsigned Opc = Op.getOpcode();
892 if (TLI.isTypeDesirableForOp(Opc, VT))
893 return SDValue();
894
Evan Chengaf56fac2010-04-16 06:14:10 +0000895 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000896 // Consult target whether it is a good idea to promote this operation and
897 // what's the right type to promote it to.
898 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000899 assert(PVT != VT && "Don't know what type to promote to!");
900
Evan Cheng0abb54d2010-04-24 04:43:44 +0000901 bool Replace0 = false;
902 SDValue N0 = Op.getOperand(0);
903 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000904 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000905 return SDValue();
906
Evan Cheng0abb54d2010-04-24 04:43:44 +0000907 bool Replace1 = false;
908 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000909 SDValue NN1;
910 if (N0 == N1)
911 NN1 = NN0;
912 else {
913 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000914 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000915 return SDValue();
916 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000917
Evan Cheng0abb54d2010-04-24 04:43:44 +0000918 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000919 if (NN1.getNode())
920 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000921
922 if (Replace0)
923 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
924 if (Replace1)
925 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000926
Evan Chenge8136902010-04-27 19:48:13 +0000927 DEBUG(dbgs() << "\nPromoting ";
928 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000929 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000930 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000931 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000932 }
933 return SDValue();
934}
935
936/// PromoteIntShiftOp - Promote the specified integer shift operation if the
937/// target indicates it is beneficial. e.g. On x86, it's usually better to
938/// promote i16 operations to i32 since i16 instructions are longer.
939SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
940 if (!LegalOperations)
941 return SDValue();
942
943 EVT VT = Op.getValueType();
944 if (VT.isVector() || !VT.isInteger())
945 return SDValue();
946
947 // If operation type is 'undesirable', e.g. i16 on x86, consider
948 // promoting it.
949 unsigned Opc = Op.getOpcode();
950 if (TLI.isTypeDesirableForOp(Opc, VT))
951 return SDValue();
952
953 EVT PVT = VT;
954 // Consult target whether it is a good idea to promote this operation and
955 // what's the right type to promote it to.
956 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957 assert(PVT != VT && "Don't know what type to promote to!");
958
Evan Cheng0abb54d2010-04-24 04:43:44 +0000959 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000960 SDValue N0 = Op.getOperand(0);
961 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000962 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000963 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000964 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000965 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000966 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000967 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000968 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000969
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000970 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000971 if (Replace)
972 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000973
Evan Chenge8136902010-04-27 19:48:13 +0000974 DEBUG(dbgs() << "\nPromoting ";
975 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000976 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000977 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000978 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000979 }
980 return SDValue();
981}
982
Evan Chenge19aa5c2010-04-19 19:29:22 +0000983SDValue DAGCombiner::PromoteExtend(SDValue Op) {
984 if (!LegalOperations)
985 return SDValue();
986
987 EVT VT = Op.getValueType();
988 if (VT.isVector() || !VT.isInteger())
989 return SDValue();
990
991 // If operation type is 'undesirable', e.g. i16 on x86, consider
992 // promoting it.
993 unsigned Opc = Op.getOpcode();
994 if (TLI.isTypeDesirableForOp(Opc, VT))
995 return SDValue();
996
997 EVT PVT = VT;
998 // Consult target whether it is a good idea to promote this operation and
999 // what's the right type to promote it to.
1000 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1001 assert(PVT != VT && "Don't know what type to promote to!");
1002 // fold (aext (aext x)) -> (aext x)
1003 // fold (aext (zext x)) -> (zext x)
1004 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001005 DEBUG(dbgs() << "\nPromoting ";
1006 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001007 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001008 }
1009 return SDValue();
1010}
1011
1012bool DAGCombiner::PromoteLoad(SDValue Op) {
1013 if (!LegalOperations)
1014 return false;
1015
1016 EVT VT = Op.getValueType();
1017 if (VT.isVector() || !VT.isInteger())
1018 return false;
1019
1020 // If operation type is 'undesirable', e.g. i16 on x86, consider
1021 // promoting it.
1022 unsigned Opc = Op.getOpcode();
1023 if (TLI.isTypeDesirableForOp(Opc, VT))
1024 return false;
1025
1026 EVT PVT = VT;
1027 // Consult target whether it is a good idea to promote this operation and
1028 // what's the right type to promote it to.
1029 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1030 assert(PVT != VT && "Don't know what type to promote to!");
1031
Andrew Trickef9de2a2013-05-25 02:42:55 +00001032 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001033 SDNode *N = Op.getNode();
1034 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001035 EVT MemVT = LD->getMemoryVT();
1036 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001037 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001038 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001039 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001040 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001041 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001042 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001043 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1044
Evan Cheng0abb54d2010-04-24 04:43:44 +00001045 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001046 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001047 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001048 Result.getNode()->dump(&DAG);
1049 dbgs() << '\n');
1050 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001051 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1052 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001053 removeFromWorkList(N);
1054 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001055 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001056 return true;
1057 }
1058 return false;
1059}
1060
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001061
Chris Lattnere49c9742007-05-14 22:04:50 +00001062//===----------------------------------------------------------------------===//
1063// Main DAG Combiner implementation
1064//===----------------------------------------------------------------------===//
1065
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001066void DAGCombiner::Run(CombineLevel AtLevel) {
1067 // set the instance variables, so that the various visit routines may use it.
1068 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001069 LegalOperations = Level >= AfterLegalizeVectorOps;
1070 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001071
Evan Cheng5e7658c2008-08-29 22:21:44 +00001072 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001073 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1074 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001075 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001076
Evan Cheng5e7658c2008-08-29 22:21:44 +00001077 // Create a dummy node (which is not added to allnodes), that adds a reference
1078 // to the root node, preventing it from being deleted, and tracking any
1079 // changes of the root.
1080 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001081
Jim Laskeye7d2c242006-10-17 19:33:52 +00001082 // The root of the dag may dangle to deleted nodes until the dag combiner is
1083 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001084 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001085
James Molloy67b6b112012-02-16 09:17:04 +00001086 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001087 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001088 while (!WorkListContents.empty()) {
1089 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001090 // The WorkListOrder holds the SDNodes in order, but it may contain
1091 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001092 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1093 // worklist *should* contain, and check the node we want to visit is should
1094 // actually be visited.
1095 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001096 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001097 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001098
Evan Cheng5e7658c2008-08-29 22:21:44 +00001099 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1100 // N is deleted from the DAG, since they too may now be dead or may have a
1101 // reduced number of uses, allowing other xforms.
1102 if (N->use_empty() && N != &Dummy) {
1103 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1104 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001105
Evan Cheng5e7658c2008-08-29 22:21:44 +00001106 DAG.DeleteNode(N);
1107 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001108 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001109
Evan Cheng5e7658c2008-08-29 22:21:44 +00001110 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001111
Craig Topperc0196b12014-04-14 00:51:57 +00001112 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001113 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001114
Evan Cheng5e7658c2008-08-29 22:21:44 +00001115 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001116
Evan Cheng5e7658c2008-08-29 22:21:44 +00001117 // If we get back the same node we passed in, rather than a new node or
1118 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001119 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001120 // mechanics for us, we have no work to do in this case.
1121 if (RV.getNode() == N)
1122 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001123
Evan Cheng5e7658c2008-08-29 22:21:44 +00001124 assert(N->getOpcode() != ISD::DELETED_NODE &&
1125 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1126 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001127
Wesley Peck527da1b2010-11-23 03:31:01 +00001128 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001129 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001130 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001131 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001132 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001133
Devang Patelefec7712011-05-23 22:04:42 +00001134 // Transfer debug value.
1135 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001136 WorkListRemover DeadNodes(*this);
1137 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001138 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001139 else {
1140 assert(N->getValueType(0) == RV.getValueType() &&
1141 N->getNumValues() == 1 && "Type mismatch");
1142 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001143 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001145
Evan Cheng5e7658c2008-08-29 22:21:44 +00001146 // Push the new node and any users onto the worklist
1147 AddToWorkList(RV.getNode());
1148 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001149
Evan Cheng5e7658c2008-08-29 22:21:44 +00001150 // Add any uses of the old node to the worklist in case this node is the
1151 // last one that uses them. They may become dead after this node is
1152 // deleted.
1153 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1154 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001155
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001156 // Finally, if the node is now dead, remove it from the graph. The node
1157 // may not be dead if the replacement process recursively simplified to
1158 // something else needing this node.
1159 if (N->use_empty()) {
1160 // Nodes can be reintroduced into the worklist. Make sure we do not
1161 // process a node that has been replaced.
1162 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001163
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001164 // Finally, since the node is now dead, remove it from the graph.
1165 DAG.DeleteNode(N);
1166 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001167 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001168
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001169 // If the root changed (e.g. it was a dead load, update the root).
1170 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001171 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001172}
1173
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001174SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001175 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001176 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001177 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001178 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001179 case ISD::ADD: return visitADD(N);
1180 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001181 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001182 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001183 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001184 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001185 case ISD::MUL: return visitMUL(N);
1186 case ISD::SDIV: return visitSDIV(N);
1187 case ISD::UDIV: return visitUDIV(N);
1188 case ISD::SREM: return visitSREM(N);
1189 case ISD::UREM: return visitUREM(N);
1190 case ISD::MULHU: return visitMULHU(N);
1191 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001192 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1193 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001194 case ISD::SMULO: return visitSMULO(N);
1195 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001196 case ISD::SDIVREM: return visitSDIVREM(N);
1197 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001198 case ISD::AND: return visitAND(N);
1199 case ISD::OR: return visitOR(N);
1200 case ISD::XOR: return visitXOR(N);
1201 case ISD::SHL: return visitSHL(N);
1202 case ISD::SRA: return visitSRA(N);
1203 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001204 case ISD::ROTR:
1205 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001206 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001207 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001208 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001209 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001210 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001211 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001212 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001213 case ISD::SELECT_CC: return visitSELECT_CC(N);
1214 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001215 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1216 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001217 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001218 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1219 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001220 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001221 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001222 case ISD::FADD: return visitFADD(N);
1223 case ISD::FSUB: return visitFSUB(N);
1224 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001225 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001226 case ISD::FDIV: return visitFDIV(N);
1227 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001228 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001229 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1230 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1231 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1232 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1233 case ISD::FP_ROUND: return visitFP_ROUND(N);
1234 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1235 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1236 case ISD::FNEG: return visitFNEG(N);
1237 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001238 case ISD::FFLOOR: return visitFFLOOR(N);
1239 case ISD::FCEIL: return visitFCEIL(N);
1240 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001241 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001242 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001243 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001244 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001245 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001246 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001247 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1248 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001249 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001250 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001251 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001252 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001253 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001254}
1255
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001256SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001257 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001258
1259 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001260 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001261 assert(N->getOpcode() != ISD::DELETED_NODE &&
1262 "Node was deleted but visit returned NULL!");
1263
1264 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1265 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1266
1267 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001268 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001269 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001270
1271 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1272 }
1273 }
1274
Evan Chengf1005572010-04-28 07:10:39 +00001275 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001276 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001277 switch (N->getOpcode()) {
1278 default: break;
1279 case ISD::ADD:
1280 case ISD::SUB:
1281 case ISD::MUL:
1282 case ISD::AND:
1283 case ISD::OR:
1284 case ISD::XOR:
1285 RV = PromoteIntBinOp(SDValue(N, 0));
1286 break;
1287 case ISD::SHL:
1288 case ISD::SRA:
1289 case ISD::SRL:
1290 RV = PromoteIntShiftOp(SDValue(N, 0));
1291 break;
1292 case ISD::SIGN_EXTEND:
1293 case ISD::ZERO_EXTEND:
1294 case ISD::ANY_EXTEND:
1295 RV = PromoteExtend(SDValue(N, 0));
1296 break;
1297 case ISD::LOAD:
1298 if (PromoteLoad(SDValue(N, 0)))
1299 RV = SDValue(N, 0);
1300 break;
1301 }
1302 }
1303
Scott Michelcf0da6c2009-02-17 22:15:04 +00001304 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001305 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001306 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001307 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001308 SDValue N0 = N->getOperand(0);
1309 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001310
Evan Cheng31604a62008-03-22 01:55:50 +00001311 // Constant operands are canonicalized to RHS.
1312 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001313 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001314 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1315 Ops, 2);
Evan Chengfe7610f2008-03-24 23:55:16 +00001316 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001317 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001318 }
1319 }
1320
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001321 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001322}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001323
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001324/// getInputChainForNode - Given a node, return its input chain if it has one,
1325/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001326static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001327 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001328 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001329 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001330 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001331 return N->getOperand(NumOps-1);
1332 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001333 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001334 return N->getOperand(i);
1335 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001336 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001337}
1338
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001339SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001340 // If N has two operands, where one has an input chain equal to the other,
1341 // the 'other' chain is redundant.
1342 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001343 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001344 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001345 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001346 return N->getOperand(1);
1347 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001348
Chris Lattner48fb92f2007-05-16 06:37:59 +00001349 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001350 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001351 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001352 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001353
Jim Laskey708d0db2006-10-04 16:53:27 +00001354 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001355 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001356
Jim Laskey0463e082006-10-07 23:37:56 +00001357 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001358 // encountered.
1359 for (unsigned i = 0; i < TFs.size(); ++i) {
1360 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001361
Jim Laskey708d0db2006-10-04 16:53:27 +00001362 // Check each of the operands.
1363 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001364 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001365
Jim Laskey708d0db2006-10-04 16:53:27 +00001366 switch (Op.getOpcode()) {
1367 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001368 // Entry tokens don't need to be added to the list. They are
1369 // rededundant.
1370 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001371 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001372
Jim Laskey708d0db2006-10-04 16:53:27 +00001373 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001374 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001375 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001376 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001377 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001378 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001379 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001380 Changed = true;
1381 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001382 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001383 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001384
Jim Laskey708d0db2006-10-04 16:53:27 +00001385 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001386 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001387 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001388 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001389 else
1390 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001391 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001392 }
1393 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001394 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001395
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001396 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001397
1398 // If we've change things around then replace token factor.
1399 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001400 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001401 // The entry token is the only possible outcome.
1402 Result = DAG.getEntryNode();
1403 } else {
1404 // New and improved token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001405 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00001406 MVT::Other, &Ops[0], Ops.size());
Nate Begeman02b23c62005-10-13 03:11:28 +00001407 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001408
Jim Laskeydcf983c2006-10-13 23:32:28 +00001409 // Don't add users to work list.
1410 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001411 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001412
Jim Laskey708d0db2006-10-04 16:53:27 +00001413 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001414}
1415
Chris Lattneree322b42008-02-13 07:25:05 +00001416/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001417SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001418 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001419 // Replacing results may cause a different MERGE_VALUES to suddenly
1420 // be CSE'd with N, and carry its uses with it. Iterate until no
1421 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001422 // First add the users of this node to the work list so that they
1423 // can be tried again once they have new operands.
1424 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001425 do {
1426 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001427 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001428 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001429 removeFromWorkList(N);
1430 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001431 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001432}
1433
Evan Cheng92011002007-01-19 17:51:44 +00001434static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001435SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001436 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001437 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001438 SDValue N00 = N0.getOperand(0);
1439 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001440 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001441
Gabor Greiff304a7a2008-08-28 21:40:38 +00001442 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001443 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001444 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001445 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1446 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001447 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001448 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001449 N00.getOperand(1), N01));
1450 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001451 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001452
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001453 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001454}
1455
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001456SDValue DAGCombiner::visitADD(SDNode *N) {
1457 SDValue N0 = N->getOperand(0);
1458 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001459 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1460 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001461 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001462
1463 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001464 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001465 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001466 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001467
1468 // fold (add x, 0) -> x, vector edition
1469 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1470 return N0;
1471 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1472 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001473 }
Bill Wendling0864a752008-12-10 22:36:00 +00001474
Dan Gohman06563a82007-07-03 14:03:57 +00001475 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001476 if (N0.getOpcode() == ISD::UNDEF)
1477 return N0;
1478 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001479 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001480 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001481 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001482 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001483 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001484 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001485 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001486 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001487 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001488 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001489 // fold (add Sym, c) -> Sym+c
1490 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001491 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001492 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001493 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001494 GA->getOffset() +
1495 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001496 // fold ((c1-A)+c2) -> (c1+c2)-A
1497 if (N1C && N0.getOpcode() == ISD::SUB)
1498 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001499 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001500 DAG.getConstant(N1C->getAPIntValue()+
1501 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001502 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001503 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001504 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001505 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001506 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001507 // fold ((0-A) + B) -> B-A
1508 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1509 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001510 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001511 // fold (A + (0-B)) -> A-B
1512 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1513 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001514 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001515 // fold (A+(B-A)) -> B
1516 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001517 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001518 // fold ((B-A)+A) -> B
1519 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1520 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001521 // fold (A+(B-(A+C))) to (B-C)
1522 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001523 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001524 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001525 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001526 // fold (A+(B-(C+A))) to (B-C)
1527 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001528 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001529 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001530 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001531 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001532 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1533 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001534 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001535 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001536 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001537
Dale Johannesen8c766702008-12-02 01:30:54 +00001538 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1539 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1540 SDValue N00 = N0.getOperand(0);
1541 SDValue N01 = N0.getOperand(1);
1542 SDValue N10 = N1.getOperand(0);
1543 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001544
1545 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001546 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1547 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1548 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001549 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001550
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001551 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1552 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001553
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001554 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001555 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001556 APInt LHSZero, LHSOne;
1557 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001558 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001559
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001560 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001561 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001562
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001563 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1564 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001565 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1566 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1567 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1568 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001569 }
1570 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001571
Evan Cheng92011002007-01-19 17:51:44 +00001572 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001573 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001574 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001575 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001576 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001577 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001578 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001579 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001580 }
1581
Dan Gohman954f4902010-01-19 23:30:49 +00001582 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1583 if (N1.getOpcode() == ISD::SHL &&
1584 N1.getOperand(0).getOpcode() == ISD::SUB)
1585 if (ConstantSDNode *C =
1586 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1587 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001588 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1589 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001590 N1.getOperand(0).getOperand(1),
1591 N1.getOperand(1)));
1592 if (N0.getOpcode() == ISD::SHL &&
1593 N0.getOperand(0).getOpcode() == ISD::SUB)
1594 if (ConstantSDNode *C =
1595 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1596 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001597 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1598 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001599 N0.getOperand(0).getOperand(1),
1600 N0.getOperand(1)));
1601
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001602 if (N1.getOpcode() == ISD::AND) {
1603 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001604 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001605 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1606 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001607
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001608 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1609 // and similar xforms where the inner op is either ~0 or 0.
1610 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001611 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001612 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1613 }
1614 }
1615
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001616 // add (sext i1), X -> sub X, (zext i1)
1617 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1618 N0.getOperand(0).getValueType() == MVT::i1 &&
1619 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001620 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001621 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1622 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1623 }
1624
Evan Chengf1005572010-04-28 07:10:39 +00001625 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001626}
1627
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001628SDValue DAGCombiner::visitADDC(SDNode *N) {
1629 SDValue N0 = N->getOperand(0);
1630 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001631 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1632 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001633 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001634
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001635 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001636 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001637 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001638 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001639 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001640
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001641 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001642 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001643 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001644
Chris Lattner47206662007-03-04 20:40:38 +00001645 // fold (addc x, 0) -> x + no carry out
1646 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001647 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001648 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001649
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001650 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001651 APInt LHSZero, LHSOne;
1652 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001653 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001654
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001655 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001656 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001657
Chris Lattner47206662007-03-04 20:40:38 +00001658 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1659 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001660 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001661 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001662 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001663 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001664 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001665
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001666 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001667}
1668
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001669SDValue DAGCombiner::visitADDE(SDNode *N) {
1670 SDValue N0 = N->getOperand(0);
1671 SDValue N1 = N->getOperand(1);
1672 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001673 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1674 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001675
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001676 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001677 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001678 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001679 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001680
Chris Lattner47206662007-03-04 20:40:38 +00001681 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001682 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001683 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001684
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001685 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001686}
1687
Eric Christophere5ca1e02011-02-16 04:50:12 +00001688// Since it may not be valid to emit a fold to zero for vector initializers
1689// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001690static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001691 SelectionDAG &DAG,
1692 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001693 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001694 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001695 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1696 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001697 return SDValue();
1698}
1699
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001700SDValue DAGCombiner::visitSUB(SDNode *N) {
1701 SDValue N0 = N->getOperand(0);
1702 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001703 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1704 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001705 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001706 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001707 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001708
Dan Gohmana8665142007-06-25 16:23:39 +00001709 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001710 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001711 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001712 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001713
1714 // fold (sub x, 0) -> x, vector edition
1715 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1716 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001717 }
Bill Wendling0864a752008-12-10 22:36:00 +00001718
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001719 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001720 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001721 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001722 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001723 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001724 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001725 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001726 // fold (sub x, c) -> (add x, -c)
1727 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001728 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001729 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001730 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1731 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001732 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001733 // fold A-(A-B) -> B
1734 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1735 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001736 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001737 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001738 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001739 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001740 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001741 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001742 // fold C2-(A+C1) -> (C2-C1)-A
1743 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001744 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1745 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001746 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001747 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001748 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001749 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001750 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001751 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1752 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001753 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001754 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001755 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001756 // fold ((A+(C+B))-B) -> A+C
1757 if (N0.getOpcode() == ISD::ADD &&
1758 N0.getOperand(1).getOpcode() == ISD::ADD &&
1759 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001760 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001761 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001762 // fold ((A-(B-C))-C) -> A-B
1763 if (N0.getOpcode() == ISD::SUB &&
1764 N0.getOperand(1).getOpcode() == ISD::SUB &&
1765 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001766 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001767 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001768
Dan Gohman06563a82007-07-03 14:03:57 +00001769 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001770 if (N0.getOpcode() == ISD::UNDEF)
1771 return N0;
1772 if (N1.getOpcode() == ISD::UNDEF)
1773 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001774
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001775 // If the relocation model supports it, consider symbol offsets.
1776 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001777 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001778 // fold (sub Sym, c) -> Sym-c
1779 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001780 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001781 GA->getOffset() -
1782 (uint64_t)N1C->getSExtValue());
1783 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1784 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1785 if (GA->getGlobal() == GB->getGlobal())
1786 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1787 VT);
1788 }
1789
Evan Chengf1005572010-04-28 07:10:39 +00001790 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001791}
1792
Craig Topper43a1bd62012-01-07 09:06:39 +00001793SDValue DAGCombiner::visitSUBC(SDNode *N) {
1794 SDValue N0 = N->getOperand(0);
1795 SDValue N1 = N->getOperand(1);
1796 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1797 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1798 EVT VT = N0.getValueType();
1799
1800 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001801 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001802 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1803 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001804 MVT::Glue));
1805
1806 // fold (subc x, x) -> 0 + no borrow
1807 if (N0 == N1)
1808 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001809 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001810 MVT::Glue));
1811
1812 // fold (subc x, 0) -> x + no borrow
1813 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001814 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001815 MVT::Glue));
1816
1817 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1818 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001819 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1820 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001821 MVT::Glue));
1822
1823 return SDValue();
1824}
1825
1826SDValue DAGCombiner::visitSUBE(SDNode *N) {
1827 SDValue N0 = N->getOperand(0);
1828 SDValue N1 = N->getOperand(1);
1829 SDValue CarryIn = N->getOperand(2);
1830
1831 // fold (sube x, y, false) -> (subc x, y)
1832 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001833 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001834
1835 return SDValue();
1836}
1837
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001838SDValue DAGCombiner::visitMUL(SDNode *N) {
1839 SDValue N0 = N->getOperand(0);
1840 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001841 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001842
Dan Gohman06563a82007-07-03 14:03:57 +00001843 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001844 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001845 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001846
1847 bool N0IsConst = false;
1848 bool N1IsConst = false;
1849 APInt ConstValue0, ConstValue1;
1850 // fold vector ops
1851 if (VT.isVector()) {
1852 SDValue FoldedVOp = SimplifyVBinOp(N);
1853 if (FoldedVOp.getNode()) return FoldedVOp;
1854
1855 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1856 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1857 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001858 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001859 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1860 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001861 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001862 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1863 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001864 }
1865
Nate Begeman21158fc2005-09-01 00:19:25 +00001866 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001867 if (N0IsConst && N1IsConst)
1868 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1869
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001870 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001871 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001872 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001873 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001874 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001875 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001876 // We require a splat of the entire scalar bit width for non-contiguous
1877 // bit patterns.
1878 bool IsFullSplat =
1879 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001880 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001881 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001882 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001883 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001884 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001885 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001886 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001887 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001888 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001889 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001890 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001891 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001892 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001893 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001894 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001895 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001896 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001897 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001898 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001899 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001900 DAG.getConstant(Log2Val,
1901 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001902 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001903
1904 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001905 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001906 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001907 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1908 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001909 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001910 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001911 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001912 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001913 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001914 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001915
Chris Lattner324871e2006-03-01 03:44:24 +00001916 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1917 // use.
1918 {
Craig Topperc0196b12014-04-14 00:51:57 +00001919 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001920 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001921 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001922 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1923 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001924 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001925 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001926 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001927 isa<ConstantSDNode>(N1.getOperand(1)) &&
1928 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001929 Sh = N1; Y = N0;
1930 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001931
Gabor Greiff304a7a2008-08-28 21:40:38 +00001932 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001933 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001934 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001935 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001936 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001937 }
1938 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001939
Chris Lattnerf29f5202006-03-04 23:33:26 +00001940 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001941 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001944 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1945 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001946 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001947 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001948 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001949
Nate Begeman22e251a2006-02-03 06:46:56 +00001950 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001951 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001952 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001953 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001954
Evan Chengf1005572010-04-28 07:10:39 +00001955 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001956}
1957
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001958SDValue DAGCombiner::visitSDIV(SDNode *N) {
1959 SDValue N0 = N->getOperand(0);
1960 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001961 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1962 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001963 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001964
Dan Gohmana8665142007-06-25 16:23:39 +00001965 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001966 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001967 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001968 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001969 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001970
Nate Begeman21158fc2005-09-01 00:19:25 +00001971 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001972 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001973 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001974 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001975 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001976 return N0;
1977 // fold (sdiv X, -1) -> 0-X
1978 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001979 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00001980 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00001981 // If we know the sign bits of both operands are zero, strength reduce to a
1982 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00001983 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00001984 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001985 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00001986 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00001987 }
Nate Begeman57b35672006-02-17 07:26:20 +00001988 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedmanf9081a82011-12-07 03:55:52 +00001989 if (N1C && !N1C->isNullValue() &&
Eli Friedmane9e356a2011-10-27 02:06:39 +00001990 (N1C->getAPIntValue().isPowerOf2() ||
1991 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00001992 // If dividing by powers of two is cheap, then don't perform the following
1993 // fold.
1994 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001995 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00001996
Eli Friedmane9e356a2011-10-27 02:06:39 +00001997 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00001998
Chris Lattner471627c2006-02-16 08:02:36 +00001999 // Splat the sign bit into the register
Andrew Trickef9de2a2013-05-25 02:42:55 +00002000 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling5b663e72009-01-30 02:52:17 +00002001 DAG.getConstant(VT.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002002 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002003 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002004
Chris Lattner471627c2006-02-16 08:02:36 +00002005 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002006 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling5b663e72009-01-30 02:52:17 +00002007 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002008 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002009 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002010 AddToWorkList(SRL.getNode());
2011 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002012 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002013 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002014
Nate Begeman4dd38312005-10-21 00:02:42 +00002015 // If we're dividing by a positive value, we're done. Otherwise, we must
2016 // negate the result.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002017 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002018 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002019
Gabor Greiff304a7a2008-08-28 21:40:38 +00002020 AddToWorkList(SRA.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002021 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002022 DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002023 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002024
Nate Begemanc6f067a2005-10-20 02:15:44 +00002025 // if integer divide is expensive and we satisfy the requirements, emit an
2026 // alternate sequence.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002027 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002028 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002029 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002030 }
Dan Gohmana8665142007-06-25 16:23:39 +00002031
Dan Gohman06563a82007-07-03 14:03:57 +00002032 // undef / X -> 0
2033 if (N0.getOpcode() == ISD::UNDEF)
2034 return DAG.getConstant(0, VT);
2035 // X / undef -> undef
2036 if (N1.getOpcode() == ISD::UNDEF)
2037 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002038
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002039 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002040}
2041
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002042SDValue DAGCombiner::visitUDIV(SDNode *N) {
2043 SDValue N0 = N->getOperand(0);
2044 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002045 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2046 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00002047 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002048
Dan Gohmana8665142007-06-25 16:23:39 +00002049 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002050 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002051 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002052 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002053 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002054
Nate Begeman21158fc2005-09-01 00:19:25 +00002055 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002056 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002057 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002058 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002059 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002060 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002061 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002062 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002063 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002064 if (N1.getOpcode() == ISD::SHL) {
2065 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002066 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002067 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002068 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002069 N1.getOperand(1),
2070 DAG.getConstant(SHC->getAPIntValue()
2071 .logBase2(),
2072 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002073 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002074 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002075 }
2076 }
2077 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002078 // fold (udiv x, c) -> alternate
Dan Gohmanb72127a2008-03-13 22:13:53 +00002079 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002080 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002081 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002082 }
Dan Gohmana8665142007-06-25 16:23:39 +00002083
Dan Gohman06563a82007-07-03 14:03:57 +00002084 // undef / X -> 0
2085 if (N0.getOpcode() == ISD::UNDEF)
2086 return DAG.getConstant(0, VT);
2087 // X / undef -> undef
2088 if (N1.getOpcode() == ISD::UNDEF)
2089 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002090
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002091 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002092}
2093
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002094SDValue DAGCombiner::visitSREM(SDNode *N) {
2095 SDValue N0 = N->getOperand(0);
2096 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2098 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002099 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002100
Nate Begeman21158fc2005-09-01 00:19:25 +00002101 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002102 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002103 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002104 // If we know the sign bits of both operands are zero, strength reduce to a
2105 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002106 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002107 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002108 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002109 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002110
Dan Gohman9a693412007-11-26 23:46:11 +00002111 // If X/C can be simplified by the division-by-constant logic, lower
2112 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002113 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002114 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002115 AddToWorkList(Div.getNode());
2116 SDValue OptimizedDiv = combine(Div.getNode());
2117 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002118 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002119 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002120 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002121 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002122 return Sub;
2123 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002124 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002125
Dan Gohman06563a82007-07-03 14:03:57 +00002126 // undef % X -> 0
2127 if (N0.getOpcode() == ISD::UNDEF)
2128 return DAG.getConstant(0, VT);
2129 // X % undef -> undef
2130 if (N1.getOpcode() == ISD::UNDEF)
2131 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002132
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002133 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002134}
2135
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002136SDValue DAGCombiner::visitUREM(SDNode *N) {
2137 SDValue N0 = N->getOperand(0);
2138 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002139 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002141 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002142
Nate Begeman21158fc2005-09-01 00:19:25 +00002143 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002144 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002145 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002146 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002147 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002148 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002149 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002150 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2151 if (N1.getOpcode() == ISD::SHL) {
2152 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002153 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002154 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002155 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002156 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002157 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002158 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002159 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002160 }
2161 }
2162 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002163
Dan Gohman9a693412007-11-26 23:46:11 +00002164 // If X/C can be simplified by the division-by-constant logic, lower
2165 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002166 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002167 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002168 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002169 SDValue OptimizedDiv = combine(Div.getNode());
2170 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002171 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002172 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002173 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002174 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002175 return Sub;
2176 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002177 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002178
Dan Gohman06563a82007-07-03 14:03:57 +00002179 // undef % X -> 0
2180 if (N0.getOpcode() == ISD::UNDEF)
2181 return DAG.getConstant(0, VT);
2182 // X % undef -> undef
2183 if (N1.getOpcode() == ISD::UNDEF)
2184 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002185
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002186 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002187}
2188
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002189SDValue DAGCombiner::visitMULHS(SDNode *N) {
2190 SDValue N0 = N->getOperand(0);
2191 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002193 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002194 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002195
Nate Begeman21158fc2005-09-01 00:19:25 +00002196 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002197 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002198 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002199 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002200 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002201 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002202 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002203 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002204 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002205 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002206 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002207
Chris Lattner10bd29f2010-12-13 08:39:01 +00002208 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2209 // plus a shift.
2210 if (VT.isSimple() && !VT.isVector()) {
2211 MVT Simple = VT.getSimpleVT();
2212 unsigned SimpleSize = Simple.getSizeInBits();
2213 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2214 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2215 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2216 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2217 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002218 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002219 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002220 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2221 }
2222 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002223
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002224 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002225}
2226
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002227SDValue DAGCombiner::visitMULHU(SDNode *N) {
2228 SDValue N0 = N->getOperand(0);
2229 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002231 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002232 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002233
Nate Begeman21158fc2005-09-01 00:19:25 +00002234 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002235 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002236 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002237 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002238 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002239 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002240 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002241 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002242 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002243
Chris Lattner10bd29f2010-12-13 08:39:01 +00002244 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2245 // plus a shift.
2246 if (VT.isSimple() && !VT.isVector()) {
2247 MVT Simple = VT.getSimpleVT();
2248 unsigned SimpleSize = Simple.getSizeInBits();
2249 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2250 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2251 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2252 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2253 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2254 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002255 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002256 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2257 }
2258 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002259
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002260 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002261}
2262
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002263/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2264/// compute two values. LoOp and HiOp give the opcodes for the two computations
2265/// that are being performed. Return true if a simplification was made.
2266///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002267SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002268 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002269 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002270 bool HiExists = N->hasAnyUseOfValue(1);
2271 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002272 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002273 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002274 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002275 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002276 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002277 }
2278
2279 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002280 bool LoExists = N->hasAnyUseOfValue(0);
2281 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002282 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002283 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002284 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002285 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002286 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002287 }
2288
Evan Chengece4c682007-11-08 09:25:29 +00002289 // If both halves are used, return as it is.
2290 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002291 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002292
2293 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002294 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002295 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002296 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002297 AddToWorkList(Lo.getNode());
2298 SDValue LoOpt = combine(Lo.getNode());
2299 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002300 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002301 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002302 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002303 }
2304
Evan Chengece4c682007-11-08 09:25:29 +00002305 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002306 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002307 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002308 AddToWorkList(Hi.getNode());
2309 SDValue HiOpt = combine(Hi.getNode());
2310 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002311 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002312 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002313 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002314 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002315
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002316 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002317}
2318
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002319SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2320 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002321 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002322
Chris Lattner15090e12010-12-15 06:04:19 +00002323 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002324 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002325
2326 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2327 // plus a shift.
2328 if (VT.isSimple() && !VT.isVector()) {
2329 MVT Simple = VT.getSimpleVT();
2330 unsigned SimpleSize = Simple.getSizeInBits();
2331 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2332 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2333 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2334 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2335 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2336 // Compute the high part as N1.
2337 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002338 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002339 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2340 // Compute the low part as N0.
2341 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2342 return CombineTo(N, Lo, Hi);
2343 }
2344 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002345
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002346 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002347}
2348
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002349SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2350 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002351 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002352
Chris Lattner15090e12010-12-15 06:04:19 +00002353 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002354 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002355
Chris Lattner15090e12010-12-15 06:04:19 +00002356 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2357 // plus a shift.
2358 if (VT.isSimple() && !VT.isVector()) {
2359 MVT Simple = VT.getSimpleVT();
2360 unsigned SimpleSize = Simple.getSizeInBits();
2361 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2362 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2363 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2364 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2365 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2366 // Compute the high part as N1.
2367 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002368 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002369 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2370 // Compute the low part as N0.
2371 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2372 return CombineTo(N, Lo, Hi);
2373 }
2374 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002375
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002376 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002377}
2378
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002379SDValue DAGCombiner::visitSMULO(SDNode *N) {
2380 // (smulo x, 2) -> (saddo x, x)
2381 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2382 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002383 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002384 N->getOperand(0), N->getOperand(0));
2385
2386 return SDValue();
2387}
2388
2389SDValue DAGCombiner::visitUMULO(SDNode *N) {
2390 // (umulo x, 2) -> (uaddo x, x)
2391 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002393 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002394 N->getOperand(0), N->getOperand(0));
2395
2396 return SDValue();
2397}
2398
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002399SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2400 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002401 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002402
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002403 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002404}
2405
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002406SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2407 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002408 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002409
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002410 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002411}
2412
Chris Lattner8d6fc202006-05-05 05:51:50 +00002413/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2414/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002415SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2416 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002417 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002418 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002419
Dan Gohmandd5286d2010-01-14 03:08:49 +00002420 // Bail early if none of these transforms apply.
2421 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2422
Chris Lattner002ee912006-05-05 06:31:05 +00002423 // For each of OP in AND/OR/XOR:
2424 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2425 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2426 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002427 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002428 //
2429 // do not sink logical op inside of a vector extend, since it may combine
2430 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002431 EVT Op0VT = N0.getOperand(0).getValueType();
2432 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002433 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002434 // Avoid infinite looping with PromoteIntBinOp.
2435 (N0.getOpcode() == ISD::ANY_EXTEND &&
2436 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002437 (N0.getOpcode() == ISD::TRUNCATE &&
2438 (!TLI.isZExtFree(VT, Op0VT) ||
2439 !TLI.isTruncateFree(Op0VT, VT)) &&
2440 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002441 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002442 Op0VT == N1.getOperand(0).getValueType() &&
2443 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002444 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002445 N0.getOperand(0).getValueType(),
2446 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002447 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002448 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002450
Chris Lattner5ac42932006-05-05 06:10:43 +00002451 // For each of OP in SHL/SRL/SRA/AND...
2452 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2453 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2454 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002455 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002456 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002457 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002458 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002459 N0.getOperand(0).getValueType(),
2460 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002461 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002462 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002463 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002464 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002465
Nadav Rotemb0783502012-04-01 19:31:22 +00002466 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2467 // Only perform this optimization after type legalization and before
2468 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2469 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2470 // we don't want to undo this promotion.
2471 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2472 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002473 if ((N0.getOpcode() == ISD::BITCAST ||
2474 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2475 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002476 SDValue In0 = N0.getOperand(0);
2477 SDValue In1 = N1.getOperand(0);
2478 EVT In0Ty = In0.getValueType();
2479 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002480 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002481 // If both incoming values are integers, and the original types are the
2482 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002483 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002484 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2485 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002486 AddToWorkList(Op.getNode());
2487 return BC;
2488 }
2489 }
2490
2491 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2492 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2493 // If both shuffles use the same mask, and both shuffle within a single
2494 // vector, then it is worthwhile to move the swizzle after the operation.
2495 // The type-legalizer generates this pattern when loading illegal
2496 // vector types from memory. In many cases this allows additional shuffle
2497 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002498 // There are other cases where moving the shuffle after the xor/and/or
2499 // is profitable even if shuffles don't perform a swizzle.
2500 // If both shuffles use the same mask, and both shuffles have the same first
2501 // or second operand, then it might still be profitable to move the shuffle
2502 // after the xor/and/or operation.
2503 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002504 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2505 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002506
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002507 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002508 "Inputs to shuffles are not the same type");
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002509
Nadav Rotemb0783502012-04-01 19:31:22 +00002510 // Check that both shuffles use the same mask. The masks are known to be of
2511 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002512 // Check also that shuffles have only one use to avoid introducing extra
2513 // instructions.
2514 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2515 SVN0->getMask().equals(SVN1->getMask())) {
2516 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002517
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002518 // Don't try to fold this node if it requires introducing a
2519 // build vector of all zeros that might be illegal at this stage.
2520 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2521 if (!LegalTypes)
2522 ShOp = DAG.getConstant(0, VT);
2523 else
2524 ShOp = SDValue();
2525 }
2526
2527 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2528 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2529 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2530 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2531 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2532 N0->getOperand(0), N1->getOperand(0));
2533 AddToWorkList(NewNode.getNode());
2534 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2535 &SVN0->getMask()[0]);
2536 }
2537
2538 // Don't try to fold this node if it requires introducing a
2539 // build vector of all zeros that might be illegal at this stage.
2540 ShOp = N0->getOperand(0);
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 (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2549 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2550 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2551 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2552 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2553 N0->getOperand(1), N1->getOperand(1));
2554 AddToWorkList(NewNode.getNode());
2555 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2556 &SVN0->getMask()[0]);
2557 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002558 }
2559 }
Craig Topper9c3da312012-04-09 07:19:09 +00002560
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002561 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002562}
2563
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002564SDValue DAGCombiner::visitAND(SDNode *N) {
2565 SDValue N0 = N->getOperand(0);
2566 SDValue N1 = N->getOperand(1);
2567 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002568 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2569 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002570 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002571 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002572
Dan Gohmana8665142007-06-25 16:23:39 +00002573 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002574 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002575 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002576 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002577
2578 // fold (and x, 0) -> 0, vector edition
2579 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2580 return N0;
2581 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2582 return N1;
2583
2584 // fold (and x, -1) -> x, vector edition
2585 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2586 return N1;
2587 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2588 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002589 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002590
Dan Gohman06563a82007-07-03 14:03:57 +00002591 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002592 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002593 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002594 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002595 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002596 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002597 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002598 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002599 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002600 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002601 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002602 return N0;
2603 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002604 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002605 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002606 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002607 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002608 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002609 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002610 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002611 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002612 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002613 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002614 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002615 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002616 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2617 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002618 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002619 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002620 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002621 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002622 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002623 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002624
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002625 // Replace uses of the AND with uses of the Zero extend node.
2626 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002627
Chris Lattner49beaf42006-02-02 07:17:31 +00002628 // We actually want to replace all uses of the any_extend with the
2629 // zero_extend, to avoid duplicating things. This will later cause this
2630 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002631 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002632 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002633 }
2634 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002635 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002636 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2637 // already be zero by virtue of the width of the base type of the load.
2638 //
2639 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2640 // more cases.
2641 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2642 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2643 N0.getOpcode() == ISD::LOAD) {
2644 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2645 N0 : N0.getOperand(0) );
2646
2647 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2648 // This can be a pure constant or a vector splat, in which case we treat the
2649 // vector as a scalar and use the splat value.
2650 APInt Constant = APInt::getNullValue(1);
2651 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2652 Constant = C->getAPIntValue();
2653 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2654 APInt SplatValue, SplatUndef;
2655 unsigned SplatBitSize;
2656 bool HasAnyUndefs;
2657 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2658 SplatBitSize, HasAnyUndefs);
2659 if (IsSplat) {
2660 // Undef bits can contribute to a possible optimisation if set, so
2661 // set them.
2662 SplatValue |= SplatUndef;
2663
2664 // The splat value may be something like "0x00FFFFFF", which means 0 for
2665 // the first vector value and FF for the rest, repeating. We need a mask
2666 // that will apply equally to all members of the vector, so AND all the
2667 // lanes of the constant together.
2668 EVT VT = Vector->getValueType(0);
2669 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002670
2671 // If the splat value has been compressed to a bitlength lower
2672 // than the size of the vector lane, we need to re-expand it to
2673 // the lane size.
2674 if (BitWidth > SplatBitSize)
2675 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2676 SplatBitSize < BitWidth;
2677 SplatBitSize = SplatBitSize * 2)
2678 SplatValue |= SplatValue.shl(SplatBitSize);
2679
James Molloy862fe492012-02-20 12:02:38 +00002680 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002681 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002682 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2683 }
2684 }
2685
2686 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2687 // actually legal and isn't going to get expanded, else this is a false
2688 // optimisation.
2689 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2690 Load->getMemoryVT());
2691
2692 // Resize the constant to the same size as the original memory access before
2693 // extension. If it is still the AllOnesValue then this AND is completely
2694 // unneeded.
2695 Constant =
2696 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2697
2698 bool B;
2699 switch (Load->getExtensionType()) {
2700 default: B = false; break;
2701 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2702 case ISD::ZEXTLOAD:
2703 case ISD::NON_EXTLOAD: B = true; break;
2704 }
2705
2706 if (B && Constant.isAllOnesValue()) {
2707 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2708 // preserve semantics once we get rid of the AND.
2709 SDValue NewLoad(Load, 0);
2710 if (Load->getExtensionType() == ISD::EXTLOAD) {
2711 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002712 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002713 Load->getChain(), Load->getBasePtr(),
2714 Load->getOffset(), Load->getMemoryVT(),
2715 Load->getMemOperand());
2716 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002717 if (Load->getNumValues() == 3) {
2718 // PRE/POST_INC loads have 3 values.
2719 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2720 NewLoad.getValue(2) };
2721 CombineTo(Load, To, 3, true);
2722 } else {
2723 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2724 }
James Molloy862fe492012-02-20 12:02:38 +00002725 }
2726
2727 // Fold the AND away, taking care not to fold to the old load node if we
2728 // replaced it.
2729 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2730
2731 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2732 }
2733 }
Nate Begeman049b7482005-09-09 19:49:52 +00002734 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2735 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2736 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2737 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002738
Nate Begeman049b7482005-09-09 19:49:52 +00002739 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002740 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002741 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002742 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002743 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002744 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002745 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002746 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002747 }
Bill Wendling86171912009-01-30 20:43:18 +00002748 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002749 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002750 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002751 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002752 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002753 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002754 }
Bill Wendling86171912009-01-30 20:43:18 +00002755 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002756 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002757 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002758 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002759 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002760 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002761 }
2762 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002763 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2764 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2765 Op0 == Op1 && LL.getValueType().isInteger() &&
2766 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2767 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2768 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2769 cast<ConstantSDNode>(RR)->isNullValue()))) {
2770 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2771 LL, DAG.getConstant(1, LL.getValueType()));
2772 AddToWorkList(ADDNode.getNode());
2773 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2774 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2775 }
Nate Begeman049b7482005-09-09 19:49:52 +00002776 // canonicalize equivalent to ll == rl
2777 if (LL == RR && LR == RL) {
2778 Op1 = ISD::getSetCCSwappedOperands(Op1);
2779 std::swap(RL, RR);
2780 }
2781 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002782 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002783 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002784 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002785 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002786 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2787 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002788 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002789 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002790 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002791 }
2792 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002793
Bill Wendling86171912009-01-30 20:43:18 +00002794 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002795 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002796 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002797 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002798 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002799
Nate Begemandc7bba92006-02-03 22:24:05 +00002800 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2801 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002802 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002803 SimplifyDemandedBits(SDValue(N, 0)))
2804 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002805
Nate Begeman02b23c62005-10-13 03:11:28 +00002806 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002807 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002808 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002809 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002810 // If we zero all the possible extended bits, then we can turn this into
2811 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002812 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002813 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002814 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002815 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002816 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002817 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002818 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002819 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002820 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002821 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002822 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002823 }
2824 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002825 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002826 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002827 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002828 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002829 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002830 // If we zero all the possible extended bits, then we can turn this into
2831 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002832 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002833 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002834 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002835 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002836 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002837 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002838 LN0->getChain(), LN0->getBasePtr(),
2839 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002840 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002841 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002842 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002843 }
2844 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002845
Chris Lattnerf0032b32006-02-28 06:49:37 +00002846 // fold (and (load x), 255) -> (zextload x, i8)
2847 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002848 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2849 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2850 (N0.getOpcode() == ISD::ANY_EXTEND &&
2851 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2852 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2853 LoadSDNode *LN0 = HasAnyExt
2854 ? cast<LoadSDNode>(N0.getOperand(0))
2855 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002856 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002857 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002858 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002859 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2860 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2861 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002862
Evan Cheng166a4e62010-01-06 19:38:29 +00002863 if (ExtVT == LoadedVT &&
2864 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002865 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002866
2867 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002868 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002869 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2870 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002871 AddToWorkList(N);
2872 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2873 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2874 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002875
Chris Lattner88de3842010-01-07 21:53:27 +00002876 // Do not change the width of a volatile load.
2877 // Do not generate loads of non-round integer types since these can
2878 // be expensive (and would be wrong if the type is not byte sized).
2879 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2880 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2881 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002882
Chris Lattner88de3842010-01-07 21:53:27 +00002883 unsigned Alignment = LN0->getAlignment();
2884 SDValue NewPtr = LN0->getBasePtr();
2885
2886 // For big endian targets, we need to add an offset to the pointer
2887 // to load the correct bytes. For little endian systems, we merely
2888 // need to read fewer bytes from the same pointer.
2889 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002890 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2891 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2892 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002893 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002894 NewPtr, DAG.getConstant(PtrOff, PtrType));
2895 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002896 }
Chris Lattner88de3842010-01-07 21:53:27 +00002897
2898 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002899
Chris Lattner88de3842010-01-07 21:53:27 +00002900 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2901 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002902 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002903 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002904 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002905 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002906 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002907 AddToWorkList(N);
2908 CombineTo(LN0, Load, Load.getValue(1));
2909 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002910 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002911 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002912 }
2913 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002914
Evan Chenge6a3b032012-07-17 18:54:11 +00002915 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2916 VT.getSizeInBits() <= 64) {
2917 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2918 APInt ADDC = ADDI->getAPIntValue();
2919 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2920 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2921 // immediate for an add, but it is legal if its top c2 bits are set,
2922 // transform the ADD so the immediate doesn't need to be materialized
2923 // in a register.
2924 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2925 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2926 SRLI->getZExtValue());
2927 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2928 ADDC |= Mask;
2929 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2930 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002931 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002932 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2933 CombineTo(N0.getNode(), NewAdd);
2934 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2935 }
2936 }
2937 }
2938 }
2939 }
2940 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002941
Tim Northover819bfb52013-08-27 13:46:45 +00002942 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2943 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2944 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2945 N0.getOperand(1), false);
2946 if (BSwap.getNode())
2947 return BSwap;
2948 }
2949
Evan Chengf1005572010-04-28 07:10:39 +00002950 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002951}
2952
Evan Cheng4c0bd962011-06-21 06:01:08 +00002953/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2954///
2955SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2956 bool DemandHighBits) {
2957 if (!LegalOperations)
2958 return SDValue();
2959
2960 EVT VT = N->getValueType(0);
2961 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2962 return SDValue();
2963 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2964 return SDValue();
2965
2966 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2967 bool LookPassAnd0 = false;
2968 bool LookPassAnd1 = false;
2969 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2970 std::swap(N0, N1);
2971 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2972 std::swap(N0, N1);
2973 if (N0.getOpcode() == ISD::AND) {
2974 if (!N0.getNode()->hasOneUse())
2975 return SDValue();
2976 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2977 if (!N01C || N01C->getZExtValue() != 0xFF00)
2978 return SDValue();
2979 N0 = N0.getOperand(0);
2980 LookPassAnd0 = true;
2981 }
2982
2983 if (N1.getOpcode() == ISD::AND) {
2984 if (!N1.getNode()->hasOneUse())
2985 return SDValue();
2986 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2987 if (!N11C || N11C->getZExtValue() != 0xFF)
2988 return SDValue();
2989 N1 = N1.getOperand(0);
2990 LookPassAnd1 = true;
2991 }
2992
2993 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2994 std::swap(N0, N1);
2995 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2996 return SDValue();
2997 if (!N0.getNode()->hasOneUse() ||
2998 !N1.getNode()->hasOneUse())
2999 return SDValue();
3000
3001 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3002 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3003 if (!N01C || !N11C)
3004 return SDValue();
3005 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3006 return SDValue();
3007
3008 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3009 SDValue N00 = N0->getOperand(0);
3010 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3011 if (!N00.getNode()->hasOneUse())
3012 return SDValue();
3013 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3014 if (!N001C || N001C->getZExtValue() != 0xFF)
3015 return SDValue();
3016 N00 = N00.getOperand(0);
3017 LookPassAnd0 = true;
3018 }
3019
3020 SDValue N10 = N1->getOperand(0);
3021 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3022 if (!N10.getNode()->hasOneUse())
3023 return SDValue();
3024 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3025 if (!N101C || N101C->getZExtValue() != 0xFF00)
3026 return SDValue();
3027 N10 = N10.getOperand(0);
3028 LookPassAnd1 = true;
3029 }
3030
3031 if (N00 != N10)
3032 return SDValue();
3033
Tim Northover819bfb52013-08-27 13:46:45 +00003034 // Make sure everything beyond the low halfword gets set to zero since the SRL
3035 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003036 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003037 if (DemandHighBits && OpSizeInBits > 16) {
3038 // If the left-shift isn't masked out then the only way this is a bswap is
3039 // if all bits beyond the low 8 are 0. In that case the entire pattern
3040 // reduces to a left shift anyway: leave it for other parts of the combiner.
3041 if (!LookPassAnd0)
3042 return SDValue();
3043
3044 // However, if the right shift isn't masked out then it might be because
3045 // it's not needed. See if we can spot that too.
3046 if (!LookPassAnd1 &&
3047 !DAG.MaskedValueIsZero(
3048 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3049 return SDValue();
3050 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003051
Andrew Trickef9de2a2013-05-25 02:42:55 +00003052 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003053 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003054 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003055 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3056 return Res;
3057}
3058
3059/// isBSwapHWordElement - Return true if the specified node is an element
3060/// that makes up a 32-bit packed halfword byteswap. i.e.
3061/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003062static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003063 if (!N.getNode()->hasOneUse())
3064 return false;
3065
3066 unsigned Opc = N.getOpcode();
3067 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3068 return false;
3069
3070 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3071 if (!N1C)
3072 return false;
3073
3074 unsigned Num;
3075 switch (N1C->getZExtValue()) {
3076 default:
3077 return false;
3078 case 0xFF: Num = 0; break;
3079 case 0xFF00: Num = 1; break;
3080 case 0xFF0000: Num = 2; break;
3081 case 0xFF000000: Num = 3; break;
3082 }
3083
3084 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3085 SDValue N0 = N.getOperand(0);
3086 if (Opc == ISD::AND) {
3087 if (Num == 0 || Num == 2) {
3088 // (x >> 8) & 0xff
3089 // (x >> 8) & 0xff0000
3090 if (N0.getOpcode() != ISD::SRL)
3091 return false;
3092 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3093 if (!C || C->getZExtValue() != 8)
3094 return false;
3095 } else {
3096 // (x << 8) & 0xff00
3097 // (x << 8) & 0xff000000
3098 if (N0.getOpcode() != ISD::SHL)
3099 return false;
3100 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3101 if (!C || C->getZExtValue() != 8)
3102 return false;
3103 }
3104 } else if (Opc == ISD::SHL) {
3105 // (x & 0xff) << 8
3106 // (x & 0xff0000) << 8
3107 if (Num != 0 && Num != 2)
3108 return false;
3109 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3110 if (!C || C->getZExtValue() != 8)
3111 return false;
3112 } else { // Opc == ISD::SRL
3113 // (x & 0xff00) >> 8
3114 // (x & 0xff000000) >> 8
3115 if (Num != 1 && Num != 3)
3116 return false;
3117 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3118 if (!C || C->getZExtValue() != 8)
3119 return false;
3120 }
3121
3122 if (Parts[Num])
3123 return false;
3124
3125 Parts[Num] = N0.getOperand(0).getNode();
3126 return true;
3127}
3128
3129/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3130/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3131/// => (rotl (bswap x), 16)
3132SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3133 if (!LegalOperations)
3134 return SDValue();
3135
3136 EVT VT = N->getValueType(0);
3137 if (VT != MVT::i32)
3138 return SDValue();
3139 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3140 return SDValue();
3141
Craig Topperc0196b12014-04-14 00:51:57 +00003142 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003143 // Look for either
3144 // (or (or (and), (and)), (or (and), (and)))
3145 // (or (or (or (and), (and)), (and)), (and))
3146 if (N0.getOpcode() != ISD::OR)
3147 return SDValue();
3148 SDValue N00 = N0.getOperand(0);
3149 SDValue N01 = N0.getOperand(1);
3150
Evan Chengbf0baa92012-12-13 01:34:32 +00003151 if (N1.getOpcode() == ISD::OR &&
3152 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003153 // (or (or (and), (and)), (or (and), (and)))
3154 SDValue N000 = N00.getOperand(0);
3155 if (!isBSwapHWordElement(N000, Parts))
3156 return SDValue();
3157
3158 SDValue N001 = N00.getOperand(1);
3159 if (!isBSwapHWordElement(N001, Parts))
3160 return SDValue();
3161 SDValue N010 = N01.getOperand(0);
3162 if (!isBSwapHWordElement(N010, Parts))
3163 return SDValue();
3164 SDValue N011 = N01.getOperand(1);
3165 if (!isBSwapHWordElement(N011, Parts))
3166 return SDValue();
3167 } else {
3168 // (or (or (or (and), (and)), (and)), (and))
3169 if (!isBSwapHWordElement(N1, Parts))
3170 return SDValue();
3171 if (!isBSwapHWordElement(N01, Parts))
3172 return SDValue();
3173 if (N00.getOpcode() != ISD::OR)
3174 return SDValue();
3175 SDValue N000 = N00.getOperand(0);
3176 if (!isBSwapHWordElement(N000, Parts))
3177 return SDValue();
3178 SDValue N001 = N00.getOperand(1);
3179 if (!isBSwapHWordElement(N001, Parts))
3180 return SDValue();
3181 }
3182
3183 // Make sure the parts are all coming from the same node.
3184 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3185 return SDValue();
3186
Andrew Trickef9de2a2013-05-25 02:42:55 +00003187 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003188 SDValue(Parts[0],0));
3189
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003190 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003191 // do (x << 16) | (x >> 16).
3192 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3193 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003194 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003195 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003196 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3197 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3198 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3199 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003200}
3201
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003202SDValue DAGCombiner::visitOR(SDNode *N) {
3203 SDValue N0 = N->getOperand(0);
3204 SDValue N1 = N->getOperand(1);
3205 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003206 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3207 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003208 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003209
Dan Gohmana8665142007-06-25 16:23:39 +00003210 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003211 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003212 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003213 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003214
3215 // fold (or x, 0) -> x, vector edition
3216 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3217 return N1;
3218 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3219 return N0;
3220
3221 // fold (or x, -1) -> -1, vector edition
3222 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3223 return N0;
3224 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3225 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003226
3227 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3228 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3229 // Do this only if the resulting shuffle is legal.
3230 if (isa<ShuffleVectorSDNode>(N0) &&
3231 isa<ShuffleVectorSDNode>(N1) &&
3232 N0->getOperand(1) == N1->getOperand(1) &&
3233 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3234 bool CanFold = true;
3235 unsigned NumElts = VT.getVectorNumElements();
3236 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3237 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3238 // We construct two shuffle masks:
3239 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3240 // and N1 as the second operand.
3241 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3242 // and N0 as the second operand.
3243 // We do this because OR is commutable and therefore there might be
3244 // two ways to fold this node into a shuffle.
3245 SmallVector<int,4> Mask1;
3246 SmallVector<int,4> Mask2;
3247
3248 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3249 int M0 = SV0->getMaskElt(i);
3250 int M1 = SV1->getMaskElt(i);
3251
3252 // Both shuffle indexes are undef. Propagate Undef.
3253 if (M0 < 0 && M1 < 0) {
3254 Mask1.push_back(M0);
3255 Mask2.push_back(M0);
3256 continue;
3257 }
3258
3259 if (M0 < 0 || M1 < 0 ||
3260 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3261 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3262 CanFold = false;
3263 break;
3264 }
3265
3266 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3267 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3268 }
3269
3270 if (CanFold) {
3271 // Fold this sequence only if the resulting shuffle is 'legal'.
3272 if (TLI.isShuffleMaskLegal(Mask1, VT))
3273 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3274 N1->getOperand(0), &Mask1[0]);
3275 if (TLI.isShuffleMaskLegal(Mask2, VT))
3276 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3277 N0->getOperand(0), &Mask2[0]);
3278 }
3279 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003280 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003281
Dan Gohman06563a82007-07-03 14:03:57 +00003282 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003283 if (!LegalOperations &&
3284 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003285 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3286 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3287 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003288 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003289 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003290 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003291 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003292 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003293 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003294 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003295 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003296 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003297 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003298 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003299 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003300 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003301 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003302 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003303
3304 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3305 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003306 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003307 return BSwap;
3308 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003309 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003310 return BSwap;
3311
Nate Begeman22e251a2006-02-03 06:46:56 +00003312 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003313 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003314 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003315 return ROR;
3316 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003317 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003318 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003319 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003320 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003321 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3322 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3323 if (!COR.getNode())
3324 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003325 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3326 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003327 N0.getOperand(0), N1), COR);
3328 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003329 }
Nate Begeman049b7482005-09-09 19:49:52 +00003330 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3331 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3332 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3333 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003334
Nate Begeman049b7482005-09-09 19:49:52 +00003335 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003336 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003337 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3338 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003339 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003340 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003341 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003342 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003343 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003344 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003345 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003346 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3347 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003348 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003349 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003350 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003351 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003352 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003353 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003354 }
3355 }
3356 // canonicalize equivalent to ll == rl
3357 if (LL == RR && LR == RL) {
3358 Op1 = ISD::getSetCCSwappedOperands(Op1);
3359 std::swap(RL, RR);
3360 }
3361 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003362 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003363 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003364 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003365 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003366 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3367 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003368 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003369 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003370 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003371 }
3372 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003373
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003374 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003375 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003376 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003377 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003378 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003379
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003380 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003381 if (N0.getOpcode() == ISD::AND &&
3382 N1.getOpcode() == ISD::AND &&
3383 N0.getOperand(1).getOpcode() == ISD::Constant &&
3384 N1.getOperand(1).getOpcode() == ISD::Constant &&
3385 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003386 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003387 // We can only do this xform if we know that bits from X that are set in C2
3388 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003389 const APInt &LHSMask =
3390 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3391 const APInt &RHSMask =
3392 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003393
Dan Gohman309d3d52007-06-22 14:59:07 +00003394 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3395 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003396 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003397 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003398 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003399 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003400 }
3401 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003402
Chris Lattner97614c82006-09-14 20:50:57 +00003403 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003404 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003405 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003406
Dan Gohman600f62b2010-06-24 14:30:44 +00003407 // Simplify the operands using demanded-bits information.
3408 if (!VT.isVector() &&
3409 SimplifyDemandedBits(SDValue(N, 0)))
3410 return SDValue(N, 0);
3411
Evan Chengf1005572010-04-28 07:10:39 +00003412 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003413}
3414
Chris Lattner97614c82006-09-14 20:50:57 +00003415/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003416static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003417 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003418 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003419 Mask = Op.getOperand(1);
3420 Op = Op.getOperand(0);
3421 } else {
3422 return false;
3423 }
3424 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003425
Chris Lattner97614c82006-09-14 20:50:57 +00003426 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3427 Shift = Op;
3428 return true;
3429 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003430
Scott Michelcf0da6c2009-02-17 22:15:04 +00003431 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003432}
3433
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003434// Return true if we can prove that, whenever Neg and Pos are both in the
3435// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003436// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3437//
3438// (or (shift1 X, Neg), (shift2 X, Pos))
3439//
Adam Nemetc6553a82014-03-07 23:56:24 +00003440// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3441// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3442// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003443static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003444 // If OpSize is a power of 2 then:
3445 //
3446 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3447 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3448 //
3449 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3450 // for the stronger condition:
3451 //
3452 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3453 //
3454 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3455 // we can just replace Neg with Neg' for the rest of the function.
3456 //
3457 // In other cases we check for the even stronger condition:
3458 //
3459 // Neg == OpSize - Pos [B]
3460 //
3461 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3462 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003463 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003464 // We could actually use [A] whenever OpSize is a power of 2, but the
3465 // only extra cases that it would match are those uninteresting ones
3466 // where Neg and Pos are never in range at the same time. E.g. for
3467 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3468 // as well as (sub 32, Pos), but:
3469 //
3470 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3471 //
3472 // always invokes undefined behavior for 32-bit X.
3473 //
3474 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003475 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003476 if (Neg.getOpcode() == ISD::AND &&
3477 isPowerOf2_64(OpSize) &&
3478 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3479 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3480 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003481 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003482 }
3483
Richard Sandiford0f264db2014-01-09 10:49:40 +00003484 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3485 if (Neg.getOpcode() != ISD::SUB)
3486 return 0;
3487 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3488 if (!NegC)
3489 return 0;
3490 SDValue NegOp1 = Neg.getOperand(1);
3491
Adam Nemet5117f5d2014-03-07 23:56:28 +00003492 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3493 // Pos'. The truncation is redundant for the purpose of the equality.
3494 if (MaskLoBits &&
3495 Pos.getOpcode() == ISD::AND &&
3496 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3497 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3498 Pos = Pos.getOperand(0);
3499
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003500 // The condition we need is now:
3501 //
3502 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3503 //
3504 // If NegOp1 == Pos then we need:
3505 //
3506 // OpSize & Mask == NegC & Mask
3507 //
3508 // (because "x & Mask" is a truncation and distributes through subtraction).
3509 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003510 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003511 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003512 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3513 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003514 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003515 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3516 //
3517 // which, again because "x & Mask" is a truncation, becomes:
3518 //
3519 // NegC & Mask == (OpSize - PosC) & Mask
3520 // OpSize & Mask == (NegC + PosC) & Mask
3521 else if (Pos.getOpcode() == ISD::ADD &&
3522 Pos.getOperand(0) == NegOp1 &&
3523 Pos.getOperand(1).getOpcode() == ISD::Constant)
3524 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3525 NegC->getAPIntValue());
3526 else
3527 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003528
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003529 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003530 if (MaskLoBits)
3531 // Opsize & Mask is 0 since Mask is Opsize - 1.
3532 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003533 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003534}
3535
Richard Sandiford95c864d2014-01-08 15:40:47 +00003536// A subroutine of MatchRotate used once we have found an OR of two opposite
3537// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3538// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3539// former being preferred if supported. InnerPos and InnerNeg are Pos and
3540// Neg with outer conversions stripped away.
3541SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3542 SDValue Neg, SDValue InnerPos,
3543 SDValue InnerNeg, unsigned PosOpcode,
3544 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003545 // fold (or (shl x, (*ext y)),
3546 // (srl x, (*ext (sub 32, y)))) ->
3547 // (rotl x, y) or (rotr x, (sub 32, y))
3548 //
3549 // fold (or (shl x, (*ext (sub 32, y))),
3550 // (srl x, (*ext y))) ->
3551 // (rotr x, y) or (rotl x, (sub 32, y))
3552 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003553 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003554 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3555 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3556 HasPos ? Pos : Neg).getNode();
3557 }
3558
Craig Topperc0196b12014-04-14 00:51:57 +00003559 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003560}
3561
Chris Lattner97614c82006-09-14 20:50:57 +00003562// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3563// idioms for rotate, and if the target supports rotation instructions, generate
3564// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003565SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003566 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003567 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003568 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003569
3570 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003571 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3572 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003573 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003574
Chris Lattner97614c82006-09-14 20:50:57 +00003575 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003576 SDValue LHSShift; // The shift.
3577 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003578 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003579 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003580
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003581 SDValue RHSShift; // The shift.
3582 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003583 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003584 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003585
Chris Lattner97614c82006-09-14 20:50:57 +00003586 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003587 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003588
3589 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003590 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003591
Chris Lattner97614c82006-09-14 20:50:57 +00003592 // Canonicalize shl to left side in a shl/srl pair.
3593 if (RHSShift.getOpcode() == ISD::SHL) {
3594 std::swap(LHS, RHS);
3595 std::swap(LHSShift, RHSShift);
3596 std::swap(LHSMask , RHSMask );
3597 }
3598
Duncan Sands13237ac2008-06-06 12:08:01 +00003599 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003600 SDValue LHSShiftArg = LHSShift.getOperand(0);
3601 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003602 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003603 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003604
3605 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3606 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003607 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3608 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003609 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3610 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003611 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003612 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003613
Craig Topper65161fa2012-09-29 06:54:22 +00003614 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3615 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003616
Chris Lattner97614c82006-09-14 20:50:57 +00003617 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003618 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003619 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003620
Gabor Greiff304a7a2008-08-28 21:40:38 +00003621 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003622 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3623 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003624 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003625 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003626 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3627 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003628 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003629
Bill Wendling35972a92009-01-30 21:14:50 +00003630 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003631 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003632
Gabor Greiff304a7a2008-08-28 21:40:38 +00003633 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003634 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003635
Chris Lattner97614c82006-09-14 20:50:57 +00003636 // If there is a mask here, and we have a variable shift, we can't be sure
3637 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003638 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003639 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003640
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003641 // If the shift amount is sign/zext/any-extended just peel it off.
3642 SDValue LExtOp0 = LHSShiftAmt;
3643 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003644 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3645 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3646 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3647 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3648 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3649 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3650 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3651 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003652 LExtOp0 = LHSShiftAmt.getOperand(0);
3653 RExtOp0 = RHSShiftAmt.getOperand(0);
3654 }
3655
Richard Sandiford95c864d2014-01-08 15:40:47 +00003656 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3657 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3658 if (TryL)
3659 return TryL;
3660
3661 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3662 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3663 if (TryR)
3664 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003665
Craig Topperc0196b12014-04-14 00:51:57 +00003666 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003667}
3668
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003669SDValue DAGCombiner::visitXOR(SDNode *N) {
3670 SDValue N0 = N->getOperand(0);
3671 SDValue N1 = N->getOperand(1);
3672 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003673 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3674 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003675 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003676
Dan Gohmana8665142007-06-25 16:23:39 +00003677 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003678 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003679 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003680 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003681
3682 // fold (xor x, 0) -> x, vector edition
3683 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3684 return N1;
3685 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3686 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003687 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003688
Evan Chengdf1690d2008-03-25 20:08:07 +00003689 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3690 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3691 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003692 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003693 if (N0.getOpcode() == ISD::UNDEF)
3694 return N0;
3695 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003696 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003697 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003698 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003699 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003700 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003701 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003702 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003703 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003704 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003705 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003706 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003707 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003708 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003709 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003710
Nate Begeman21158fc2005-09-01 00:19:25 +00003711 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003712 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003713 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003714 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3715 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003716
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003717 if (!LegalOperations ||
3718 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003719 switch (N0.getOpcode()) {
3720 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003721 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003722 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003723 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003724 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003725 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003726 N0.getOperand(3), NotCC);
3727 }
3728 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003729 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003730
Chris Lattner58c227b2007-09-10 21:39:07 +00003731 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003732 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003733 N0.getNode()->hasOneUse() &&
3734 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003735 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003736 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003737 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003738 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003739 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003740 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003741
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003742 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003743 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003744 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003745 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003746 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3747 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003748 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3749 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003750 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003751 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003752 }
3753 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003754 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003755 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003756 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003757 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003758 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3759 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003760 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3761 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003762 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003763 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003764 }
3765 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003766 // fold (xor (and x, y), y) -> (and (not x), y)
3767 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003768 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003769 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003770 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003771 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003772 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003773 }
Bill Wendling35972a92009-01-30 21:14:50 +00003774 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003775 if (N1C && N0.getOpcode() == ISD::XOR) {
3776 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3777 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3778 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003779 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003780 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003781 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003782 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003783 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003784 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003785 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003786 }
3787 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003788 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003789 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003790
Chris Lattner8d6fc202006-05-05 05:51:50 +00003791 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3792 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003793 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003794 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003795 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003796
Chris Lattner098c01e2006-04-08 04:15:24 +00003797 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003798 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003799 SimplifyDemandedBits(SDValue(N, 0)))
3800 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003801
Evan Chengf1005572010-04-28 07:10:39 +00003802 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003803}
3804
Chris Lattner7c709a52007-12-06 07:33:36 +00003805/// visitShiftByConstant - Handle transforms common to the three shifts, when
3806/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003807SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003808 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003809 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003810 return SDValue();
3811
Gabor Greiff304a7a2008-08-28 21:40:38 +00003812 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003813 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003814
Chris Lattner7c709a52007-12-06 07:33:36 +00003815 // We want to pull some binops through shifts, so that we have (and (shift))
3816 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3817 // thing happens with address calculations, so it's important to canonicalize
3818 // it.
3819 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003820
Chris Lattner7c709a52007-12-06 07:33:36 +00003821 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003822 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003823 case ISD::OR:
3824 case ISD::XOR:
3825 HighBitSet = false; // We can only transform sra if the high bit is clear.
3826 break;
3827 case ISD::AND:
3828 HighBitSet = true; // We can only transform sra if the high bit is set.
3829 break;
3830 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003831 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003832 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003833 HighBitSet = false; // We can only transform sra if the high bit is clear.
3834 break;
3835 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003836
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003837 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003838 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003839 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003840
3841 // FIXME: disable this unless the input to the binop is a shift by a constant.
3842 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003843 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003844 // void foo(int *X, int i) { X[i & 1235] = 1; }
3845 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003846 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003847 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003848 BinOpLHSVal->getOpcode() != ISD::SRA &&
3849 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3850 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003851 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003852
Owen Anderson53aa7a92009-08-10 22:56:29 +00003853 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003854
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003855 // If this is a signed shift right, and the high bit is modified by the
3856 // logical operation, do not perform the transformation. The highBitSet
3857 // boolean indicates the value of the high bit of the constant which would
3858 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003859 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003860 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3861 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003862 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003863 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003864
Chris Lattner7c709a52007-12-06 07:33:36 +00003865 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003866 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003867 N->getValueType(0),
3868 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003869 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003870
3871 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003872 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003873 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003874 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003875
3876 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003877 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003878}
3879
Adam Nemet67483892014-03-04 23:28:31 +00003880SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3881 assert(N->getOpcode() == ISD::TRUNCATE);
3882 assert(N->getOperand(0).getOpcode() == ISD::AND);
3883
3884 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3885 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3886 SDValue N01 = N->getOperand(0).getOperand(1);
3887
Matt Arsenault985b9de2014-03-17 18:58:01 +00003888 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003889 EVT TruncVT = N->getValueType(0);
3890 SDValue N00 = N->getOperand(0).getOperand(0);
3891 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003892 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003893
3894 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3895 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3896 DAG.getConstant(TruncC, TruncVT));
3897 }
3898 }
3899
3900 return SDValue();
3901}
Adam Nemet7f928f12014-03-07 23:56:30 +00003902
3903SDValue DAGCombiner::visitRotate(SDNode *N) {
3904 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3905 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3906 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3907 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3908 if (NewOp1.getNode())
3909 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3910 N->getOperand(0), NewOp1);
3911 }
3912 return SDValue();
3913}
3914
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003915SDValue DAGCombiner::visitSHL(SDNode *N) {
3916 SDValue N0 = N->getOperand(0);
3917 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003918 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3919 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003920 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003921 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003922
Daniel Sandersa1840d22013-11-11 17:23:41 +00003923 // fold vector ops
3924 if (VT.isVector()) {
3925 SDValue FoldedVOp = SimplifyVBinOp(N);
3926 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003927
3928 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3929 // If setcc produces all-one true value then:
3930 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003931 if (N1CV && N1CV->isConstant()) {
3932 if (N0.getOpcode() == ISD::AND &&
3933 TLI.getBooleanContents(true) ==
3934 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3935 SDValue N00 = N0->getOperand(0);
3936 SDValue N01 = N0->getOperand(1);
3937 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003938
Matt Arsenault985b9de2014-03-17 18:58:01 +00003939 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3940 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3941 if (C.getNode())
3942 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3943 }
3944 } else {
3945 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003946 }
3947 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003948 }
3949
Nate Begeman21158fc2005-09-01 00:19:25 +00003950 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003951 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003952 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003953 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003954 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003955 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003956 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003957 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003958 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003959 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003960 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003961 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003962 // fold (shl undef, x) -> 0
3963 if (N0.getOpcode() == ISD::UNDEF)
3964 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003965 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003966 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003967 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003968 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003969 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003970 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00003971 N1.getOperand(0).getOpcode() == ISD::AND) {
3972 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3973 if (NewOp1.getNode())
3974 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003975 }
3976
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003977 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3978 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003979
3980 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00003981 if (N1C && N0.getOpcode() == ISD::SHL) {
3982 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3983 uint64_t c1 = N0C1->getZExtValue();
3984 uint64_t c2 = N1C->getZExtValue();
3985 if (c1 + c2 >= OpSizeInBits)
3986 return DAG.getConstant(0, VT);
3987 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3988 DAG.getConstant(c1 + c2, N1.getValueType()));
3989 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003990 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00003991
3992 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3993 // For this to be valid, the second form must not preserve any of the bits
3994 // that are shifted out by the inner shift in the first form. This means
3995 // the outer shift size must be >= the number of bits added by the ext.
3996 // As a corollary, we don't care what kind of ext it is.
3997 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3998 N0.getOpcode() == ISD::ANY_EXTEND ||
3999 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004000 N0.getOperand(0).getOpcode() == ISD::SHL) {
4001 SDValue N0Op0 = N0.getOperand(0);
4002 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4003 uint64_t c1 = N0Op0C1->getZExtValue();
4004 uint64_t c2 = N1C->getZExtValue();
4005 EVT InnerShiftVT = N0Op0.getValueType();
4006 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4007 if (c2 >= OpSizeInBits - InnerShiftSize) {
4008 if (c1 + c2 >= OpSizeInBits)
4009 return DAG.getConstant(0, VT);
4010 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4011 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4012 N0Op0->getOperand(0)),
4013 DAG.getConstant(c1 + c2, N1.getValueType()));
4014 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004015 }
4016 }
4017
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004018 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4019 // Only fold this if the inner zext has no other uses to avoid increasing
4020 // the total number of instructions.
4021 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004022 N0.getOperand(0).getOpcode() == ISD::SRL) {
4023 SDValue N0Op0 = N0.getOperand(0);
4024 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4025 uint64_t c1 = N0Op0C1->getZExtValue();
4026 if (c1 < VT.getScalarSizeInBits()) {
4027 uint64_t c2 = N1C->getZExtValue();
4028 if (c1 == c2) {
4029 SDValue NewOp0 = N0.getOperand(0);
4030 EVT CountVT = NewOp0.getOperand(1).getValueType();
4031 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4032 NewOp0, DAG.getConstant(c2, CountVT));
4033 AddToWorkList(NewSHL.getNode());
4034 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4035 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004036 }
4037 }
4038 }
4039
Eli Friedman1877ac92011-06-09 22:14:44 +00004040 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4041 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004042 // Only fold this if the inner shift has no other uses -- if it does, folding
4043 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004044 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4045 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4046 uint64_t c1 = N0C1->getZExtValue();
4047 if (c1 < OpSizeInBits) {
4048 uint64_t c2 = N1C->getZExtValue();
4049 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4050 SDValue Shift;
4051 if (c2 > c1) {
4052 Mask = Mask.shl(c2 - c1);
4053 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4054 DAG.getConstant(c2 - c1, N1.getValueType()));
4055 } else {
4056 Mask = Mask.lshr(c1 - c2);
4057 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4058 DAG.getConstant(c1 - c2, N1.getValueType()));
4059 }
4060 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4061 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004062 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004063 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004064 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004065 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004066 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004067 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004068 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004069 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4070 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004071 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004072 HiBitsMask);
4073 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004074
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004075 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004076 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004077 if (NewSHL.getNode())
4078 return NewSHL;
4079 }
4080
Evan Chengf1005572010-04-28 07:10:39 +00004081 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004082}
4083
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004084SDValue DAGCombiner::visitSRA(SDNode *N) {
4085 SDValue N0 = N->getOperand(0);
4086 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004087 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4088 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004089 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004090 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004091
Daniel Sandersa1840d22013-11-11 17:23:41 +00004092 // fold vector ops
4093 if (VT.isVector()) {
4094 SDValue FoldedVOp = SimplifyVBinOp(N);
4095 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004096
4097 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004098 }
4099
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004100 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004101 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004102 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004103 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004104 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004105 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004106 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004107 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004108 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004109 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004110 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004111 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004112 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004113 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004114 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004115 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4116 // sext_inreg.
4117 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004118 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004119 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4120 if (VT.isVector())
4121 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4122 ExtVT, VT.getVectorNumElements());
4123 if ((!LegalOperations ||
4124 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004125 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004126 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004127 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004128
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004129 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004130 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004131 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004132 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004133 if (Sum >= OpSizeInBits)
4134 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004135 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004136 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004137 }
4138 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004139
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004140 // fold (sra (shl X, m), (sub result_size, n))
4141 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004142 // result_size - n != m.
4143 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004144 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004145 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004146 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004147 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4148 if (N01C) {
4149 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004150 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004151 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4152
4153 if (VT.isVector())
4154 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4155
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004156 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004157 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004158
Scott Michelcf0da6c2009-02-17 22:15:04 +00004159 // If the shift is not a no-op (in which case this should be just a sign
4160 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004161 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004162 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004163 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004164 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4165 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004166 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004167
Owen Andersonb2c80da2011-02-25 21:41:48 +00004168 SDValue Amt = DAG.getConstant(ShiftAmt,
4169 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004170 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004171 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004172 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004173 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004174 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004175 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004176 }
4177 }
4178 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004179
Duncan Sands3ed76882009-02-01 18:06:53 +00004180 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004181 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004182 N1.getOperand(0).getOpcode() == ISD::AND) {
4183 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4184 if (NewOp1.getNode())
4185 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004186 }
4187
Matt Arsenault985b9de2014-03-17 18:58:01 +00004188 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004189 // if c1 is equal to the number of bits the trunc removes
4190 if (N0.getOpcode() == ISD::TRUNCATE &&
4191 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4192 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4193 N0.getOperand(0).hasOneUse() &&
4194 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004195 N1C) {
4196 SDValue N0Op0 = N0.getOperand(0);
4197 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4198 unsigned LargeShiftVal = LargeShift->getZExtValue();
4199 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004200
Matt Arsenault985b9de2014-03-17 18:58:01 +00004201 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4202 SDValue Amt =
4203 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4204 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4205 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4206 N0Op0.getOperand(0), Amt);
4207 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4208 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004209 }
4210 }
4211
Scott Michelcf0da6c2009-02-17 22:15:04 +00004212 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004213 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4214 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004215
4216
Nate Begeman21158fc2005-09-01 00:19:25 +00004217 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004218 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004219 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004220
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004221 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004222 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004223 if (NewSRA.getNode())
4224 return NewSRA;
4225 }
4226
Evan Chengf1005572010-04-28 07:10:39 +00004227 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004228}
4229
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004230SDValue DAGCombiner::visitSRL(SDNode *N) {
4231 SDValue N0 = N->getOperand(0);
4232 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004233 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4234 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004235 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004236 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004237
Daniel Sandersa1840d22013-11-11 17:23:41 +00004238 // fold vector ops
4239 if (VT.isVector()) {
4240 SDValue FoldedVOp = SimplifyVBinOp(N);
4241 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004242
4243 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004244 }
4245
Nate Begeman21158fc2005-09-01 00:19:25 +00004246 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004247 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004248 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004249 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004250 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004251 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004252 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004253 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004254 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004255 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004256 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004257 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004258 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004259 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004260 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004261 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004262
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004263 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004264 if (N1C && N0.getOpcode() == ISD::SRL) {
4265 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4266 uint64_t c1 = N01C->getZExtValue();
4267 uint64_t c2 = N1C->getZExtValue();
4268 if (c1 + c2 >= OpSizeInBits)
4269 return DAG.getConstant(0, VT);
4270 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4271 DAG.getConstant(c1 + c2, N1.getValueType()));
4272 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004273 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004274
Dale Johannesencd538af2010-12-17 21:45:49 +00004275 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004276 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4277 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004278 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004279 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004280 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4281 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004282 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4283 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004284 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004285 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004286 if (c1 + OpSizeInBits == InnerShiftSize) {
4287 if (c1 + c2 >= InnerShiftSize)
4288 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004289 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4290 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004291 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004292 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004293 }
4294 }
4295
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004296 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004297 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4298 unsigned BitSize = N0.getScalarValueSizeInBits();
4299 if (BitSize <= 64) {
4300 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4301 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4302 DAG.getConstant(~0ULL >> ShAmt, VT));
4303 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004304 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004305
Michael Liao62ebfd82013-06-21 18:45:27 +00004306 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004307 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4308 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004309 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004310 unsigned BitSize = SmallVT.getScalarSizeInBits();
4311 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004312 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004313
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004314 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004315 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004316 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004317 N0.getOperand(0),
4318 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004319 AddToWorkList(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004320 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004321 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4322 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4323 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004324 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004325 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004326
Chris Lattner2e33fb42006-10-12 20:23:19 +00004327 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4328 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004329 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004330 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004331 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004332 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004333
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004334 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004335 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004336 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004337 APInt KnownZero, KnownOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004338 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004339
Chris Lattner49932492006-04-02 06:11:11 +00004340 // If any of the input bits are KnownOne, then the input couldn't be all
4341 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004342 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004343
Chris Lattner49932492006-04-02 06:11:11 +00004344 // If all of the bits input the to ctlz node are known to be zero, then
4345 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004346 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004347 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004348
Chris Lattner49932492006-04-02 06:11:11 +00004349 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004350 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004351 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004352 // could be set on input to the CTLZ node. If this bit is set, the SRL
4353 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4354 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004355 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004356 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004357
Chris Lattner49932492006-04-02 06:11:11 +00004358 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004359 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004360 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004361 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004362 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004363
Andrew Trickef9de2a2013-05-25 02:42:55 +00004364 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004365 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004366 }
4367 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004368
Duncan Sands3ed76882009-02-01 18:06:53 +00004369 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004370 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004371 N1.getOperand(0).getOpcode() == ISD::AND) {
4372 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4373 if (NewOp1.getNode())
4374 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004375 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004376
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004377 // fold operands of srl based on knowledge that the low bits are not
4378 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004379 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4380 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004381
Evan Chengb175de62009-12-18 21:31:31 +00004382 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004383 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004384 if (NewSRL.getNode())
4385 return NewSRL;
4386 }
4387
Dan Gohman600f62b2010-06-24 14:30:44 +00004388 // Attempt to convert a srl of a load into a narrower zero-extending load.
4389 SDValue NarrowLoad = ReduceLoadWidth(N);
4390 if (NarrowLoad.getNode())
4391 return NarrowLoad;
4392
Evan Chengb175de62009-12-18 21:31:31 +00004393 // Here is a common situation. We want to optimize:
4394 //
4395 // %a = ...
4396 // %b = and i32 %a, 2
4397 // %c = srl i32 %b, 1
4398 // brcond i32 %c ...
4399 //
4400 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004401 //
Evan Chengb175de62009-12-18 21:31:31 +00004402 // %a = ...
4403 // %b = and %a, 2
4404 // %c = setcc eq %b, 0
4405 // brcond %c ...
4406 //
4407 // However when after the source operand of SRL is optimized into AND, the SRL
4408 // itself may not be optimized further. Look for it and add the BRCOND into
4409 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004410 if (N->hasOneUse()) {
4411 SDNode *Use = *N->use_begin();
4412 if (Use->getOpcode() == ISD::BRCOND)
4413 AddToWorkList(Use);
4414 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4415 // Also look pass the truncate.
4416 Use = *Use->use_begin();
4417 if (Use->getOpcode() == ISD::BRCOND)
4418 AddToWorkList(Use);
4419 }
4420 }
Evan Chengb175de62009-12-18 21:31:31 +00004421
Evan Chengf1005572010-04-28 07:10:39 +00004422 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004423}
4424
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004425SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4426 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004427 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004428
4429 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004430 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004431 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004432 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004433}
4434
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004435SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4436 SDValue N0 = N->getOperand(0);
4437 EVT VT = N->getValueType(0);
4438
4439 // fold (ctlz_zero_undef c1) -> c2
4440 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004441 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004442 return SDValue();
4443}
4444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004445SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4446 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004447 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004448
Nate Begeman21158fc2005-09-01 00:19:25 +00004449 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004450 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004451 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004452 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004453}
4454
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004455SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4456 SDValue N0 = N->getOperand(0);
4457 EVT VT = N->getValueType(0);
4458
4459 // fold (cttz_zero_undef c1) -> c2
4460 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004461 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004462 return SDValue();
4463}
4464
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004465SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4466 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004467 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004468
Nate Begeman21158fc2005-09-01 00:19:25 +00004469 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004470 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004471 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004472 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004473}
4474
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004475SDValue DAGCombiner::visitSELECT(SDNode *N) {
4476 SDValue N0 = N->getOperand(0);
4477 SDValue N1 = N->getOperand(1);
4478 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004479 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4480 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4481 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004482 EVT VT = N->getValueType(0);
4483 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004484
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004485 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004486 if (N1 == N2)
4487 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004488 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004489 if (N0C && !N0C->isNullValue())
4490 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004491 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004492 if (N0C && N0C->isNullValue())
4493 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004494 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004495 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004496 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004497 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004498 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004499 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004500 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004501 TLI.getBooleanContents(false) ==
4502 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004503 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004504 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004505 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004506 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004507 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004508 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004509 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004510 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004511 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004512 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4513 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004514 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004515 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004516 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004517 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004518 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004519 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004520 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004521 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004522 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004523 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004524 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004525 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004526 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004527 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004528 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004529 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004530 // fold (select X, X, Y) -> (or X, Y)
4531 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004532 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004533 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004534 // fold (select X, Y, X) -> (and X, Y)
4535 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004536 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004537 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004538
Chris Lattner6c14c352005-10-18 06:04:22 +00004539 // If we can fold this based on the true/false value, do so.
4540 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004541 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004542
Nate Begemanc760f802005-09-19 22:34:01 +00004543 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004544 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004545 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004546 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004547 // having to say they don't support SELECT_CC on every type the DAG knows
4548 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004549 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004550 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004551 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004552 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004553 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004554 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004555 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004556
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004557 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004558}
4559
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004560static
4561std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4562 SDLoc DL(N);
4563 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004564 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004565
4566 // Split the inputs.
4567 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004568 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4569 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004570
4571 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4572 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4573
4574 return std::make_pair(Lo, Hi);
4575}
4576
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004577SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4578 SDValue N0 = N->getOperand(0);
4579 SDValue N1 = N->getOperand(1);
4580 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004581 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004582
4583 // Canonicalize integer abs.
4584 // vselect (setg[te] X, 0), X, -X ->
4585 // vselect (setgt X, -1), X, -X ->
4586 // vselect (setl[te] X, 0), -X, X ->
4587 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4588 if (N0.getOpcode() == ISD::SETCC) {
4589 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4590 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4591 bool isAbs = false;
4592 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4593
4594 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4595 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4596 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4597 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4598 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4599 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4600 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4601
4602 if (isAbs) {
4603 EVT VT = LHS.getValueType();
4604 SDValue Shift = DAG.getNode(
4605 ISD::SRA, DL, VT, LHS,
4606 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4607 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4608 AddToWorkList(Shift.getNode());
4609 AddToWorkList(Add.getNode());
4610 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4611 }
4612 }
4613
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004614 // If the VSELECT result requires splitting and the mask is provided by a
4615 // SETCC, then split both nodes and its operands before legalization. This
4616 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4617 // and enables future optimizations (e.g. min/max pattern matching on X86).
4618 if (N0.getOpcode() == ISD::SETCC) {
4619 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004620
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004621 // Check if any splitting is required.
4622 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4623 TargetLowering::TypeSplitVector)
4624 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004625
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004626 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004627 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4628 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4629 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004630
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004631 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4632 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004633
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004634 // Add the new VSELECT nodes to the work list in case they need to be split
4635 // again.
4636 AddToWorkList(Lo.getNode());
4637 AddToWorkList(Hi.getNode());
4638
4639 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004640 }
4641
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004642 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4643 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4644 return N1;
4645 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4646 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4647 return N2;
4648
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004649 return SDValue();
4650}
4651
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004652SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4653 SDValue N0 = N->getOperand(0);
4654 SDValue N1 = N->getOperand(1);
4655 SDValue N2 = N->getOperand(2);
4656 SDValue N3 = N->getOperand(3);
4657 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004658 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004659
Nate Begemanc760f802005-09-19 22:34:01 +00004660 // fold select_cc lhs, rhs, x, x, cc -> x
4661 if (N2 == N3)
4662 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004663
Chris Lattner8b68dec2006-09-20 06:19:26 +00004664 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004665 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004666 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004667 if (SCC.getNode()) {
4668 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004669
Stephen Lin605207f2013-06-15 04:03:33 +00004670 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4671 if (!SCCC->isNullValue())
4672 return N2; // cond always true -> true val
4673 else
4674 return N3; // cond always false -> false val
4675 }
4676
4677 // Fold to a simpler select_cc
4678 if (SCC.getOpcode() == ISD::SETCC)
4679 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4680 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4681 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004682 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004683
Chris Lattner6c14c352005-10-18 06:04:22 +00004684 // If we can fold this based on the true/false value, do so.
4685 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004686 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004687
Nate Begemanc760f802005-09-19 22:34:01 +00004688 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004689 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004690}
4691
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004692SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004693 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004694 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004695 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004696}
4697
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004698// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4699// dag node into a ConstantSDNode or a build_vector of constants.
4700// This function is called by the DAGCombiner when visiting sext/zext/aext
4701// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4702// Vector extends are not folded if operations are legal; this is to
4703// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004704static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4705 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004706 bool LegalOperations) {
4707 unsigned Opcode = N->getOpcode();
4708 SDValue N0 = N->getOperand(0);
4709 EVT VT = N->getValueType(0);
4710
4711 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4712 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4713
4714 // fold (sext c1) -> c1
4715 // fold (zext c1) -> c1
4716 // fold (aext c1) -> c1
4717 if (isa<ConstantSDNode>(N0))
4718 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4719
4720 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4721 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4722 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004723 EVT SVT = VT.getScalarType();
4724 if (!(VT.isVector() &&
4725 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004726 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004727 return nullptr;
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004728
4729 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004730 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004731 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4732 unsigned ShAmt = VTBits - EVTBits;
4733 SmallVector<SDValue, 8> Elts;
4734 unsigned NumElts = N0->getNumOperands();
4735 SDLoc DL(N);
4736
4737 for (unsigned i=0; i != NumElts; ++i) {
4738 SDValue Op = N0->getOperand(i);
4739 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004740 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004741 continue;
4742 }
4743
4744 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4745 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4746 if (Opcode == ISD::SIGN_EXTEND)
4747 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004748 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004749 else
4750 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004751 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004752 }
4753
4754 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4755}
4756
Evan Chenge106e2f2007-10-29 19:58:20 +00004757// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004758// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004759// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004760// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004761static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004762 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004763 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004764 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004765 bool HasCopyToRegUses = false;
4766 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004767 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4768 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004769 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004770 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004771 if (User == N)
4772 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004773 if (UI.getUse().getResNo() != N0.getResNo())
4774 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004775 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004776 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004777 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4778 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4779 // Sign bits will be lost after a zext.
4780 return false;
4781 bool Add = false;
4782 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004783 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004784 if (UseOp == N0)
4785 continue;
4786 if (!isa<ConstantSDNode>(UseOp))
4787 return false;
4788 Add = true;
4789 }
4790 if (Add)
4791 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004792 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004793 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004794 // If truncates aren't free and there are users we can't
4795 // extend, it isn't worthwhile.
4796 if (!isTruncFree)
4797 return false;
4798 // Remember if this value is live-out.
4799 if (User->getOpcode() == ISD::CopyToReg)
4800 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004801 }
4802
4803 if (HasCopyToRegUses) {
4804 bool BothLiveOut = false;
4805 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4806 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004807 SDUse &Use = UI.getUse();
4808 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4809 BothLiveOut = true;
4810 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004811 }
4812 }
4813 if (BothLiveOut)
4814 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004815 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004816 return ExtendNodes.size();
4817 }
4818 return true;
4819}
4820
Craig Toppere0b71182013-07-13 07:43:40 +00004821void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004822 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004823 ISD::NodeType ExtType) {
4824 // Extend SetCC uses if necessary.
4825 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4826 SDNode *SetCC = SetCCs[i];
4827 SmallVector<SDValue, 4> Ops;
4828
4829 for (unsigned j = 0; j != 2; ++j) {
4830 SDValue SOp = SetCC->getOperand(j);
4831 if (SOp == Trunc)
4832 Ops.push_back(ExtLoad);
4833 else
4834 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4835 }
4836
4837 Ops.push_back(SetCC->getOperand(2));
4838 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4839 &Ops[0], Ops.size()));
4840 }
4841}
4842
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004843SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4844 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004845 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004846
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004847 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4848 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004849 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004850
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004851 // fold (sext (sext x)) -> (sext x)
4852 // fold (sext (aext x)) -> (sext x)
4853 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004854 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004855 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004856
Chris Lattnerfce448f2007-02-26 03:13:59 +00004857 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004858 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4859 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004860 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4861 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004862 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4863 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004864 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004865 // CombineTo deleted the truncate, if needed, but not what's under it.
4866 AddToWorkList(oye);
4867 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004869 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004870
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004871 // See if the value being truncated is already sign extended. If so, just
4872 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004873 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004874 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4875 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4876 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004877 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004878
Chris Lattnerfce448f2007-02-26 03:13:59 +00004879 if (OpBits == DestBits) {
4880 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4881 // bits, it is already ready.
4882 if (NumSignBits > DestBits-MidBits)
4883 return Op;
4884 } else if (OpBits < DestBits) {
4885 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4886 // bits, just sext from i32.
4887 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004888 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004889 } else {
4890 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4891 // bits, just truncate to i32.
4892 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004893 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004894 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004895
Chris Lattnerfce448f2007-02-26 03:13:59 +00004896 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004897 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4898 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004899 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004900 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004901 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004902 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4903 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004904 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004905 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004906 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004907
Evan Chengbce7c472005-12-14 02:19:23 +00004908 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004909 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004910 // on vectors in one instruction. We only perform this transformation on
4911 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004912 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004913 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004914 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004915 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004916 bool DoXform = true;
4917 SmallVector<SDNode*, 4> SetCCs;
4918 if (!N0.hasOneUse())
4919 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4920 if (DoXform) {
4921 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004922 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004923 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004924 LN0->getBasePtr(), N0.getValueType(),
4925 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004926 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004927 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004928 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004929 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004930 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004931 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004932 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004933 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004934 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004935
4936 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4937 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004938 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4939 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004940 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004941 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004942 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004943 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004944 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004945 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004946 LN0->getBasePtr(), MemVT,
4947 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004948 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004949 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004950 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004951 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004952 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004953 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004954 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004955 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004956
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004957 // fold (sext (and/or/xor (load x), cst)) ->
4958 // (and/or/xor (sextload x), (sext cst))
4959 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4960 N0.getOpcode() == ISD::XOR) &&
4961 isa<LoadSDNode>(N0.getOperand(0)) &&
4962 N0.getOperand(1).getOpcode() == ISD::Constant &&
4963 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4964 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4965 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004966 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004967 bool DoXform = true;
4968 SmallVector<SDNode*, 4> SetCCs;
4969 if (!N0.hasOneUse())
4970 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4971 SetCCs, TLI);
4972 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004973 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004974 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004975 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004976 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004977 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4978 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004979 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004980 ExtLoad, DAG.getConstant(Mask, VT));
4981 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004982 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004983 N0.getOperand(0).getValueType(), ExtLoad);
4984 CombineTo(N, And);
4985 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004986 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004987 ISD::SIGN_EXTEND);
4988 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4989 }
4990 }
4991 }
4992
Chris Lattner65786b02007-04-11 05:32:27 +00004993 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00004994 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00004995 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00004996 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00004997 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00004998 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00004999 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00005000 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5001 // of the same size as the compared operands. Only optimize sext(setcc())
5002 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005003 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005004
5005 // We know that the # elements of the results is the same as the
5006 // # elements of the compare (and the # elements of the compare result
5007 // for that matter). Check to see that they are the same size. If so,
5008 // we know that the element size of the sext'd result matches the
5009 // element size of the compare operands.
5010 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005011 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005012 N0.getOperand(1),
5013 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005014
Dan Gohmane82c25e2010-04-30 17:19:19 +00005015 // If the desired elements are smaller or larger than the source
5016 // elements we can use a matching integer vector type and then
5017 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005018 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005019 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005020 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005021 N0.getOperand(0), N0.getOperand(1),
5022 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005023 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005024 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005025 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005026
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005027 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005028 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005029 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005030 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005031 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005032 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005033 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005034 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005035 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005036
5037 if (!VT.isVector()) {
5038 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5039 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5040 SDLoc DL(N);
5041 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5042 SDValue SetCC = DAG.getSetCC(DL,
5043 SetCCVT,
5044 N0.getOperand(0), N0.getOperand(1), CC);
5045 EVT SelectVT = getSetCCResultType(VT);
5046 return DAG.getSelect(DL, VT,
5047 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5048 NegOne, DAG.getConstant(0, VT));
5049
5050 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005051 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005052 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005053
Dan Gohman3eb10f72008-04-28 16:58:24 +00005054 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005055 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005056 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005057 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005058
Evan Chengf1005572010-04-28 07:10:39 +00005059 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005060}
5061
Rafael Espindola8f62b322012-04-09 16:06:03 +00005062// isTruncateOf - If N is a truncate of some other value, return true, record
5063// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5064// This function computes KnownZero to avoid a duplicated call to
5065// ComputeMaskedBits in the caller.
5066static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5067 APInt &KnownZero) {
5068 APInt KnownOne;
5069 if (N->getOpcode() == ISD::TRUNCATE) {
5070 Op = N->getOperand(0);
5071 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5072 return true;
5073 }
5074
5075 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5076 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5077 return false;
5078
5079 SDValue Op0 = N->getOperand(0);
5080 SDValue Op1 = N->getOperand(1);
5081 assert(Op0.getValueType() == Op1.getValueType());
5082
5083 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5084 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005085 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005086 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005087 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005088 Op = Op0;
5089 else
5090 return false;
5091
5092 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5093
5094 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5095 return false;
5096
5097 return true;
5098}
5099
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005100SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5101 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005102 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005103
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005104 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5105 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005106 return SDValue(Res, 0);
5107
Nate Begeman21158fc2005-09-01 00:19:25 +00005108 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005109 // fold (zext (aext x)) -> (zext x)
5110 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005111 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005112 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005113
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005114 // fold (zext (truncate x)) -> (zext x) or
5115 // (zext (truncate x)) -> (truncate x)
5116 // This is valid when the truncated bits of x are already zero.
5117 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005118 SDValue Op;
5119 APInt KnownZero;
5120 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5121 APInt TruncatedBits =
5122 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5123 APInt(Op.getValueSizeInBits(), 0) :
5124 APInt::getBitsSet(Op.getValueSizeInBits(),
5125 N0.getValueSizeInBits(),
5126 std::min(Op.getValueSizeInBits(),
5127 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005128 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005129 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005130 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005131 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005132 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005133
5134 return Op;
5135 }
5136 }
5137
Evan Cheng464dc9b2007-03-22 01:54:19 +00005138 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5139 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005140 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005141 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5142 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005143 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5144 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005145 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005146 // CombineTo deleted the truncate, if needed, but not what's under it.
5147 AddToWorkList(oye);
5148 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005149 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005150 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005151 }
5152
Chris Lattnera31f0a62006-09-21 06:00:20 +00005153 // fold (zext (truncate x)) -> (and x, mask)
5154 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005155 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005156
5157 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5158 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5159 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5160 if (NarrowLoad.getNode()) {
5161 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5162 if (NarrowLoad.getNode() != N0.getNode()) {
5163 CombineTo(N0.getNode(), NarrowLoad);
5164 // CombineTo deleted the truncate, if needed, but not what's under it.
5165 AddToWorkList(oye);
5166 }
5167 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5168 }
5169
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005170 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005171 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005172 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005173 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005174 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005175 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005176 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005177 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005178 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005179 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005180 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005181
Dan Gohmanad3e5492009-04-08 00:15:30 +00005182 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5183 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005184 if (N0.getOpcode() == ISD::AND &&
5185 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005186 N0.getOperand(1).getOpcode() == ISD::Constant &&
5187 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5188 N0.getValueType()) ||
5189 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005190 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005191 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005192 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005193 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005194 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005195 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005196 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005197 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005198 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005199 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005200 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005201
Evan Chengbce7c472005-12-14 02:19:23 +00005202 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005203 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005204 // on vectors in one instruction. We only perform this transformation on
5205 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005206 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005207 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005208 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005209 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005210 bool DoXform = true;
5211 SmallVector<SDNode*, 4> SetCCs;
5212 if (!N0.hasOneUse())
5213 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5214 if (DoXform) {
5215 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005216 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005217 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005218 LN0->getBasePtr(), N0.getValueType(),
5219 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005220 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005221 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005222 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005223 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005224
Andrew Trickef9de2a2013-05-25 02:42:55 +00005225 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005226 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005227 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005228 }
Evan Chengbce7c472005-12-14 02:19:23 +00005229 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005230
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005231 // fold (zext (and/or/xor (load x), cst)) ->
5232 // (and/or/xor (zextload x), (zext cst))
5233 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5234 N0.getOpcode() == ISD::XOR) &&
5235 isa<LoadSDNode>(N0.getOperand(0)) &&
5236 N0.getOperand(1).getOpcode() == ISD::Constant &&
5237 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5238 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5239 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005240 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005241 bool DoXform = true;
5242 SmallVector<SDNode*, 4> SetCCs;
5243 if (!N0.hasOneUse())
5244 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5245 SetCCs, TLI);
5246 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005247 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005248 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005249 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005250 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005251 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5252 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005253 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005254 ExtLoad, DAG.getConstant(Mask, VT));
5255 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005256 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005257 N0.getOperand(0).getValueType(), ExtLoad);
5258 CombineTo(N, And);
5259 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005260 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005261 ISD::ZERO_EXTEND);
5262 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5263 }
5264 }
5265 }
5266
Chris Lattner7dac1082005-12-14 19:05:06 +00005267 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5268 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005269 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5270 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005271 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005272 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005273 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005274 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005275 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005276 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005277 LN0->getBasePtr(), MemVT,
5278 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005279 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005280 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005281 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005282 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005283 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005284 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005285 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005286 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005287
Chris Lattner65786b02007-04-11 05:32:27 +00005288 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005289 if (!LegalOperations && VT.isVector() &&
5290 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005291 EVT N0VT = N0.getOperand(0).getValueType();
5292 if (getSetCCResultType(N0VT) == N0.getValueType())
5293 return SDValue();
5294
Evan Chengabd0ad52010-05-19 01:08:17 +00005295 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5296 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005297 EVT EltVT = VT.getVectorElementType();
5298 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5299 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005300 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005301 // We know that the # elements of the results is the same as the
5302 // # elements of the compare (and the # elements of the compare result
5303 // for that matter). Check to see that they are the same size. If so,
5304 // we know that the element size of the sext'd result matches the
5305 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005306 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5307 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005308 N0.getOperand(1),
5309 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005310 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Chengabd0ad52010-05-19 01:08:17 +00005311 &OneOps[0], OneOps.size()));
Dan Gohman4298df62011-05-17 22:20:36 +00005312
5313 // If the desired elements are smaller or larger than the source
5314 // elements we can use a matching integer vector type and then
5315 // truncate/sign extend
5316 EVT MatchingElementType =
5317 EVT::getIntegerVT(*DAG.getContext(),
5318 N0VT.getScalarType().getSizeInBits());
5319 EVT MatchingVectorType =
5320 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5321 N0VT.getVectorNumElements());
5322 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005323 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005324 N0.getOperand(1),
5325 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005326 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5327 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5328 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman4298df62011-05-17 22:20:36 +00005329 &OneOps[0], OneOps.size()));
Evan Chengabd0ad52010-05-19 01:08:17 +00005330 }
5331
5332 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005333 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005334 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005335 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005336 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005337 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005338 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005339
Evan Cheng852c4862009-12-15 03:00:32 +00005340 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005341 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005342 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005343 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5344 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005345 SDValue ShAmt = N0.getOperand(1);
5346 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005347 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005348 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005349 // If the original shl may be shifting out bits, do not perform this
5350 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005351 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5352 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5353 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005354 return SDValue();
5355 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005356
Andrew Trickef9de2a2013-05-25 02:42:55 +00005357 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005358
5359 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005360 if (VT.getSizeInBits() >= 256)
5361 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005362
Chris Lattnere95d1952011-02-13 19:09:16 +00005363 return DAG.getNode(N0.getOpcode(), DL, VT,
5364 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5365 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005366 }
5367
Evan Chengf1005572010-04-28 07:10:39 +00005368 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005369}
5370
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005371SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5372 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005373 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005374
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005375 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5376 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005377 return SDValue(Res, 0);
5378
Chris Lattner812646a2006-05-05 05:58:59 +00005379 // fold (aext (aext x)) -> (aext x)
5380 // fold (aext (zext x)) -> (zext x)
5381 // fold (aext (sext x)) -> (sext x)
5382 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5383 N0.getOpcode() == ISD::ZERO_EXTEND ||
5384 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005385 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005386
Evan Cheng464dc9b2007-03-22 01:54:19 +00005387 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5388 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5389 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005390 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5391 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005392 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5393 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005394 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005395 // CombineTo deleted the truncate, if needed, but not what's under it.
5396 AddToWorkList(oye);
5397 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005398 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005399 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005400 }
5401
Chris Lattner8746e2c2006-09-20 06:29:17 +00005402 // fold (aext (truncate x))
5403 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005404 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005405 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005406 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005407 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005408 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5409 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005410 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005411
Dan Gohmanad3e5492009-04-08 00:15:30 +00005412 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5413 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005414 if (N0.getOpcode() == ISD::AND &&
5415 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005416 N0.getOperand(1).getOpcode() == ISD::Constant &&
5417 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5418 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005419 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005420 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005421 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005422 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005423 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005424 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005425 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005426 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005427 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005428 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005429 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005430
Chris Lattner812646a2006-05-05 05:58:59 +00005431 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005432 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005433 // on vectors in one instruction. We only perform this transformation on
5434 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005435 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005436 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005437 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005438 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005439 bool DoXform = true;
5440 SmallVector<SDNode*, 4> SetCCs;
5441 if (!N0.hasOneUse())
5442 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5443 if (DoXform) {
5444 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005445 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005446 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005447 LN0->getBasePtr(), N0.getValueType(),
5448 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005449 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005450 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005451 N0.getValueType(), ExtLoad);
5452 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005453 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005454 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005455 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5456 }
Chris Lattner812646a2006-05-05 05:58:59 +00005457 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005458
Chris Lattner812646a2006-05-05 05:58:59 +00005459 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5460 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5461 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005462 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005463 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005464 N0.hasOneUse()) {
5465 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005466 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005467 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005468 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5469 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5470 VT, LN0->getChain(), LN0->getBasePtr(),
5471 MemVT, LN0->getMemOperand());
5472 CombineTo(N, ExtLoad);
5473 CombineTo(N0.getNode(),
5474 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5475 N0.getValueType(), ExtLoad),
5476 ExtLoad.getValue(1));
5477 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5478 }
Chris Lattner812646a2006-05-05 05:58:59 +00005479 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005480
Chris Lattner65786b02007-04-11 05:32:27 +00005481 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005482 // For vectors:
5483 // aext(setcc) -> vsetcc
5484 // aext(setcc) -> truncate(vsetcc)
5485 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005486 // Only do this before legalize for now.
5487 if (VT.isVector() && !LegalOperations) {
5488 EVT N0VT = N0.getOperand(0).getValueType();
5489 // We know that the # elements of the results is the same as the
5490 // # elements of the compare (and the # elements of the compare result
5491 // for that matter). Check to see that they are the same size. If so,
5492 // we know that the element size of the sext'd result matches the
5493 // element size of the compare operands.
5494 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005495 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005496 N0.getOperand(1),
5497 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005498 // If the desired elements are smaller or larger than the source
5499 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005500 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005501 else {
Hao Liuc636d152014-04-22 09:57:06 +00005502 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005503 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005504 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005505 N0.getOperand(1),
5506 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005507 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005508 }
5509 }
5510
5511 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005512 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005513 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005514 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005515 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005516 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005517 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005518 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005519
Evan Chengf1005572010-04-28 07:10:39 +00005520 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005521}
5522
Chris Lattner5e6fe052007-10-13 06:35:54 +00005523/// GetDemandedBits - See if the specified operand can be simplified with the
5524/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005525/// simpler operand, otherwise return a null SDValue.
5526SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005527 switch (V.getOpcode()) {
5528 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005529 case ISD::Constant: {
5530 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005531 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005532 const APInt &CVal = CV->getAPIntValue();
5533 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005534 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005535 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005536 break;
5537 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005538 case ISD::OR:
5539 case ISD::XOR:
5540 // If the LHS or RHS don't contribute bits to the or, drop them.
5541 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5542 return V.getOperand(1);
5543 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5544 return V.getOperand(0);
5545 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005546 case ISD::SRL:
5547 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005548 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005549 break;
5550 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5551 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005552 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005553
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005554 // Watch out for shift count overflow though.
5555 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005556 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005557 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005558 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005559 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005560 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005561 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005562 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005563 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005564}
5565
Evan Cheng464dc9b2007-03-22 01:54:19 +00005566/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5567/// bits and then truncated to a narrower type and where N is a multiple
5568/// of number of bits of the narrower type, transform it to a narrower load
5569/// from address + N / num of bits of new type. If the result is to be
5570/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005571SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005572 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005573
Evan Cheng464dc9b2007-03-22 01:54:19 +00005574 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005575 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005576 EVT VT = N->getValueType(0);
5577 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005578
Dan Gohman550c9af2008-08-14 20:04:46 +00005579 // This transformation isn't valid for vector loads.
5580 if (VT.isVector())
5581 return SDValue();
5582
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005583 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005584 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005585 if (Opc == ISD::SIGN_EXTEND_INREG) {
5586 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005587 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005588 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005589 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005590 ExtType = ISD::ZEXTLOAD;
5591 N0 = SDValue(N, 0);
5592 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5593 if (!N01) return SDValue();
5594 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5595 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005596 }
Richard Osborne272e0842011-01-31 17:41:44 +00005597 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5598 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005599
Owen Anderson53aa7a92009-08-10 22:56:29 +00005600 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005601
Chris Lattner9a499e92010-12-22 08:01:44 +00005602 // Do not generate loads of non-round integer types since these can
5603 // be expensive (and would be wrong if the type is not byte sized).
5604 if (!ExtVT.isRound())
5605 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005606
Evan Cheng464dc9b2007-03-22 01:54:19 +00005607 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005608 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005609 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005610 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005611 // Is the shift amount a multiple of size of VT?
5612 if ((ShAmt & (EVTBits-1)) == 0) {
5613 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005614 // Is the load width a multiple of size of VT?
5615 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005616 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005617 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005618
Chris Lattnercafc1e62010-12-22 08:02:57 +00005619 // At this point, we must have a load or else we can't do the transform.
5620 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005621
Chandler Carruthb27041c2012-12-11 00:36:57 +00005622 // Because a SRL must be assumed to *need* to zero-extend the high bits
5623 // (as opposed to anyext the high bits), we can't combine the zextload
5624 // lowering of SRL and an sextload.
5625 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5626 return SDValue();
5627
Chris Lattnera2050552010-10-01 05:36:09 +00005628 // If the shift amount is larger than the input type then we're not
5629 // accessing any of the loaded bytes. If the load was a zextload/extload
5630 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005631 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005632 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005633 }
5634 }
5635
Dan Gohman68fb0042010-11-03 01:47:46 +00005636 // If the load is shifted left (and the result isn't shifted back right),
5637 // we can fold the truncate through the shift.
5638 unsigned ShLeftAmt = 0;
5639 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005640 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005641 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5642 ShLeftAmt = N01->getZExtValue();
5643 N0 = N0.getOperand(0);
5644 }
5645 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005646
Chris Lattner222374d2010-12-22 07:36:50 +00005647 // If we haven't found a load, we can't narrow it. Don't transform one with
5648 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005649 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5650 return SDValue();
5651
5652 // Don't change the width of a volatile load.
5653 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5654 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005655 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005656
Chris Lattner9a499e92010-12-22 08:01:44 +00005657 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005658 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005659 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005660
Bill Schmidtd006c692013-01-14 22:04:38 +00005661 // For the transform to be legal, the load must produce only two values
5662 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005663 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005664 // transformation is not equivalent, and the downstream logic to replace
5665 // uses gets things wrong.
5666 if (LN0->getNumValues() > 2)
5667 return SDValue();
5668
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005669 // If the load that we're shrinking is an extload and we're not just
5670 // discarding the extension we can't simply shrink the load. Bail.
5671 // TODO: It would be possible to merge the extensions in some cases.
5672 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5673 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5674 return SDValue();
5675
Chris Lattner222374d2010-12-22 07:36:50 +00005676 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005677
Evan Cheng4c6f9172012-06-26 01:19:33 +00005678 if (PtrType == MVT::Untyped || PtrType.isExtended())
5679 // It's not possible to generate a constant of extended or untyped type.
5680 return SDValue();
5681
Chris Lattner222374d2010-12-22 07:36:50 +00005682 // For big endian targets, we need to adjust the offset to the pointer to
5683 // load the correct bytes.
5684 if (TLI.isBigEndian()) {
5685 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5686 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5687 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005688 }
5689
Chris Lattner222374d2010-12-22 07:36:50 +00005690 uint64_t PtrOff = ShAmt / 8;
5691 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005692 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005693 PtrType, LN0->getBasePtr(),
5694 DAG.getConstant(PtrOff, PtrType));
5695 AddToWorkList(NewPtr.getNode());
5696
Chris Lattner9a499e92010-12-22 08:01:44 +00005697 SDValue Load;
5698 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005699 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005700 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005701 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005702 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005703 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005704 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005705 LN0->getPointerInfo().getWithOffset(PtrOff),
5706 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005707 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005708
5709 // Replace the old load's chain with the new load's chain.
5710 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005711 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005712
5713 // Shift the result left, if we've swallowed a left shift.
5714 SDValue Result = Load;
5715 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005716 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005717 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5718 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005719 // If the shift amount is as large as the result size (but, presumably,
5720 // no larger than the source) then the useful bits of the result are
5721 // zero; we can't simply return the shortened shift, because the result
5722 // of that operation is undefined.
5723 if (ShLeftAmt >= VT.getSizeInBits())
5724 Result = DAG.getConstant(0, VT);
5725 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005726 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005727 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005728 }
5729
5730 // Return the new loaded value.
5731 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005732}
5733
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005734SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5735 SDValue N0 = N->getOperand(0);
5736 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005737 EVT VT = N->getValueType(0);
5738 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005739 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005740 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005741
Nate Begeman21158fc2005-09-01 00:19:25 +00005742 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005743 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005744 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005745
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005746 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005747 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005748 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005749
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005750 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5751 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005752 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005753 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005754 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005755
Dan Gohman345d63c2008-07-31 00:50:31 +00005756 // fold (sext_in_reg (sext x)) -> (sext x)
5757 // fold (sext_in_reg (aext x)) -> (sext x)
5758 // if x is small enough.
5759 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5760 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005761 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5762 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005763 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005764 }
5765
Chris Lattner9ad59152007-04-17 19:03:21 +00005766 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005767 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005768 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005769
Chris Lattner9ad59152007-04-17 19:03:21 +00005770 // fold operands of sext_in_reg based on knowledge that the top bits are not
5771 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005772 if (SimplifyDemandedBits(SDValue(N, 0)))
5773 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005774
Evan Cheng464dc9b2007-03-22 01:54:19 +00005775 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5776 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005777 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005778 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005779 return NarrowLoad;
5780
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005781 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005782 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005783 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5784 if (N0.getOpcode() == ISD::SRL) {
5785 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005786 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005787 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005788 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005789 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005790 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005791 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005792 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005793 }
5794 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005795
Nate Begeman02b23c62005-10-13 03:11:28 +00005796 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005797 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005798 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005799 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005800 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005801 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005802 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005803 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005804 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005805 LN0->getBasePtr(), EVT,
5806 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005807 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005808 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005809 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005810 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005811 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005812 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005813 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005814 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005815 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005816 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005817 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005818 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005819 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005820 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005821 LN0->getBasePtr(), EVT,
5822 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005823 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005824 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005825 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005826 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005827
5828 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5829 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5830 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5831 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005832 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005833 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005834 BSwap, N1);
5835 }
5836
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005837 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5838 // into a build_vector.
5839 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5840 SmallVector<SDValue, 8> Elts;
5841 unsigned NumElts = N0->getNumOperands();
5842 unsigned ShAmt = VTBits - EVTBits;
5843
5844 for (unsigned i = 0; i != NumElts; ++i) {
5845 SDValue Op = N0->getOperand(i);
5846 if (Op->getOpcode() == ISD::UNDEF) {
5847 Elts.push_back(Op);
5848 continue;
5849 }
5850
5851 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005852 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5853 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005854 Op.getValueType()));
5855 }
5856
5857 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5858 }
5859
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005860 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005861}
5862
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005863SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5864 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005865 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005866 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005867
5868 // noop truncate
5869 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005870 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005871 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005872 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005873 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005874 // fold (truncate (truncate x)) -> (truncate x)
5875 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005876 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005877 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005878 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5879 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005880 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005881 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005882 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005883 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005884 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005885 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005886 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005887 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005888 // if the source and dest are the same type, we can drop both the extend
5889 // and the truncate.
5890 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005891 }
Evan Chengd63baea2007-03-21 20:14:05 +00005892
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005893 // Fold extract-and-trunc into a narrow extract. For example:
5894 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5895 // i32 y = TRUNCATE(i64 x)
5896 // -- becomes --
5897 // v16i8 b = BITCAST (v2i64 val)
5898 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5899 //
5900 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005901 // creates this pattern) and before operation legalization after which
5902 // we need to be more careful about the vector instructions that we generate.
5903 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005904 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005905
5906 EVT VecTy = N0.getOperand(0).getValueType();
5907 EVT ExTy = N0.getValueType();
5908 EVT TrTy = N->getValueType(0);
5909
5910 unsigned NumElem = VecTy.getVectorNumElements();
5911 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5912
5913 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5914 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5915
5916 SDValue EltNo = N0->getOperand(1);
5917 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5918 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005919 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005920 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5921
Andrew Trickef9de2a2013-05-25 02:42:55 +00005922 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005923 NVT, N0.getOperand(0));
5924
5925 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005926 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005927 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005928 }
5929 }
5930
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005931 // Fold a series of buildvector, bitcast, and truncate if possible.
5932 // For example fold
5933 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5934 // (2xi32 (buildvector x, y)).
5935 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5936 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5937 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5938 N0.getOperand(0).hasOneUse()) {
5939
5940 SDValue BuildVect = N0.getOperand(0);
5941 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5942 EVT TruncVecEltTy = VT.getVectorElementType();
5943
5944 // Check that the element types match.
5945 if (BuildVectEltTy == TruncVecEltTy) {
5946 // Now we only need to compute the offset of the truncated elements.
5947 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5948 unsigned TruncVecNumElts = VT.getVectorNumElements();
5949 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5950
5951 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5952 "Invalid number of elements");
5953
5954 SmallVector<SDValue, 8> Opnds;
5955 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5956 Opnds.push_back(BuildVect.getOperand(i));
5957
Andrew Trickef9de2a2013-05-25 02:42:55 +00005958 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005959 Opnds.size());
5960 }
5961 }
5962
Chris Lattner5e6fe052007-10-13 06:35:54 +00005963 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00005964 // only the low bits are being used.
5965 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00005966 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00005967 // may have different active low bits.
5968 if (!VT.isVector()) {
5969 SDValue Shorter =
5970 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5971 VT.getSizeInBits()));
5972 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005973 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00005974 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005975 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00005976 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00005977 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5978 SDValue Reduced = ReduceLoadWidth(N);
5979 if (Reduced.getNode())
5980 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00005981 // Handle the case where the load remains an extending load even
5982 // after truncation.
5983 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5984 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5985 if (!LN0->isVolatile() &&
5986 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5987 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5988 VT, LN0->getChain(), LN0->getBasePtr(),
5989 LN0->getMemoryVT(),
5990 LN0->getMemOperand());
5991 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5992 return NewLoad;
5993 }
5994 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005995 }
Michael Liao3ac82012012-10-17 23:45:54 +00005996 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5997 // where ... are all 'undef'.
5998 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5999 SmallVector<EVT, 8> VTs;
6000 SDValue V;
6001 unsigned Idx = 0;
6002 unsigned NumDefs = 0;
6003
6004 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6005 SDValue X = N0.getOperand(i);
6006 if (X.getOpcode() != ISD::UNDEF) {
6007 V = X;
6008 Idx = i;
6009 NumDefs++;
6010 }
6011 // Stop if more than one members are non-undef.
6012 if (NumDefs > 1)
6013 break;
6014 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6015 VT.getVectorElementType(),
6016 X.getValueType().getVectorNumElements()));
6017 }
6018
6019 if (NumDefs == 0)
6020 return DAG.getUNDEF(VT);
6021
6022 if (NumDefs == 1) {
6023 assert(V.getNode() && "The single defined operand is empty!");
6024 SmallVector<SDValue, 8> Opnds;
6025 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6026 if (i != Idx) {
6027 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6028 continue;
6029 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006030 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00006031 AddToWorkList(NV.getNode());
6032 Opnds.push_back(NV);
6033 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006034 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao3ac82012012-10-17 23:45:54 +00006035 &Opnds[0], Opnds.size());
6036 }
6037 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006038
6039 // Simplify the operands using demanded-bits information.
6040 if (!VT.isVector() &&
6041 SimplifyDemandedBits(SDValue(N, 0)))
6042 return SDValue(N, 0);
6043
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006044 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006045}
6046
Evan Chengb980f6f2008-05-12 23:04:07 +00006047static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006048 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006049 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006050 return Elt.getNode();
6051 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006052}
6053
6054/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006055/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006056SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006057 assert(N->getOpcode() == ISD::BUILD_PAIR);
6058
Nate Begeman624690c2009-06-05 21:37:30 +00006059 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6060 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006061 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006062 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006063 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006064 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006065
Evan Chengb980f6f2008-05-12 23:04:07 +00006066 if (ISD::isNON_EXTLoad(LD2) &&
6067 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006068 // If both are volatile this would reduce the number of volatile loads.
6069 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006070 !LD1->isVolatile() &&
6071 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006072 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006073 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006074 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006075 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006076
Duncan Sands8651e9c2008-06-13 19:07:40 +00006077 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006078 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006079 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006080 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006081 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006082 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006083
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006084 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006085}
6086
Wesley Peck527da1b2010-11-23 03:31:01 +00006087SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006088 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006089 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006090
Dan Gohmana8665142007-06-25 16:23:39 +00006091 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6092 // Only do this before legalize, since afterward the target may be depending
6093 // on the bitconvert.
6094 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006095 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006096 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006097 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006098 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006099
Owen Anderson53aa7a92009-08-10 22:56:29 +00006100 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006101 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006102 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006103 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006104 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006105 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006106
Dan Gohman921ddd62008-09-05 01:58:21 +00006107 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006108 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006109 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006110 if (Res.getNode() != N) {
6111 if (!LegalOperations ||
6112 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6113 return Res;
6114
6115 // Folding it resulted in an illegal node, and it's too late to
6116 // do that. Clean up the old node and forego the transformation.
6117 // Ideally this won't happen very often, because instcombine
6118 // and the earlier dagcombine runs (where illegal nodes are
6119 // permitted) should have folded most of them already.
6120 DAG.DeleteNode(Res.getNode());
6121 }
Chris Lattnera1874602005-12-23 05:30:37 +00006122 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006123
Bill Wendling4e0a6152009-01-30 22:44:24 +00006124 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006125 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006126 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006127 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006128
Chris Lattner54560f62005-12-23 05:44:41 +00006129 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006130 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006131 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006132 // Do not change the width of a volatile load.
6133 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006134 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6135 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006136 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006137 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006138 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006139 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006140
Evan Chenga4cf58a2007-05-07 21:27:48 +00006141 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006142 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006143 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006144 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006145 LN0->isInvariant(), OrigAlign,
6146 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006147 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006148 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006149 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006150 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006151 Load.getValue(1));
6152 return Load;
6153 }
Chris Lattner54560f62005-12-23 05:44:41 +00006154 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006155
Bill Wendling4e0a6152009-01-30 22:44:24 +00006156 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6157 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006158 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006159 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6160 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006161 N0.getNode()->hasOneUse() && VT.isInteger() &&
6162 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006163 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006164 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006165 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006166
Duncan Sands13237ac2008-06-06 12:08:01 +00006167 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006168 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006169 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006170 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006171 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006172 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006173 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006174 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006175
Bill Wendling4e0a6152009-01-30 22:44:24 +00006176 // fold (bitconvert (fcopysign cst, x)) ->
6177 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6178 // Note that we don't handle (copysign x, cst) because this can always be
6179 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006180 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006181 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006182 VT.isInteger() && !VT.isVector()) {
6183 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006184 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006185 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006186 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006187 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006188 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006189
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006190 // If X has a different width than the result/lhs, sext it or truncate it.
6191 unsigned VTWidth = VT.getSizeInBits();
6192 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006193 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006194 AddToWorkList(X.getNode());
6195 } else if (OrigXWidth > VTWidth) {
6196 // To get the sign bit in the right place, we have to shift it right
6197 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006198 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006199 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006200 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6201 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006202 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006203 AddToWorkList(X.getNode());
6204 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006205
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006206 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006207 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006208 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006209 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006210
Andrew Trickef9de2a2013-05-25 02:42:55 +00006211 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006212 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006213 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006214 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006215 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006216
Andrew Trickef9de2a2013-05-25 02:42:55 +00006217 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006218 }
Chris Lattner888560d2008-01-27 17:42:27 +00006219 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006220
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006221 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006222 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006223 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6224 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006225 return CombineLD;
6226 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006227
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006228 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006229}
6230
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006231SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006232 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006233 return CombineConsecutiveLoads(N, VT);
6234}
6235
Wesley Peck527da1b2010-11-23 03:31:01 +00006236/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006237/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006238/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006239SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006240ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006241 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006242
Chris Lattnere4e64b62006-04-02 02:53:43 +00006243 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006244 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006245
Duncan Sands13237ac2008-06-06 12:08:01 +00006246 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6247 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006248
Chris Lattnere4e64b62006-04-02 02:53:43 +00006249 // If this is a conversion of N elements of one type to N elements of another
6250 // type, convert each element. This handles FP<->INT cases.
6251 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006252 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6253 BV->getValueType(0).getVectorNumElements());
6254
6255 // Due to the FP element handling below calling this routine recursively,
6256 // we can end up with a scalar-to-vector node here.
6257 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006258 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6259 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006260 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006261
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006262 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006263 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006264 SDValue Op = BV->getOperand(i);
6265 // If the vector element type is not legal, the BUILD_VECTOR operands
6266 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006267 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006268 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6269 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006270 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006271 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006272 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006273 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006274 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006275 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006276
Chris Lattnere4e64b62006-04-02 02:53:43 +00006277 // Otherwise, we're growing or shrinking the elements. To avoid having to
6278 // handle annoying details of growing/shrinking FP values, we convert them to
6279 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006280 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006281 // Convert the input float vector to a int vector where the elements are the
6282 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006283 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006284 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006285 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006286 SrcEltVT = IntVT;
6287 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006288
Chris Lattnere4e64b62006-04-02 02:53:43 +00006289 // Now we know the input is an integer vector. If the output is a FP type,
6290 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006291 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006292 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006293 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006294 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006295
Chris Lattnere4e64b62006-04-02 02:53:43 +00006296 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006297 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006298 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006299
Chris Lattnere4e64b62006-04-02 02:53:43 +00006300 // Okay, we know the src/dst types are both integers of differing types.
6301 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006302 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006303 if (SrcBitSize < DstBitSize) {
6304 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006305
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006306 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006307 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006308 i += NumInputsPerOutput) {
6309 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006310 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006311 bool EltIsUndef = true;
6312 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6313 // Shift the previously computed bits over.
6314 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006315 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006316 if (Op.getOpcode() == ISD::UNDEF) continue;
6317 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006318
Jay Foad583abbc2010-12-07 08:25:19 +00006319 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006320 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006321 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006322
Chris Lattnere4e64b62006-04-02 02:53:43 +00006323 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006324 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006325 else
6326 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6327 }
6328
Owen Anderson117c9e82009-08-12 00:36:31 +00006329 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006330 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006331 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006332 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006333
Chris Lattnere4e64b62006-04-02 02:53:43 +00006334 // Finally, this must be the case where we are shrinking elements: each input
6335 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006336 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006337 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006338 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6339 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006340 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006341
Dan Gohmana8665142007-06-25 16:23:39 +00006342 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006343 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6344 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006345 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006346 continue;
6347 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006348
Jay Foad583abbc2010-12-07 08:25:19 +00006349 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6350 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006351
Chris Lattnere4e64b62006-04-02 02:53:43 +00006352 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006353 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006354 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006355 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006356 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006357 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006358 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006359 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006360 }
6361
6362 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006363 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006364 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6365 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006366
Andrew Trickef9de2a2013-05-25 02:42:55 +00006367 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006368 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006369}
6370
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006371SDValue DAGCombiner::visitFADD(SDNode *N) {
6372 SDValue N0 = N->getOperand(0);
6373 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006374 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6375 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006376 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006377
Dan Gohmana8665142007-06-25 16:23:39 +00006378 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006379 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006380 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006381 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006382 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006383
Lang Hamesa33db652012-06-14 20:37:15 +00006384 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006385 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006386 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006387 // canonicalize constant to RHS
6388 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006389 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006390 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006391 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6392 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006393 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006394 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006395 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006396 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006397 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006398 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006399 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006400 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006401 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006402 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006403 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006404
Chris Lattner0199fd62007-01-08 23:04:05 +00006405 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006406 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6407 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6408 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006409 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6410 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006411 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006412
Shuxin Yang93b1f122013-03-25 22:52:29 +00006413 // No FP constant should be created after legalization as Instruction
6414 // Selection pass has hard time in dealing with FP constant.
6415 //
6416 // We don't need test this condition for transformation like following, as
6417 // the DAG being transformed implies it is legal to take FP constant as
6418 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006419 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006420 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006421 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006422 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6423
Owen Andersonb351c8d2012-11-01 02:00:53 +00006424 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006425 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006426 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006427 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006428
6429 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006430 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006431 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006432 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006433
Owen Andersoncc61f872012-08-30 23:35:16 +00006434 // In unsafe math mode, we can fold chains of FADD's of the same value
6435 // into multiplications. This transform is not safe in general because
6436 // we are reducing the number of rounding steps.
6437 if (DAG.getTarget().Options.UnsafeFPMath &&
6438 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6439 !N0CFP && !N1CFP) {
6440 if (N0.getOpcode() == ISD::FMUL) {
6441 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6442 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6443
Stephen Line31f2d22013-06-14 18:17:35 +00006444 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006445 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006446 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006447 SDValue(CFP00, 0),
6448 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006449 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006450 N1, NewCFP);
6451 }
6452
Stephen Line31f2d22013-06-14 18:17:35 +00006453 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006454 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006455 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006456 SDValue(CFP01, 0),
6457 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006458 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006459 N1, NewCFP);
6460 }
6461
Stephen Line31f2d22013-06-14 18:17:35 +00006462 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006463 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6464 N1.getOperand(0) == N1.getOperand(1) &&
6465 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006466 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006467 SDValue(CFP00, 0),
6468 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006469 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006470 N0.getOperand(1), NewCFP);
6471 }
6472
Stephen Line31f2d22013-06-14 18:17:35 +00006473 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006474 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6475 N1.getOperand(0) == N1.getOperand(1) &&
6476 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006477 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006478 SDValue(CFP01, 0),
6479 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006480 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006481 N0.getOperand(0), NewCFP);
6482 }
6483 }
6484
6485 if (N1.getOpcode() == ISD::FMUL) {
6486 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6487 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6488
Stephen Line31f2d22013-06-14 18:17:35 +00006489 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006490 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006491 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006492 SDValue(CFP10, 0),
6493 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006494 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006495 N0, NewCFP);
6496 }
6497
Stephen Line31f2d22013-06-14 18:17:35 +00006498 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006499 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006500 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006501 SDValue(CFP11, 0),
6502 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006503 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006504 N0, NewCFP);
6505 }
6506
Owen Andersoncc61f872012-08-30 23:35:16 +00006507
Stephen Line31f2d22013-06-14 18:17:35 +00006508 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6509 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6510 N0.getOperand(0) == N0.getOperand(1) &&
6511 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006512 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006513 SDValue(CFP10, 0),
6514 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006515 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006516 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006517 }
6518
Stephen Line31f2d22013-06-14 18:17:35 +00006519 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6520 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6521 N0.getOperand(0) == N0.getOperand(1) &&
6522 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006523 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006524 SDValue(CFP11, 0),
6525 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006526 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006527 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006528 }
6529 }
6530
Shuxin Yang93b1f122013-03-25 22:52:29 +00006531 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006532 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006533 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006534 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006535 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006536 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006537 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006538 }
6539
Shuxin Yang93b1f122013-03-25 22:52:29 +00006540 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006541 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006542 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006543 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006544 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006545 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006546 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006547 }
6548
Stephen Lin4e69d012013-06-14 21:33:58 +00006549 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006550 if (AllowNewFpConst &&
6551 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006552 N0.getOperand(0) == N0.getOperand(1) &&
6553 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006554 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006555 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006556 N0.getOperand(0),
6557 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006558 }
6559
Lang Hames39fb1d02012-06-19 22:51:23 +00006560 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006561 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006562 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006563 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6564 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006565
6566 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006567 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006568 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006569 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006570
Michael Liaoec3850122012-09-01 04:09:16 +00006571 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006572 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006573 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006574 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006575 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006576 }
6577
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006578 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006579}
6580
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006581SDValue DAGCombiner::visitFSUB(SDNode *N) {
6582 SDValue N0 = N->getOperand(0);
6583 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006584 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6585 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006586 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006587 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006588
Dan Gohmana8665142007-06-25 16:23:39 +00006589 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006590 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006591 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006592 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006593 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006594
Nate Begeman418c6e42005-10-18 00:28:13 +00006595 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006596 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006597 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006598 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006599 if (DAG.getTarget().Options.UnsafeFPMath &&
6600 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006601 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006602 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006603 if (DAG.getTarget().Options.UnsafeFPMath &&
6604 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006605 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006606 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006607 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006608 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006609 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006610 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006611 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006612 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006613 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006614
Bill Wendlingdf170db2012-03-15 05:12:00 +00006615 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006616 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006617 // (fsub x, (fadd x, y)) -> (fneg y) &
6618 // (fsub x, (fadd y, x)) -> (fneg y)
6619 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006620 if (N0 == N1)
6621 return DAG.getConstantFP(0.0f, VT);
6622
Bill Wendlingdf170db2012-03-15 05:12:00 +00006623 if (N1.getOpcode() == ISD::FADD) {
6624 SDValue N10 = N1->getOperand(0);
6625 SDValue N11 = N1->getOperand(1);
6626
6627 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6628 &DAG.getTarget().Options))
6629 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006630
Stephen Lin8e8424e2013-07-09 00:44:49 +00006631 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6632 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006633 return GetNegatedExpression(N10, DAG, LegalOperations);
6634 }
6635 }
6636
Lang Hames39fb1d02012-06-19 22:51:23 +00006637 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006638 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006639 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006640 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6641 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006642
6643 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006644 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006645 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006646 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006647 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006648
6649 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6650 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006651 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006652 return DAG.getNode(ISD::FMA, dl, VT,
6653 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006654 N1.getOperand(0)),
6655 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006656
Stephen Lin8e8424e2013-07-09 00:44:49 +00006657 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006658 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006659 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6660 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6661 SDValue N00 = N0.getOperand(0).getOperand(0);
6662 SDValue N01 = N0.getOperand(0).getOperand(1);
6663 return DAG.getNode(ISD::FMA, dl, VT,
6664 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6665 DAG.getNode(ISD::FNEG, dl, VT, N1));
6666 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006667 }
6668
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006669 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006670}
6671
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006672SDValue DAGCombiner::visitFMUL(SDNode *N) {
6673 SDValue N0 = N->getOperand(0);
6674 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006675 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6676 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006677 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006678 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006679
Dan Gohmana8665142007-06-25 16:23:39 +00006680 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006681 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006682 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006683 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006684 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006685
Nate Begemanec48a1b2005-10-17 20:40:11 +00006686 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006687 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006688 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006689 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006690 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006691 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006692 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006693 if (DAG.getTarget().Options.UnsafeFPMath &&
6694 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006695 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006696 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006697 if (DAG.getTarget().Options.UnsafeFPMath &&
6698 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006699 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006700 // fold (fmul A, 1.0) -> A
6701 if (N1CFP && N1CFP->isExactlyValue(1.0))
6702 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006703 // fold (fmul X, 2.0) -> (fadd X, X)
6704 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006705 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006706 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006707 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006708 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006709 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006710
Bill Wendling3dc5d242009-01-30 22:57:07 +00006711 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006712 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006713 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006714 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006715 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006716 // Both can be negated for free, check to see if at least one is cheaper
6717 // negated.
6718 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006719 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006720 GetNegatedExpression(N0, DAG, LegalOperations),
6721 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006722 }
6723 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006724
Chris Lattner0199fd62007-01-08 23:04:05 +00006725 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006726 if (DAG.getTarget().Options.UnsafeFPMath &&
6727 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006728 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006729 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6730 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006731 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006732
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006733 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006734}
6735
Owen Anderson41b06652012-05-02 22:17:40 +00006736SDValue DAGCombiner::visitFMA(SDNode *N) {
6737 SDValue N0 = N->getOperand(0);
6738 SDValue N1 = N->getOperand(1);
6739 SDValue N2 = N->getOperand(2);
6740 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6741 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6742 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006743 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006744
Owen Andersonb351c8d2012-11-01 02:00:53 +00006745 if (DAG.getTarget().Options.UnsafeFPMath) {
6746 if (N0CFP && N0CFP->isZero())
6747 return N2;
6748 if (N1CFP && N1CFP->isZero())
6749 return N2;
6750 }
Owen Anderson41b06652012-05-02 22:17:40 +00006751 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006752 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006753 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006754 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006755
Owen Andersonc7aaf522012-05-30 18:50:39 +00006756 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006757 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006758 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006759
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006760 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6761 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6762 N2.getOpcode() == ISD::FMUL &&
6763 N0 == N2.getOperand(0) &&
6764 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6765 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6766 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6767 }
6768
6769
6770 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6771 if (DAG.getTarget().Options.UnsafeFPMath &&
6772 N0.getOpcode() == ISD::FMUL && N1CFP &&
6773 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6774 return DAG.getNode(ISD::FMA, dl, VT,
6775 N0.getOperand(0),
6776 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6777 N2);
6778 }
6779
6780 // (fma x, 1, y) -> (fadd x, y)
6781 // (fma x, -1, y) -> (fadd (fneg x), y)
6782 if (N1CFP) {
6783 if (N1CFP->isExactlyValue(1.0))
6784 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6785
6786 if (N1CFP->isExactlyValue(-1.0) &&
6787 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6788 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6789 AddToWorkList(RHSNeg.getNode());
6790 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6791 }
6792 }
6793
6794 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006795 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6796 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006797 DAG.getNode(ISD::FADD, dl, VT,
6798 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006799
6800 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6801 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006802 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6803 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006804 DAG.getNode(ISD::FADD, dl, VT,
6805 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006806
6807
Owen Anderson41b06652012-05-02 22:17:40 +00006808 return SDValue();
6809}
6810
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006811SDValue DAGCombiner::visitFDIV(SDNode *N) {
6812 SDValue N0 = N->getOperand(0);
6813 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006814 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6815 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006816 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006817 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006818
Dan Gohmana8665142007-06-25 16:23:39 +00006819 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006820 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006821 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006822 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006823 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006824
Nate Begeman569c4392006-01-18 22:35:16 +00006825 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006826 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006827 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006828
Duncan Sands2f1dc382012-04-08 18:08:12 +00006829 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006830 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006831 // Compute the reciprocal 1.0 / c2.
6832 APFloat N1APF = N1CFP->getValueAPF();
6833 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6834 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006835 // Only do the transform if the reciprocal is a legal fp immediate that
6836 // isn't too nasty (eg NaN, denormal, ...).
6837 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006838 (!LegalOperations ||
6839 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6840 // backend)... we should handle this gracefully after Legalize.
6841 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6842 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6843 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006844 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006845 DAG.getConstantFP(Recip, VT));
6846 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006847
Bill Wendling3dc5d242009-01-30 22:57:07 +00006848 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006849 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006850 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006851 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006852 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006853 // Both can be negated for free, check to see if at least one is cheaper
6854 // negated.
6855 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006856 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006857 GetNegatedExpression(N0, DAG, LegalOperations),
6858 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006859 }
6860 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006861
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006862 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006863}
6864
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006865SDValue DAGCombiner::visitFREM(SDNode *N) {
6866 SDValue N0 = N->getOperand(0);
6867 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006868 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6869 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006870 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006871
Nate Begeman569c4392006-01-18 22:35:16 +00006872 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006873 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006874 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006875
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006876 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006877}
6878
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006879SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6880 SDValue N0 = N->getOperand(0);
6881 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006882 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6883 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006884 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006885
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006886 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006887 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006888
Chris Lattner3bc40502006-03-05 05:30:57 +00006889 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006890 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006891 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6892 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006893 if (!V.isNegative()) {
6894 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006895 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006896 } else {
6897 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006898 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6899 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006900 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006901 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006902
Chris Lattner3bc40502006-03-05 05:30:57 +00006903 // copysign(fabs(x), y) -> copysign(x, y)
6904 // copysign(fneg(x), y) -> copysign(x, y)
6905 // copysign(copysign(x,z), y) -> copysign(x, y)
6906 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6907 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006908 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006909 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006910
6911 // copysign(x, abs(y)) -> abs(x)
6912 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006913 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006914
Chris Lattner3bc40502006-03-05 05:30:57 +00006915 // copysign(x, copysign(y,z)) -> copysign(x, z)
6916 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006917 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006918 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006919
Chris Lattner3bc40502006-03-05 05:30:57 +00006920 // copysign(x, fp_extend(y)) -> copysign(x, y)
6921 // copysign(x, fp_round(y)) -> copysign(x, y)
6922 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006923 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006924 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006925
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006926 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006927}
6928
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006929SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6930 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006932 EVT VT = N->getValueType(0);
6933 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006934
Nate Begeman21158fc2005-09-01 00:19:25 +00006935 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006936 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006937 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006938 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006939 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006940 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006941
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006942 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6943 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006944 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6945 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006946 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006947 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006948 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006949 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006950
Alp Tokercb402912014-01-24 17:20:08 +00006951 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006952 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6953 // having to say they don't support SELECT_CC on every type the DAG knows
6954 // about, since there is no way to mark an opcode illegal at all value types
6955 // (See also visitSELECT)
6956 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6957 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6958 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6959 !VT.isVector() &&
6960 (!LegalOperations ||
6961 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6962 SDValue Ops[] =
6963 { N0.getOperand(0), N0.getOperand(1),
6964 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6965 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006966 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006967 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006968
Nadav Rotem90560762012-07-23 07:59:50 +00006969 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6970 // (select_cc x, y, 1.0, 0.0,, cc)
6971 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6972 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6973 (!LegalOperations ||
6974 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6975 SDValue Ops[] =
6976 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6977 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6978 N0.getOperand(0).getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006979 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006980 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006981 }
6982
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006983 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006984}
6985
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006986SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6987 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006988 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006989 EVT VT = N->getValueType(0);
6990 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00006991
Nate Begeman21158fc2005-09-01 00:19:25 +00006992 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006993 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006994 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006995 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006996 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006997 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006998
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006999 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7000 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007001 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7002 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007003 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007004 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007005 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007006 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007007
Alp Tokercb402912014-01-24 17:20:08 +00007008 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00007009 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7010 // having to say they don't support SELECT_CC on every type the DAG knows
7011 // about, since there is no way to mark an opcode illegal at all value types
7012 // (See also visitSELECT)
7013 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7014 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007015
Nadav Rotem90560762012-07-23 07:59:50 +00007016 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7017 (!LegalOperations ||
7018 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7019 SDValue Ops[] =
7020 { N0.getOperand(0), N0.getOperand(1),
7021 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7022 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00007023 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00007024 }
7025 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007026
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007027 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007028}
7029
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007030SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7031 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007032 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007033 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007034
Nate Begeman21158fc2005-09-01 00:19:25 +00007035 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007036 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007037 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007038
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007039 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007040}
7041
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007042SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7043 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007044 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007045 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007046
Nate Begeman21158fc2005-09-01 00:19:25 +00007047 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007048 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007049 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007050
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007051 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007052}
7053
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007054SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7055 SDValue N0 = N->getOperand(0);
7056 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007057 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007058 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007059
Nate Begeman21158fc2005-09-01 00:19:25 +00007060 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007061 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007062 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007063
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007064 // fold (fp_round (fp_extend x)) -> x
7065 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7066 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007067
Chris Lattner0feb1b02008-01-24 06:45:35 +00007068 // fold (fp_round (fp_round x)) -> (fp_round x)
7069 if (N0.getOpcode() == ISD::FP_ROUND) {
7070 // This is a value preserving truncation if both round's are.
7071 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007072 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007073 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007074 DAG.getIntPtrConstant(IsTrunc));
7075 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007076
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007077 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007078 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007079 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007080 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007081 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007082 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007083 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007084 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007085
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007086 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007087}
7088
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007089SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7090 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007091 EVT VT = N->getValueType(0);
7092 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007093 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007094
Nate Begeman21158fc2005-09-01 00:19:25 +00007095 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007096 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007097 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007098 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007099 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007100
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007101 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007102}
7103
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007104SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7105 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007106 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007107 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007108
Chris Lattner5919b482007-12-29 06:55:23 +00007109 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007110 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007111 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007112 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007113
Nate Begeman21158fc2005-09-01 00:19:25 +00007114 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007115 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007116 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007117
7118 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7119 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007120 if (N0.getOpcode() == ISD::FP_ROUND
7121 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007122 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007123 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007124 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007125 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007126 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007127 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007128 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007129
Chris Lattner72733e52008-01-17 07:00:52 +00007130 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007131 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007132 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007133 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007134 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007135 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007136 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007137 LN0->getBasePtr(), N0.getValueType(),
7138 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007139 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007140 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007141 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007142 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007143 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007145 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007146
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007147 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007148}
7149
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007150SDValue DAGCombiner::visitFNEG(SDNode *N) {
7151 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007152 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007153
Craig Topper82384612012-09-11 01:45:21 +00007154 if (VT.isVector()) {
7155 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7156 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007157 }
7158
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007159 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7160 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007161 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007162
Chris Lattner888560d2008-01-27 17:42:27 +00007163 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7164 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007165 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007166 !VT.isVector() &&
7167 N0.getNode()->hasOneUse() &&
7168 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007169 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007170 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007171 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007172 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007173 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007174 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007175 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007176 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007177 }
7178 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007179
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007180 // (fneg (fmul c, x)) -> (fmul -c, x)
7181 if (N0.getOpcode() == ISD::FMUL) {
7182 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Lin8e8424e2013-07-09 00:44:49 +00007183 if (CFP1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007184 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007185 N0.getOperand(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007186 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007187 N0.getOperand(1)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007188 }
7189
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007190 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007191}
7192
Owen Andersona40319b2012-08-13 23:32:49 +00007193SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7194 SDValue N0 = N->getOperand(0);
7195 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7196 EVT VT = N->getValueType(0);
7197
7198 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007199 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007200 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007201
7202 return SDValue();
7203}
7204
7205SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7206 SDValue N0 = N->getOperand(0);
7207 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7208 EVT VT = N->getValueType(0);
7209
7210 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007211 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007212 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007213
7214 return SDValue();
7215}
7216
7217SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7218 SDValue N0 = N->getOperand(0);
7219 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7220 EVT VT = N->getValueType(0);
7221
7222 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007223 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007224 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007225
7226 return SDValue();
7227}
7228
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007229SDValue DAGCombiner::visitFABS(SDNode *N) {
7230 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007231 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007232 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007233
Craig Topper82384612012-09-11 01:45:21 +00007234 if (VT.isVector()) {
7235 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7236 if (FoldedVOp.getNode()) return FoldedVOp;
7237 }
7238
Nate Begeman21158fc2005-09-01 00:19:25 +00007239 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007240 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007241 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007242 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007243 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007244 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007245 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007246 // fold (fabs (fcopysign x, y)) -> (fabs x)
7247 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007248 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007249
Chris Lattner888560d2008-01-27 17:42:27 +00007250 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7251 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007252 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007253 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007254 N0.getOperand(0).getValueType().isInteger() &&
7255 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007256 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007257 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007258 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007259 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007260 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007261 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007262 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007263 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007264 }
7265 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007266
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007267 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007268}
7269
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007270SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7271 SDValue Chain = N->getOperand(0);
7272 SDValue N1 = N->getOperand(1);
7273 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007274
Dan Gohman82e80012009-11-17 00:47:23 +00007275 // If N is a constant we could fold this into a fallthrough or unconditional
7276 // branch. However that doesn't happen very often in normal code, because
7277 // Instcombine/SimplifyCFG should have handled the available opportunities.
7278 // If we did this folding here, it would be necessary to update the
7279 // MachineBasicBlock CFG, which is awkward.
7280
Nate Begeman7e7f4392006-02-01 07:19:44 +00007281 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7282 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007283 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007284 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7285 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007286 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007287 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007288 N1.getOperand(0), N1.getOperand(1), N2);
7289 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007290
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007291 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7292 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7293 (N1.getOperand(0).hasOneUse() &&
7294 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007295 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007296 if (N1.getOpcode() == ISD::TRUNCATE) {
7297 // Look pass the truncate.
7298 Trunc = N1.getNode();
7299 N1 = N1.getOperand(0);
7300 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007301
Bill Wendlingaa28be62009-03-26 06:14:09 +00007302 // Match this pattern so that we can generate simpler code:
7303 //
7304 // %a = ...
7305 // %b = and i32 %a, 2
7306 // %c = srl i32 %b, 1
7307 // brcond i32 %c ...
7308 //
7309 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007310 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007311 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007312 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007313 // %c = setcc eq %b, 0
7314 // brcond %c ...
7315 //
7316 // This applies only when the AND constant value has one bit set and the
7317 // SRL constant is equal to the log2 of the AND constant. The back-end is
7318 // smart enough to convert the result into a TEST/JMP sequence.
7319 SDValue Op0 = N1.getOperand(0);
7320 SDValue Op1 = N1.getOperand(1);
7321
7322 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007323 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007324 SDValue AndOp1 = Op0.getOperand(1);
7325
7326 if (AndOp1.getOpcode() == ISD::Constant) {
7327 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7328
7329 if (AndConst.isPowerOf2() &&
7330 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7331 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007332 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007333 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007334 Op0, DAG.getConstant(0, Op0.getValueType()),
7335 ISD::SETNE);
7336
Andrew Trickef9de2a2013-05-25 02:42:55 +00007337 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007338 MVT::Other, Chain, SetCC, N2);
7339 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7340 // will convert it back to (X & C1) >> C2.
7341 CombineTo(N, NewBRCond, false);
7342 // Truncate is dead.
7343 if (Trunc) {
7344 removeFromWorkList(Trunc);
7345 DAG.DeleteNode(Trunc);
7346 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007347 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007348 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007349 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007350 removeFromWorkList(N1.getNode());
7351 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007352 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007353 }
7354 }
7355 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007356
7357 if (Trunc)
7358 // Restore N1 if the above transformation doesn't match.
7359 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007360 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007361
Evan Cheng228c31f2010-02-27 07:36:59 +00007362 // Transform br(xor(x, y)) -> br(x != y)
7363 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7364 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7365 SDNode *TheXor = N1.getNode();
7366 SDValue Op0 = TheXor->getOperand(0);
7367 SDValue Op1 = TheXor->getOperand(1);
7368 if (Op0.getOpcode() == Op1.getOpcode()) {
7369 // Avoid missing important xor optimizations.
7370 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007371 if (Tmp.getNode()) {
7372 if (Tmp.getNode() != TheXor) {
7373 DEBUG(dbgs() << "\nReplacing.8 ";
7374 TheXor->dump(&DAG);
7375 dbgs() << "\nWith: ";
7376 Tmp.getNode()->dump(&DAG);
7377 dbgs() << '\n');
7378 WorkListRemover DeadNodes(*this);
7379 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7380 removeFromWorkList(TheXor);
7381 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007382 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007383 MVT::Other, Chain, Tmp, N2);
7384 }
7385
Benjamin Kramer93354432013-03-30 21:28:18 +00007386 // visitXOR has changed XOR's operands or replaced the XOR completely,
7387 // bail out.
7388 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007389 }
7390 }
7391
7392 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7393 bool Equal = false;
7394 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7395 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7396 Op0.getOpcode() == ISD::XOR) {
7397 TheXor = Op0.getNode();
7398 Equal = true;
7399 }
7400
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007401 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007402 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007403 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007404 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007405 SetCCVT,
7406 Op0, Op1,
7407 Equal ? ISD::SETEQ : ISD::SETNE);
7408 // Replace the uses of XOR with SETCC
7409 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007410 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007411 removeFromWorkList(N1.getNode());
7412 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007413 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007414 MVT::Other, Chain, SetCC, N2);
7415 }
7416 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007417
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007418 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007419}
7420
Chris Lattnera49e16f2005-10-05 06:47:48 +00007421// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7422//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007423SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007424 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007425 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007426
Dan Gohman82e80012009-11-17 00:47:23 +00007427 // If N is a constant we could fold this into a fallthrough or unconditional
7428 // branch. However that doesn't happen very often in normal code, because
7429 // Instcombine/SimplifyCFG should have handled the available opportunities.
7430 // If we did this folding here, it would be necessary to update the
7431 // MachineBasicBlock CFG, which is awkward.
7432
Duncan Sands93b66092008-06-09 11:32:28 +00007433 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007434 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007435 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007436 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007437 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007438
Nate Begemanbd7df032005-10-05 21:43:42 +00007439 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007440 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007441 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007442 N->getOperand(0), Simp.getOperand(2),
7443 Simp.getOperand(0), Simp.getOperand(1),
7444 N->getOperand(4));
7445
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007446 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007447}
7448
Evan Chengfa832632012-01-13 01:37:24 +00007449/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7450/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007451/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007452static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7453 SelectionDAG &DAG,
7454 const TargetLowering &TLI) {
7455 EVT VT;
7456 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7457 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7458 return false;
7459 VT = Use->getValueType(0);
7460 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7461 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7462 return false;
7463 VT = ST->getValue().getValueType();
7464 } else
7465 return false;
7466
Chandler Carruth95f83e02013-01-07 15:14:13 +00007467 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007468 if (N->getOpcode() == ISD::ADD) {
7469 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7470 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007471 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007472 AM.BaseOffs = Offset->getSExtValue();
7473 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007474 // [reg +/- reg]
7475 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007476 } else if (N->getOpcode() == ISD::SUB) {
7477 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7478 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007479 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007480 AM.BaseOffs = -Offset->getSExtValue();
7481 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007482 // [reg +/- reg]
7483 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007484 } else
7485 return false;
7486
7487 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7488}
7489
Duncan Sands075293f2008-06-15 20:12:31 +00007490/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7491/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007492/// and it has other uses besides the load / store. After the
7493/// transformation, the new indexed load / store has effectively folded
7494/// the add / subtract in and all of its other uses are redirected to the
7495/// new load / store.
7496bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007497 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007498 return false;
7499
7500 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007501 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007502 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007503 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007504 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007505 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007506 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007507 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007508 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7509 return false;
7510 Ptr = LD->getBasePtr();
7511 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007512 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007513 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007514 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007515 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7516 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7517 return false;
7518 Ptr = ST->getBasePtr();
7519 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007520 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007521 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007522 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007523
Chris Lattnereabc15c2006-11-11 00:56:29 +00007524 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7525 // out. There is no reason to make this a preinc/predec.
7526 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007527 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007528 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007529
Chris Lattnereabc15c2006-11-11 00:56:29 +00007530 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007531 SDValue BasePtr;
7532 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007533 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7534 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7535 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007536
7537 // Backends without true r+i pre-indexed forms may need to pass a
7538 // constant base with a variable offset so that constant coercion
7539 // will work with the patterns in canonical form.
7540 bool Swapped = false;
7541 if (isa<ConstantSDNode>(BasePtr)) {
7542 std::swap(BasePtr, Offset);
7543 Swapped = true;
7544 }
7545
Evan Cheng044a0a82007-05-03 23:52:19 +00007546 // Don't create a indexed load / store with zero offset.
7547 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007548 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007549 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007550
Chris Lattnera0a80032006-11-11 01:00:15 +00007551 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007552 // 1) The new base ptr is a frame index.
7553 // 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 +00007554 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007555 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007556 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007557 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007558
Chris Lattnera0a80032006-11-11 01:00:15 +00007559 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7560 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007561 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007562 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007563
Chris Lattnera0a80032006-11-11 01:00:15 +00007564 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007565 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007566 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007567 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007568 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007569 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007570
Hal Finkel25819052013-02-08 21:35:47 +00007571 // If the offset is a constant, there may be other adds of constants that
7572 // can be folded with this one. We should do this to avoid having to keep
7573 // a copy of the original base pointer.
7574 SmallVector<SDNode *, 16> OtherUses;
7575 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007576 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007577 if (Use == Ptr.getNode())
7578 continue;
7579
7580 if (Use->isPredecessorOf(N))
7581 continue;
7582
7583 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7584 OtherUses.clear();
7585 break;
7586 }
7587
7588 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7589 if (Op1.getNode() == BasePtr.getNode())
7590 std::swap(Op0, Op1);
7591 assert(Op0.getNode() == BasePtr.getNode() &&
7592 "Use of ADD/SUB but not an operand");
7593
7594 if (!isa<ConstantSDNode>(Op1)) {
7595 OtherUses.clear();
7596 break;
7597 }
7598
7599 // FIXME: In some cases, we can be smarter about this.
7600 if (Op1.getValueType() != Offset.getValueType()) {
7601 OtherUses.clear();
7602 break;
7603 }
7604
7605 OtherUses.push_back(Use);
7606 }
7607
7608 if (Swapped)
7609 std::swap(BasePtr, Offset);
7610
Evan Chenga4d187b2007-05-24 02:35:39 +00007611 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007612 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007613
7614 // Caches for hasPredecessorHelper
7615 SmallPtrSet<const SDNode *, 32> Visited;
7616 SmallVector<const SDNode *, 16> Worklist;
7617
Jim Grosbache8160032014-04-11 01:13:13 +00007618 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007619 if (Use == N)
7620 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007621 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007622 return false;
7623
Evan Chengfa832632012-01-13 01:37:24 +00007624 // If Ptr may be folded in addressing mode of other use, then it's
7625 // not profitable to do this transformation.
7626 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007627 RealUse = true;
7628 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007629
Chris Lattnereabc15c2006-11-11 00:56:29 +00007630 if (!RealUse)
7631 return false;
7632
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007633 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007634 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007635 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007636 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007637 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007638 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007639 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007640 ++PreIndexedNodes;
7641 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007642 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007643 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007644 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007645 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007646 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007647 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007648 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007649 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007651 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007652 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007653 }
7654
Chris Lattnereabc15c2006-11-11 00:56:29 +00007655 // Finally, since the node is now dead, remove it from the graph.
7656 DAG.DeleteNode(N);
7657
Hal Finkel25819052013-02-08 21:35:47 +00007658 if (Swapped)
7659 std::swap(BasePtr, Offset);
7660
7661 // Replace other uses of BasePtr that can be updated to use Ptr
7662 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7663 unsigned OffsetIdx = 1;
7664 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7665 OffsetIdx = 0;
7666 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7667 BasePtr.getNode() && "Expected BasePtr operand");
7668
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007669 // We need to replace ptr0 in the following expression:
7670 // x0 * offset0 + y0 * ptr0 = t0
7671 // knowing that
7672 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007673 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007674 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7675 // indexed load/store and the expresion that needs to be re-written.
7676 //
7677 // Therefore, we have:
7678 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007679
7680 ConstantSDNode *CN =
7681 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007682 int X0, X1, Y0, Y1;
7683 APInt Offset0 = CN->getAPIntValue();
7684 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007685
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007686 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7687 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7688 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7689 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007690
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007691 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7692
7693 APInt CNV = Offset0;
7694 if (X0 < 0) CNV = -CNV;
7695 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7696 else CNV = CNV - Offset1;
7697
7698 // We can now generate the new expression.
7699 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7700 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7701
7702 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007703 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007704 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7705 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7706 removeFromWorkList(OtherUses[i]);
7707 DAG.DeleteNode(OtherUses[i]);
7708 }
7709
Chris Lattnereabc15c2006-11-11 00:56:29 +00007710 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007711 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007712 removeFromWorkList(Ptr.getNode());
7713 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007714
7715 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007716}
7717
Duncan Sands075293f2008-06-15 20:12:31 +00007718/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007719/// add / sub of the base pointer node into a post-indexed load / store.
7720/// The transformation folded the add / subtract into the new indexed
7721/// load / store effectively and all of its uses are redirected to the
7722/// new load / store.
7723bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007724 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007725 return false;
7726
7727 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007728 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007729 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007730 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007731 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007732 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007733 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007734 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7735 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7736 return false;
7737 Ptr = LD->getBasePtr();
7738 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007739 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007740 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007741 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007742 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7743 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7744 return false;
7745 Ptr = ST->getBasePtr();
7746 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007747 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007748 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007749 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007750
Gabor Greiff304a7a2008-08-28 21:40:38 +00007751 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007752 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007753
Jim Grosbache8160032014-04-11 01:13:13 +00007754 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007755 if (Op == N ||
7756 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7757 continue;
7758
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007759 SDValue BasePtr;
7760 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007761 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7762 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007763 // Don't create a indexed load / store with zero offset.
7764 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007765 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007766 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007767
Chris Lattnereabc15c2006-11-11 00:56:29 +00007768 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007769 // 1) All uses are load / store ops that use it as base ptr (and
7770 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007771 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7772 // nor a successor of N. Otherwise, if Op is folded that would
7773 // create a cycle.
7774
Evan Chengcfc05132009-05-06 18:25:01 +00007775 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7776 continue;
7777
Chris Lattnereabc15c2006-11-11 00:56:29 +00007778 // Check for #1.
7779 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007780 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007781 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007782 continue;
7783
Chris Lattnereabc15c2006-11-11 00:56:29 +00007784 // If all the uses are load / store addresses, then don't do the
7785 // transformation.
7786 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7787 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007788 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007789 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007790 RealUse = true;
7791 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007792
Chris Lattnereabc15c2006-11-11 00:56:29 +00007793 if (!RealUse) {
7794 TryNext = true;
7795 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007796 }
7797 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007798 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007799
Chris Lattnereabc15c2006-11-11 00:56:29 +00007800 if (TryNext)
7801 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007802
Chris Lattnereabc15c2006-11-11 00:56:29 +00007803 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007804 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007805 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007806 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007807 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007808 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007809 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007810 ++PostIndexedNodes;
7811 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007812 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007813 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007814 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007815 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007816 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007817 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007818 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007819 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7820 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007821 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007822 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007823 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007824
Chris Lattnereabc15c2006-11-11 00:56:29 +00007825 // Finally, since the node is now dead, remove it from the graph.
7826 DAG.DeleteNode(N);
7827
7828 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007829 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007830 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007831 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007832 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007833 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007834 }
7835 }
7836 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007837
Chris Lattnerffad2162006-11-11 00:39:41 +00007838 return false;
7839}
7840
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007841SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007842 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007843 SDValue Chain = LD->getChain();
7844 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007845
Evan Chenga684cd22007-05-01 00:38:21 +00007846 // If load is not volatile and there are no uses of the loaded value (and
7847 // the updated indexed value in case of indexed loads), change uses of the
7848 // chain value into uses of the chain input (i.e. delete the dead load).
7849 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007850 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007851 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007852 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007853 // It's not safe to use the two value CombineTo variant here. e.g.
7854 // v1, chain2 = load chain1, loc
7855 // v2, chain3 = load chain2, loc
7856 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007857 // Now we replace use of chain2 with chain1. This makes the second load
7858 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007859 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007860 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007861 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007862 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007863 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007864 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007865 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007866
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007867 if (N->use_empty()) {
7868 removeFromWorkList(N);
7869 DAG.DeleteNode(N);
7870 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007871
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007872 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007873 }
Evan Chengb68343c2007-05-01 08:53:39 +00007874 } else {
7875 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007876 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper0515cd42012-01-07 18:31:09 +00007877 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007878 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007879 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007880 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007881 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007882 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007883 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007884 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007885 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007886 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007887 DAG.getUNDEF(N->getValueType(1)));
7888 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007889 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007890 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007892 }
Evan Chenga684cd22007-05-01 00:38:21 +00007893 }
7894 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007895
Chris Lattnere260ed82005-10-10 22:04:48 +00007896 // If this load is directly stored, replace the load value with the stored
7897 // value.
7898 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007899 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007900 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007901 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007902 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7903 if (PrevST->getBasePtr() == Ptr &&
7904 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007905 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007906 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007907 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007908
Evan Cheng43cd9e32010-04-01 06:04:33 +00007909 // Try to infer better alignment information than the load already has.
7910 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007911 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007912 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7913 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007914 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007915 LD->getValueType(0),
7916 Chain, Ptr, LD->getPointerInfo(),
7917 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007918 LD->isVolatile(), LD->isNonTemporal(), Align,
7919 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007920 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7921 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007922 }
7923 }
7924
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007925 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7926 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00007927#ifndef NDEBUG
7928 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7929 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7930 UseAA = false;
7931#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00007932 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007933 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007934 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007935
Jim Laskey708d0db2006-10-04 16:53:27 +00007936 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007937 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007938 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007939
Jim Laskeyd07be232006-09-25 16:29:54 +00007940 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007941 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007942 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007943 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007944 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007945 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007946 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007947 BetterChain, Ptr, LD->getMemoryVT(),
7948 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007949 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007950
Jim Laskey708d0db2006-10-04 16:53:27 +00007951 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007952 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007953 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007954
Nate Begeman879d8f12009-09-15 00:18:30 +00007955 // Make sure the new and old chains are cleaned up.
7956 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007957
Jim Laskeydcf983c2006-10-13 23:32:28 +00007958 // Replace uses with load result and token factor. Don't add users
7959 // to work list.
7960 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00007961 }
7962 }
7963
Evan Cheng357017f2006-11-03 03:06:21 +00007964 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00007965 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007966 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00007967
Quentin Colombetde0e0622013-10-11 18:29:42 +00007968 // Try to slice up N to more direct loads if the slices are mapped to
7969 // different register banks or pairing can take place.
7970 if (SliceUpLoad(N))
7971 return SDValue(N, 0);
7972
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007973 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00007974}
7975
Quentin Colombetde0e0622013-10-11 18:29:42 +00007976namespace {
7977/// \brief Helper structure used to slice a load in smaller loads.
7978/// Basically a slice is obtained from the following sequence:
7979/// Origin = load Ty1, Base
7980/// Shift = srl Ty1 Origin, CstTy Amount
7981/// Inst = trunc Shift to Ty2
7982///
7983/// Then, it will be rewriten into:
7984/// Slice = load SliceTy, Base + SliceOffset
7985/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7986///
7987/// SliceTy is deduced from the number of bits that are actually used to
7988/// build Inst.
7989struct LoadedSlice {
7990 /// \brief Helper structure used to compute the cost of a slice.
7991 struct Cost {
7992 /// Are we optimizing for code size.
7993 bool ForCodeSize;
7994 /// Various cost.
7995 unsigned Loads;
7996 unsigned Truncates;
7997 unsigned CrossRegisterBanksCopies;
7998 unsigned ZExts;
7999 unsigned Shift;
8000
8001 Cost(bool ForCodeSize = false)
8002 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8003 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8004
8005 /// \brief Get the cost of one isolated slice.
8006 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8007 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8008 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8009 EVT TruncType = LS.Inst->getValueType(0);
8010 EVT LoadedType = LS.getLoadedType();
8011 if (TruncType != LoadedType &&
8012 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8013 ZExts = 1;
8014 }
8015
8016 /// \brief Account for slicing gain in the current cost.
8017 /// Slicing provide a few gains like removing a shift or a
8018 /// truncate. This method allows to grow the cost of the original
8019 /// load with the gain from this slice.
8020 void addSliceGain(const LoadedSlice &LS) {
8021 // Each slice saves a truncate.
8022 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8023 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8024 LS.Inst->getOperand(0).getValueType()))
8025 ++Truncates;
8026 // If there is a shift amount, this slice gets rid of it.
8027 if (LS.Shift)
8028 ++Shift;
8029 // If this slice can merge a cross register bank copy, account for it.
8030 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8031 ++CrossRegisterBanksCopies;
8032 }
8033
8034 Cost &operator+=(const Cost &RHS) {
8035 Loads += RHS.Loads;
8036 Truncates += RHS.Truncates;
8037 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8038 ZExts += RHS.ZExts;
8039 Shift += RHS.Shift;
8040 return *this;
8041 }
8042
8043 bool operator==(const Cost &RHS) const {
8044 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8045 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8046 ZExts == RHS.ZExts && Shift == RHS.Shift;
8047 }
8048
8049 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8050
8051 bool operator<(const Cost &RHS) const {
8052 // Assume cross register banks copies are as expensive as loads.
8053 // FIXME: Do we want some more target hooks?
8054 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8055 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8056 // Unless we are optimizing for code size, consider the
8057 // expensive operation first.
8058 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8059 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8060 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8061 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8062 }
8063
8064 bool operator>(const Cost &RHS) const { return RHS < *this; }
8065
8066 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8067
8068 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8069 };
8070 // The last instruction that represent the slice. This should be a
8071 // truncate instruction.
8072 SDNode *Inst;
8073 // The original load instruction.
8074 LoadSDNode *Origin;
8075 // The right shift amount in bits from the original load.
8076 unsigned Shift;
8077 // The DAG from which Origin came from.
8078 // This is used to get some contextual information about legal types, etc.
8079 SelectionDAG *DAG;
8080
Craig Topperc0196b12014-04-14 00:51:57 +00008081 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8082 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008083 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8084
8085 LoadedSlice(const LoadedSlice &LS)
8086 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8087
8088 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8089 /// \return Result is \p BitWidth and has used bits set to 1 and
8090 /// not used bits set to 0.
8091 APInt getUsedBits() const {
8092 // Reproduce the trunc(lshr) sequence:
8093 // - Start from the truncated value.
8094 // - Zero extend to the desired bit width.
8095 // - Shift left.
8096 assert(Origin && "No original load to compare against.");
8097 unsigned BitWidth = Origin->getValueSizeInBits(0);
8098 assert(Inst && "This slice is not bound to an instruction");
8099 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8100 "Extracted slice is bigger than the whole type!");
8101 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8102 UsedBits.setAllBits();
8103 UsedBits = UsedBits.zext(BitWidth);
8104 UsedBits <<= Shift;
8105 return UsedBits;
8106 }
8107
8108 /// \brief Get the size of the slice to be loaded in bytes.
8109 unsigned getLoadedSize() const {
8110 unsigned SliceSize = getUsedBits().countPopulation();
8111 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8112 return SliceSize / 8;
8113 }
8114
8115 /// \brief Get the type that will be loaded for this slice.
8116 /// Note: This may not be the final type for the slice.
8117 EVT getLoadedType() const {
8118 assert(DAG && "Missing context");
8119 LLVMContext &Ctxt = *DAG->getContext();
8120 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8121 }
8122
8123 /// \brief Get the alignment of the load used for this slice.
8124 unsigned getAlignment() const {
8125 unsigned Alignment = Origin->getAlignment();
8126 unsigned Offset = getOffsetFromBase();
8127 if (Offset != 0)
8128 Alignment = MinAlign(Alignment, Alignment + Offset);
8129 return Alignment;
8130 }
8131
8132 /// \brief Check if this slice can be rewritten with legal operations.
8133 bool isLegal() const {
8134 // An invalid slice is not legal.
8135 if (!Origin || !Inst || !DAG)
8136 return false;
8137
8138 // Offsets are for indexed load only, we do not handle that.
8139 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8140 return false;
8141
8142 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8143
8144 // Check that the type is legal.
8145 EVT SliceType = getLoadedType();
8146 if (!TLI.isTypeLegal(SliceType))
8147 return false;
8148
8149 // Check that the load is legal for this type.
8150 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8151 return false;
8152
8153 // Check that the offset can be computed.
8154 // 1. Check its type.
8155 EVT PtrType = Origin->getBasePtr().getValueType();
8156 if (PtrType == MVT::Untyped || PtrType.isExtended())
8157 return false;
8158
8159 // 2. Check that it fits in the immediate.
8160 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8161 return false;
8162
8163 // 3. Check that the computation is legal.
8164 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8165 return false;
8166
8167 // Check that the zext is legal if it needs one.
8168 EVT TruncateType = Inst->getValueType(0);
8169 if (TruncateType != SliceType &&
8170 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8171 return false;
8172
8173 return true;
8174 }
8175
8176 /// \brief Get the offset in bytes of this slice in the original chunk of
8177 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008178 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008179 uint64_t getOffsetFromBase() const {
8180 assert(DAG && "Missing context.");
8181 bool IsBigEndian =
8182 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8183 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8184 uint64_t Offset = Shift / 8;
8185 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8186 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8187 "The size of the original loaded type is not a multiple of a"
8188 " byte.");
8189 // If Offset is bigger than TySizeInBytes, it means we are loading all
8190 // zeros. This should have been optimized before in the process.
8191 assert(TySizeInBytes > Offset &&
8192 "Invalid shift amount for given loaded size");
8193 if (IsBigEndian)
8194 Offset = TySizeInBytes - Offset - getLoadedSize();
8195 return Offset;
8196 }
8197
8198 /// \brief Generate the sequence of instructions to load the slice
8199 /// represented by this object and redirect the uses of this slice to
8200 /// this new sequence of instructions.
8201 /// \pre this->Inst && this->Origin are valid Instructions and this
8202 /// object passed the legal check: LoadedSlice::isLegal returned true.
8203 /// \return The last instruction of the sequence used to load the slice.
8204 SDValue loadSlice() const {
8205 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8206 const SDValue &OldBaseAddr = Origin->getBasePtr();
8207 SDValue BaseAddr = OldBaseAddr;
8208 // Get the offset in that chunk of bytes w.r.t. the endianess.
8209 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8210 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8211 if (Offset) {
8212 // BaseAddr = BaseAddr + Offset.
8213 EVT ArithType = BaseAddr.getValueType();
8214 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8215 DAG->getConstant(Offset, ArithType));
8216 }
8217
8218 // Create the type of the loaded slice according to its size.
8219 EVT SliceType = getLoadedType();
8220
8221 // Create the load for the slice.
8222 SDValue LastInst = DAG->getLoad(
8223 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8224 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8225 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8226 // If the final type is not the same as the loaded type, this means that
8227 // we have to pad with zero. Create a zero extend for that.
8228 EVT FinalType = Inst->getValueType(0);
8229 if (SliceType != FinalType)
8230 LastInst =
8231 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8232 return LastInst;
8233 }
8234
8235 /// \brief Check if this slice can be merged with an expensive cross register
8236 /// bank copy. E.g.,
8237 /// i = load i32
8238 /// f = bitcast i32 i to float
8239 bool canMergeExpensiveCrossRegisterBankCopy() const {
8240 if (!Inst || !Inst->hasOneUse())
8241 return false;
8242 SDNode *Use = *Inst->use_begin();
8243 if (Use->getOpcode() != ISD::BITCAST)
8244 return false;
8245 assert(DAG && "Missing context");
8246 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8247 EVT ResVT = Use->getValueType(0);
8248 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8249 const TargetRegisterClass *ArgRC =
8250 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8251 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8252 return false;
8253
8254 // At this point, we know that we perform a cross-register-bank copy.
8255 // Check if it is expensive.
8256 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8257 // Assume bitcasts are cheap, unless both register classes do not
8258 // explicitly share a common sub class.
8259 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8260 return false;
8261
8262 // Check if it will be merged with the load.
8263 // 1. Check the alignment constraint.
8264 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8265 ResVT.getTypeForEVT(*DAG->getContext()));
8266
8267 if (RequiredAlignment > getAlignment())
8268 return false;
8269
8270 // 2. Check that the load is a legal operation for that type.
8271 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8272 return false;
8273
8274 // 3. Check that we do not have a zext in the way.
8275 if (Inst->getValueType(0) != getLoadedType())
8276 return false;
8277
8278 return true;
8279 }
8280};
8281}
8282
Quentin Colombetde0e0622013-10-11 18:29:42 +00008283/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8284/// \p UsedBits looks like 0..0 1..1 0..0.
8285static bool areUsedBitsDense(const APInt &UsedBits) {
8286 // If all the bits are one, this is dense!
8287 if (UsedBits.isAllOnesValue())
8288 return true;
8289
8290 // Get rid of the unused bits on the right.
8291 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8292 // Get rid of the unused bits on the left.
8293 if (NarrowedUsedBits.countLeadingZeros())
8294 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8295 // Check that the chunk of bits is completely used.
8296 return NarrowedUsedBits.isAllOnesValue();
8297}
8298
8299/// \brief Check whether or not \p First and \p Second are next to each other
8300/// in memory. This means that there is no hole between the bits loaded
8301/// by \p First and the bits loaded by \p Second.
8302static bool areSlicesNextToEachOther(const LoadedSlice &First,
8303 const LoadedSlice &Second) {
8304 assert(First.Origin == Second.Origin && First.Origin &&
8305 "Unable to match different memory origins.");
8306 APInt UsedBits = First.getUsedBits();
8307 assert((UsedBits & Second.getUsedBits()) == 0 &&
8308 "Slices are not supposed to overlap.");
8309 UsedBits |= Second.getUsedBits();
8310 return areUsedBitsDense(UsedBits);
8311}
8312
8313/// \brief Adjust the \p GlobalLSCost according to the target
8314/// paring capabilities and the layout of the slices.
8315/// \pre \p GlobalLSCost should account for at least as many loads as
8316/// there is in the slices in \p LoadedSlices.
8317static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8318 LoadedSlice::Cost &GlobalLSCost) {
8319 unsigned NumberOfSlices = LoadedSlices.size();
8320 // If there is less than 2 elements, no pairing is possible.
8321 if (NumberOfSlices < 2)
8322 return;
8323
8324 // Sort the slices so that elements that are likely to be next to each
8325 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008326 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8327 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8328 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8329 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8330 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008331 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8332 // First (resp. Second) is the first (resp. Second) potentially candidate
8333 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008334 const LoadedSlice *First = nullptr;
8335 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008336 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8337 // Set the beginning of the pair.
8338 First = Second) {
8339
8340 Second = &LoadedSlices[CurrSlice];
8341
8342 // If First is NULL, it means we start a new pair.
8343 // Get to the next slice.
8344 if (!First)
8345 continue;
8346
8347 EVT LoadedType = First->getLoadedType();
8348
8349 // If the types of the slices are different, we cannot pair them.
8350 if (LoadedType != Second->getLoadedType())
8351 continue;
8352
8353 // Check if the target supplies paired loads for this type.
8354 unsigned RequiredAlignment = 0;
8355 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8356 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008357 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008358 continue;
8359 }
8360 // Check if we meet the alignment requirement.
8361 if (RequiredAlignment > First->getAlignment())
8362 continue;
8363
8364 // Check that both loads are next to each other in memory.
8365 if (!areSlicesNextToEachOther(*First, *Second))
8366 continue;
8367
8368 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8369 --GlobalLSCost.Loads;
8370 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008371 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008372 }
8373}
8374
8375/// \brief Check the profitability of all involved LoadedSlice.
8376/// Currently, it is considered profitable if there is exactly two
8377/// involved slices (1) which are (2) next to each other in memory, and
8378/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8379///
8380/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8381/// the elements themselves.
8382///
8383/// FIXME: When the cost model will be mature enough, we can relax
8384/// constraints (1) and (2).
8385static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8386 const APInt &UsedBits, bool ForCodeSize) {
8387 unsigned NumberOfSlices = LoadedSlices.size();
8388 if (StressLoadSlicing)
8389 return NumberOfSlices > 1;
8390
8391 // Check (1).
8392 if (NumberOfSlices != 2)
8393 return false;
8394
8395 // Check (2).
8396 if (!areUsedBitsDense(UsedBits))
8397 return false;
8398
8399 // Check (3).
8400 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8401 // The original code has one big load.
8402 OrigCost.Loads = 1;
8403 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8404 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8405 // Accumulate the cost of all the slices.
8406 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8407 GlobalSlicingCost += SliceCost;
8408
8409 // Account as cost in the original configuration the gain obtained
8410 // with the current slices.
8411 OrigCost.addSliceGain(LS);
8412 }
8413
8414 // If the target supports paired load, adjust the cost accordingly.
8415 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8416 return OrigCost > GlobalSlicingCost;
8417}
8418
8419/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8420/// operations, split it in the various pieces being extracted.
8421///
8422/// This sort of thing is introduced by SROA.
8423/// This slicing takes care not to insert overlapping loads.
8424/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8425bool DAGCombiner::SliceUpLoad(SDNode *N) {
8426 if (Level < AfterLegalizeDAG)
8427 return false;
8428
8429 LoadSDNode *LD = cast<LoadSDNode>(N);
8430 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8431 !LD->getValueType(0).isInteger())
8432 return false;
8433
8434 // Keep track of already used bits to detect overlapping values.
8435 // In that case, we will just abort the transformation.
8436 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8437
8438 SmallVector<LoadedSlice, 4> LoadedSlices;
8439
8440 // Check if this load is used as several smaller chunks of bits.
8441 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8442 // of computation for each trunc.
8443 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8444 UI != UIEnd; ++UI) {
8445 // Skip the uses of the chain.
8446 if (UI.getUse().getResNo() != 0)
8447 continue;
8448
8449 SDNode *User = *UI;
8450 unsigned Shift = 0;
8451
8452 // Check if this is a trunc(lshr).
8453 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8454 isa<ConstantSDNode>(User->getOperand(1))) {
8455 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8456 User = *User->use_begin();
8457 }
8458
8459 // At this point, User is a Truncate, iff we encountered, trunc or
8460 // trunc(lshr).
8461 if (User->getOpcode() != ISD::TRUNCATE)
8462 return false;
8463
8464 // The width of the type must be a power of 2 and greater than 8-bits.
8465 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008466 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008467 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008468 unsigned Width = User->getValueSizeInBits(0);
8469 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8470 return 0;
8471
8472 // Build the slice for this chain of computations.
8473 LoadedSlice LS(User, LD, Shift, &DAG);
8474 APInt CurrentUsedBits = LS.getUsedBits();
8475
8476 // Check if this slice overlaps with another.
8477 if ((CurrentUsedBits & UsedBits) != 0)
8478 return false;
8479 // Update the bits used globally.
8480 UsedBits |= CurrentUsedBits;
8481
8482 // Check if the new slice would be legal.
8483 if (!LS.isLegal())
8484 return false;
8485
8486 // Record the slice.
8487 LoadedSlices.push_back(LS);
8488 }
8489
8490 // Abort slicing if it does not seem to be profitable.
8491 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8492 return false;
8493
8494 ++SlicedLoads;
8495
8496 // Rewrite each chain to use an independent load.
8497 // By construction, each chain can be represented by a unique load.
8498
8499 // Prepare the argument for the new token factor for all the slices.
8500 SmallVector<SDValue, 8> ArgChains;
8501 for (SmallVectorImpl<LoadedSlice>::const_iterator
8502 LSIt = LoadedSlices.begin(),
8503 LSItEnd = LoadedSlices.end();
8504 LSIt != LSItEnd; ++LSIt) {
8505 SDValue SliceInst = LSIt->loadSlice();
8506 CombineTo(LSIt->Inst, SliceInst, true);
8507 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8508 SliceInst = SliceInst.getOperand(0);
8509 assert(SliceInst->getOpcode() == ISD::LOAD &&
8510 "It takes more than a zext to get to the loaded slice!!");
8511 ArgChains.push_back(SliceInst.getValue(1));
8512 }
8513
8514 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8515 &ArgChains[0], ArgChains.size());
8516 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8517 return true;
8518}
8519
Chris Lattner4041ab62010-04-15 04:48:01 +00008520/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8521/// load is having specific bytes cleared out. If so, return the byte size
8522/// being masked out and the shift amount.
8523static std::pair<unsigned, unsigned>
8524CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8525 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008526
Chris Lattner4041ab62010-04-15 04:48:01 +00008527 // Check for the structure we're looking for.
8528 if (V->getOpcode() != ISD::AND ||
8529 !isa<ConstantSDNode>(V->getOperand(1)) ||
8530 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8531 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008532
Chris Lattner3245afd2010-04-15 06:10:49 +00008533 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008534 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008535 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008536
Chris Lattner3245afd2010-04-15 06:10:49 +00008537 // The store should be chained directly to the load or be an operand of a
8538 // tokenfactor.
8539 if (LD == Chain.getNode())
8540 ; // ok.
8541 else if (Chain->getOpcode() != ISD::TokenFactor)
8542 return Result; // Fail.
8543 else {
8544 bool isOk = false;
8545 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8546 if (Chain->getOperand(i).getNode() == LD) {
8547 isOk = true;
8548 break;
8549 }
8550 if (!isOk) return Result;
8551 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008552
Chris Lattner4041ab62010-04-15 04:48:01 +00008553 // This only handles simple types.
8554 if (V.getValueType() != MVT::i16 &&
8555 V.getValueType() != MVT::i32 &&
8556 V.getValueType() != MVT::i64)
8557 return Result;
8558
8559 // Check the constant mask. Invert it so that the bits being masked out are
8560 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8561 // follow the sign bit for uniformity.
8562 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008563 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008564 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008565 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008566 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8567 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008568
Chris Lattner4041ab62010-04-15 04:48:01 +00008569 // See if we have a continuous run of bits. If so, we have 0*1+0*
8570 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8571 return Result;
8572
8573 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8574 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8575 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008576
Chris Lattner4041ab62010-04-15 04:48:01 +00008577 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8578 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008579 case 1:
8580 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008581 case 4: break;
8582 default: return Result; // All one mask, or 5-byte mask.
8583 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008584
Chris Lattner4041ab62010-04-15 04:48:01 +00008585 // Verify that the first bit starts at a multiple of mask so that the access
8586 // is aligned the same as the access width.
8587 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008588
Chris Lattner4041ab62010-04-15 04:48:01 +00008589 Result.first = MaskedBytes;
8590 Result.second = NotMaskTZ/8;
8591 return Result;
8592}
8593
8594
8595/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8596/// provides a value as specified by MaskInfo. If so, replace the specified
8597/// store with a narrower store of truncated IVal.
8598static SDNode *
8599ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8600 SDValue IVal, StoreSDNode *St,
8601 DAGCombiner *DC) {
8602 unsigned NumBytes = MaskInfo.first;
8603 unsigned ByteShift = MaskInfo.second;
8604 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008605
Chris Lattner4041ab62010-04-15 04:48:01 +00008606 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8607 // that uses this. If not, this is not a replacement.
8608 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8609 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008610 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008611
Chris Lattner4041ab62010-04-15 04:48:01 +00008612 // Check that it is legal on the target to do this. It is legal if the new
8613 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8614 // legalization.
8615 MVT VT = MVT::getIntegerVT(NumBytes*8);
8616 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008617 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008618
Chris Lattner4041ab62010-04-15 04:48:01 +00008619 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8620 // shifted by ByteShift and truncated down to NumBytes.
8621 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008622 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008623 DAG.getConstant(ByteShift*8,
8624 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008625
8626 // Figure out the offset for the store and the alignment of the access.
8627 unsigned StOffset;
8628 unsigned NewAlign = St->getAlignment();
8629
8630 if (DAG.getTargetLoweringInfo().isLittleEndian())
8631 StOffset = ByteShift;
8632 else
8633 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008634
Chris Lattner4041ab62010-04-15 04:48:01 +00008635 SDValue Ptr = St->getBasePtr();
8636 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008637 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008638 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8639 NewAlign = MinAlign(NewAlign, StOffset);
8640 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008641
Chris Lattner4041ab62010-04-15 04:48:01 +00008642 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008643 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008644
Chris Lattner4041ab62010-04-15 04:48:01 +00008645 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008646 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008647 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008648 false, false, NewAlign).getNode();
8649}
8650
Evan Chenga9cda8a2009-05-28 00:35:15 +00008651
8652/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8653/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8654/// of the loaded bits, try narrowing the load and store if it would end up
8655/// being a win for performance or code size.
8656SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8657 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008658 if (ST->isVolatile())
8659 return SDValue();
8660
Evan Chenga9cda8a2009-05-28 00:35:15 +00008661 SDValue Chain = ST->getChain();
8662 SDValue Value = ST->getValue();
8663 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008664 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008665
8666 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008667 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008668
8669 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008670
Chris Lattner4041ab62010-04-15 04:48:01 +00008671 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8672 // is a byte mask indicating a consecutive number of bytes, check to see if
8673 // Y is known to provide just those bytes. If so, we try to replace the
8674 // load + replace + store sequence with a single (narrower) store, which makes
8675 // the load dead.
8676 if (Opc == ISD::OR) {
8677 std::pair<unsigned, unsigned> MaskedLoad;
8678 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8679 if (MaskedLoad.first)
8680 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8681 Value.getOperand(1), ST,this))
8682 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008683
Chris Lattner4041ab62010-04-15 04:48:01 +00008684 // Or is commutative, so try swapping X and Y.
8685 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8686 if (MaskedLoad.first)
8687 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8688 Value.getOperand(0), ST,this))
8689 return SDValue(NewST, 0);
8690 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008691
Evan Chenga9cda8a2009-05-28 00:35:15 +00008692 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8693 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008694 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008695
8696 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008697 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8698 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008699 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008700 if (LD->getBasePtr() != Ptr ||
8701 LD->getPointerInfo().getAddrSpace() !=
8702 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008703 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008704
8705 // Find the type to narrow it the load / op / store to.
8706 SDValue N1 = Value.getOperand(1);
8707 unsigned BitWidth = N1.getValueSizeInBits();
8708 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8709 if (Opc == ISD::AND)
8710 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008711 if (Imm == 0 || Imm.isAllOnesValue())
8712 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008713 unsigned ShAmt = Imm.countTrailingZeros();
8714 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8715 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008716 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008717 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008718 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008719 TLI.isNarrowingProfitable(VT, NewVT))) {
8720 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008721 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008722 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008723 if (NewBW >= BitWidth)
8724 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008725
8726 // If the lsb changed does not start at the type bitwidth boundary,
8727 // start at the previous one.
8728 if (ShAmt % NewBW)
8729 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008730 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8731 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008732 if ((Imm & Mask) == Imm) {
8733 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8734 if (Opc == ISD::AND)
8735 NewImm ^= APInt::getAllOnesValue(NewBW);
8736 uint64_t PtrOff = ShAmt / 8;
8737 // For big endian targets, we need to adjust the offset to the pointer to
8738 // load the correct bytes.
8739 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008740 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008741
8742 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008743 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008744 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008745 return SDValue();
8746
Andrew Trickef9de2a2013-05-25 02:42:55 +00008747 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008748 Ptr.getValueType(), Ptr,
8749 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008750 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008751 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008752 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008753 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008754 LD->isInvariant(), NewAlign,
8755 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008756 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008757 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008758 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008759 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008760 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008761 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008762
8763 AddToWorkList(NewPtr.getNode());
8764 AddToWorkList(NewLD.getNode());
8765 AddToWorkList(NewVal.getNode());
8766 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008767 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008768 ++OpsNarrowed;
8769 return NewST;
8770 }
8771 }
8772
Evan Cheng6673ff02009-05-28 18:41:02 +00008773 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008774}
8775
Evan Chengd42641c2011-02-02 01:06:55 +00008776/// TransformFPLoadStorePair - For a given floating point load / store pair,
8777/// if the load value isn't used by any other operations, then consider
8778/// transforming the pair to integer load / store operations if the target
8779/// deems the transformation profitable.
8780SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8781 StoreSDNode *ST = cast<StoreSDNode>(N);
8782 SDValue Chain = ST->getChain();
8783 SDValue Value = ST->getValue();
8784 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8785 Value.hasOneUse() &&
8786 Chain == SDValue(Value.getNode(), 1)) {
8787 LoadSDNode *LD = cast<LoadSDNode>(Value);
8788 EVT VT = LD->getMemoryVT();
8789 if (!VT.isFloatingPoint() ||
8790 VT != ST->getMemoryVT() ||
8791 LD->isNonTemporal() ||
8792 ST->isNonTemporal() ||
8793 LD->getPointerInfo().getAddrSpace() != 0 ||
8794 ST->getPointerInfo().getAddrSpace() != 0)
8795 return SDValue();
8796
8797 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8798 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8799 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8800 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8801 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8802 return SDValue();
8803
8804 unsigned LDAlign = LD->getAlignment();
8805 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008806 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008807 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008808 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8809 return SDValue();
8810
Andrew Trickef9de2a2013-05-25 02:42:55 +00008811 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008812 LD->getChain(), LD->getBasePtr(),
8813 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008814 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008815
Andrew Trickef9de2a2013-05-25 02:42:55 +00008816 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008817 NewLD, ST->getBasePtr(),
8818 ST->getPointerInfo(),
8819 false, false, STAlign);
8820
8821 AddToWorkList(NewLD.getNode());
8822 AddToWorkList(NewST.getNode());
8823 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008824 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008825 ++LdStFP2Int;
8826 return NewST;
8827 }
8828
8829 return SDValue();
8830}
8831
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008832/// Helper struct to parse and store a memory address as base + index + offset.
8833/// We ignore sign extensions when it is safe to do so.
8834/// The following two expressions are not equivalent. To differentiate we need
8835/// to store whether there was a sign extension involved in the index
8836/// computation.
8837/// (load (i64 add (i64 copyfromreg %c)
8838/// (i64 signextend (add (i8 load %index)
8839/// (i8 1))))
8840/// vs
8841///
8842/// (load (i64 add (i64 copyfromreg %c)
8843/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8844/// (i32 1)))))
8845struct BaseIndexOffset {
8846 SDValue Base;
8847 SDValue Index;
8848 int64_t Offset;
8849 bool IsIndexSignExt;
8850
8851 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8852
8853 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8854 bool IsIndexSignExt) :
8855 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8856
8857 bool equalBaseIndex(const BaseIndexOffset &Other) {
8858 return Other.Base == Base && Other.Index == Index &&
8859 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008860 }
8861
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008862 /// Parses tree in Ptr for base, index, offset addresses.
8863 static BaseIndexOffset match(SDValue Ptr) {
8864 bool IsIndexSignExt = false;
8865
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008866 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8867 // instruction, then it could be just the BASE or everything else we don't
8868 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008869 if (Ptr->getOpcode() != ISD::ADD)
8870 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8871
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008872 // We know that we have at least an ADD instruction. Try to pattern match
8873 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008874 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8875 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8876 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8877 IsIndexSignExt);
8878 }
8879
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008880 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008881 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008882 // (i64 add (i64 %array_ptr)
8883 // (i64 mul (i64 %induction_var)
8884 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008885 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008886 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008887
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008888 // Look at Base + Index + Offset cases.
8889 SDValue Base = Ptr->getOperand(0);
8890 SDValue IndexOffset = Ptr->getOperand(1);
8891
8892 // Skip signextends.
8893 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8894 IndexOffset = IndexOffset->getOperand(0);
8895 IsIndexSignExt = true;
8896 }
8897
8898 // Either the case of Base + Index (no offset) or something else.
8899 if (IndexOffset->getOpcode() != ISD::ADD)
8900 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8901
8902 // Now we have the case of Base + Index + offset.
8903 SDValue Index = IndexOffset->getOperand(0);
8904 SDValue Offset = IndexOffset->getOperand(1);
8905
8906 if (!isa<ConstantSDNode>(Offset))
8907 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8908
8909 // Ignore signextends.
8910 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8911 Index = Index->getOperand(0);
8912 IsIndexSignExt = true;
8913 } else IsIndexSignExt = false;
8914
8915 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8916 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8917 }
8918};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008919
8920/// Holds a pointer to an LSBaseSDNode as well as information on where it
8921/// is located in a sequence of memory operations connected by a chain.
8922struct MemOpLink {
8923 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8924 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8925 // Ptr to the mem node.
8926 LSBaseSDNode *MemNode;
8927 // Offset from the base ptr.
8928 int64_t OffsetFromBase;
8929 // What is the sequence number of this mem node.
8930 // Lowest mem operand in the DAG starts at zero.
8931 unsigned SequenceNum;
8932};
8933
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008934bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8935 EVT MemVT = St->getMemoryVT();
8936 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008937 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8938 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008939
8940 // Don't merge vectors into wider inputs.
8941 if (MemVT.isVector() || !MemVT.isSimple())
8942 return false;
8943
8944 // Perform an early exit check. Do not bother looking at stored values that
8945 // are not constants or loads.
8946 SDValue StoredVal = St->getValue();
8947 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8948 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8949 !IsLoadSrc)
8950 return false;
8951
8952 // Only look at ends of store sequences.
8953 SDValue Chain = SDValue(St, 1);
8954 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8955 return false;
8956
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008957 // This holds the base pointer, index, and the offset in bytes from the base
8958 // pointer.
8959 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008960
8961 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008962 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008963 return false;
8964
8965 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008966 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008967 return false;
8968
Nadav Rotem307d7672012-11-29 00:00:08 +00008969 // Save the LoadSDNodes that we find in the chain.
8970 // We need to make sure that these nodes do not interfere with
8971 // any of the store nodes.
8972 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8973
8974 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008975 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00008976
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008977 // Walk up the chain and look for nodes with offsets from the same
8978 // base pointer. Stop when reaching an instruction with a different kind
8979 // or instruction which has a different base pointer.
8980 unsigned Seq = 0;
8981 StoreSDNode *Index = St;
8982 while (Index) {
8983 // If the chain has more than one use, then we can't reorder the mem ops.
8984 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8985 break;
8986
8987 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008988 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008989
8990 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008991 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008992 break;
8993
8994 // Check that the alignment is the same.
8995 if (Index->getAlignment() != St->getAlignment())
8996 break;
8997
8998 // The memory operands must not be volatile.
8999 if (Index->isVolatile() || Index->isIndexed())
9000 break;
9001
9002 // No truncation.
9003 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9004 if (St->isTruncatingStore())
9005 break;
9006
9007 // The stored memory type must be the same.
9008 if (Index->getMemoryVT() != MemVT)
9009 break;
9010
9011 // We do not allow unaligned stores because we want to prevent overriding
9012 // stores.
9013 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9014 break;
9015
9016 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009017 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009018
Nadav Rotem307d7672012-11-29 00:00:08 +00009019 // Find the next memory operand in the chain. If the next operand in the
9020 // chain is a store then move up and continue the scan with the next
9021 // memory operand. If the next operand is a load save it and use alias
9022 // information to check if it interferes with anything.
9023 SDNode *NextInChain = Index->getChain().getNode();
9024 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009025 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009026 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009027 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009028 break;
9029 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009030 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009031 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009032 break;
9033 }
9034
Nadav Rotem307d7672012-11-29 00:00:08 +00009035 // Save the load node for later. Continue the scan.
9036 AliasLoadNodes.push_back(Ldn);
9037 NextInChain = Ldn->getChain().getNode();
9038 continue;
9039 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009040 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009041 break;
9042 }
9043 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009044 }
9045
9046 // Check if there is anything to merge.
9047 if (StoreNodes.size() < 2)
9048 return false;
9049
9050 // Sort the memory operands according to their distance from the base pointer.
9051 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009052 [](MemOpLink LHS, MemOpLink RHS) {
9053 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9054 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9055 LHS.SequenceNum > RHS.SequenceNum);
9056 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009057
9058 // Scan the memory operations on the chain and find the first non-consecutive
9059 // store memory address.
9060 unsigned LastConsecutiveStore = 0;
9061 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009062 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9063
9064 // Check that the addresses are consecutive starting from the second
9065 // element in the list of stores.
9066 if (i > 0) {
9067 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9068 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9069 break;
9070 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009071
Nadav Rotem307d7672012-11-29 00:00:08 +00009072 bool Alias = false;
9073 // Check if this store interferes with any of the loads that we found.
9074 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9075 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9076 Alias = true;
9077 break;
9078 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009079 // We found a load that alias with this store. Stop the sequence.
9080 if (Alias)
9081 break;
9082
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009083 // Mark this node as useful.
9084 LastConsecutiveStore = i;
9085 }
9086
9087 // The node with the lowest store address.
9088 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9089
9090 // Store the constants into memory as one consecutive store.
9091 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009092 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009093 unsigned LastLegalVectorType = 0;
9094 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009095 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9096 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9097 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009098
9099 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009100 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009101 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009102 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009103 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009104 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009105 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009106 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009107
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009108 // Find a legal type for the constant store.
9109 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9110 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9111 if (TLI.isTypeLegal(StoreTy))
9112 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009113 // Or check whether a truncstore is legal.
9114 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9115 TargetLowering::TypePromoteInteger) {
9116 EVT LegalizedStoredValueTy =
9117 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9118 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9119 LastLegalType = i+1;
9120 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009121
9122 // Find a legal type for the vector store.
9123 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9124 if (TLI.isTypeLegal(Ty))
9125 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009126 }
9127
Bob Wilson3365b802012-12-20 01:36:20 +00009128 // We only use vectors if the constant is known to be zero and the
9129 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009130 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009131 LastLegalVectorType = 0;
9132
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009133 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009134 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009135 return false;
9136
Nadav Rotem495b1a42013-02-14 18:28:52 +00009137 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009138 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9139
9140 // Make sure we have something to merge.
9141 if (NumElem < 2)
9142 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009143
9144 unsigned EarliestNodeUsed = 0;
9145 for (unsigned i=0; i < NumElem; ++i) {
9146 // Find a chain for the new wide-store operand. Notice that some
9147 // of the store nodes that we found may not be selected for inclusion
9148 // in the wide store. The chain we use needs to be the chain of the
9149 // earliest store node which is *used* and replaced by the wide store.
9150 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9151 EarliestNodeUsed = i;
9152 }
9153
9154 // The earliest Node in the DAG.
9155 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009156 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009157
Nadav Rotemb27777f2012-10-04 22:35:15 +00009158 SDValue StoredVal;
9159 if (UseVector) {
9160 // Find a legal type for the vector store.
9161 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9162 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9163 StoredVal = DAG.getConstant(0, Ty);
9164 } else {
9165 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9166 APInt StoreInt(StoreBW, 0);
9167
9168 // Construct a single integer constant which is made of the smaller
9169 // constant inputs.
9170 bool IsLE = TLI.isLittleEndian();
9171 for (unsigned i = 0; i < NumElem ; ++i) {
9172 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9173 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9174 SDValue Val = St->getValue();
9175 StoreInt<<=ElementSizeBytes*8;
9176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9177 StoreInt|=C->getAPIntValue().zext(StoreBW);
9178 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9179 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9180 } else {
9181 assert(false && "Invalid constant element type");
9182 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009183 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009184
9185 // Create the new Load and Store operations.
9186 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9187 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009188 }
9189
Nadav Rotemb27777f2012-10-04 22:35:15 +00009190 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009191 FirstInChain->getBasePtr(),
9192 FirstInChain->getPointerInfo(),
9193 false, false,
9194 FirstInChain->getAlignment());
9195
9196 // Replace the first store with the new store
9197 CombineTo(EarliestOp, NewStore);
9198 // Erase all other stores.
9199 for (unsigned i = 0; i < NumElem ; ++i) {
9200 if (StoreNodes[i].MemNode == EarliestOp)
9201 continue;
9202 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009203 // ReplaceAllUsesWith will replace all uses that existed when it was
9204 // called, but graph optimizations may cause new ones to appear. For
9205 // example, the case in pr14333 looks like
9206 //
9207 // St's chain -> St -> another store -> X
9208 //
9209 // And the only difference from St to the other store is the chain.
9210 // When we change it's chain to be St's chain they become identical,
9211 // get CSEed and the net result is that X is now a use of St.
9212 // Since we know that St is redundant, just iterate.
9213 while (!St->use_empty())
9214 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009215 removeFromWorkList(St);
9216 DAG.DeleteNode(St);
9217 }
9218
9219 return true;
9220 }
9221
9222 // Below we handle the case of multiple consecutive stores that
9223 // come from multiple consecutive loads. We merge them into a single
9224 // wide load and a single wide store.
9225
9226 // Look for load nodes which are used by the stored values.
9227 SmallVector<MemOpLink, 8> LoadNodes;
9228
9229 // Find acceptable loads. Loads need to have the same chain (token factor),
9230 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009231 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009232 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9233 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9234 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9235 if (!Ld) break;
9236
9237 // Loads must only have one use.
9238 if (!Ld->hasNUsesOfValue(1, 0))
9239 break;
9240
9241 // Check that the alignment is the same as the stores.
9242 if (Ld->getAlignment() != St->getAlignment())
9243 break;
9244
9245 // The memory operands must not be volatile.
9246 if (Ld->isVolatile() || Ld->isIndexed())
9247 break;
9248
9249 // We do not accept ext loads.
9250 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9251 break;
9252
9253 // The stored memory type must be the same.
9254 if (Ld->getMemoryVT() != MemVT)
9255 break;
9256
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009257 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009258 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009259 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009260 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009261 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009262 break;
9263 } else {
9264 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009265 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009266 }
9267
9268 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009269 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009270 }
9271
9272 if (LoadNodes.size() < 2)
9273 return false;
9274
9275 // Scan the memory operations on the chain and find the first non-consecutive
9276 // load memory address. These variables hold the index in the store node
9277 // array.
9278 unsigned LastConsecutiveLoad = 0;
9279 // This variable refers to the size and not index in the array.
9280 unsigned LastLegalVectorType = 0;
9281 unsigned LastLegalIntegerType = 0;
9282 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009283 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9284 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9285 // All loads much share the same chain.
9286 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9287 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009288
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009289 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9290 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9291 break;
9292 LastConsecutiveLoad = i;
9293
9294 // Find a legal type for the vector store.
9295 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9296 if (TLI.isTypeLegal(StoreTy))
9297 LastLegalVectorType = i + 1;
9298
9299 // Find a legal type for the integer store.
9300 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9301 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9302 if (TLI.isTypeLegal(StoreTy))
9303 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009304 // Or check whether a truncstore and extload is legal.
9305 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9306 TargetLowering::TypePromoteInteger) {
9307 EVT LegalizedStoredValueTy =
9308 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9309 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9310 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9311 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9312 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9313 LastLegalIntegerType = i+1;
9314 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009315 }
9316
9317 // Only use vector types if the vector type is larger than the integer type.
9318 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009319 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009320 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9321
9322 // We add +1 here because the LastXXX variables refer to location while
9323 // the NumElem refers to array/index size.
9324 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9325 NumElem = std::min(LastLegalType, NumElem);
9326
9327 if (NumElem < 2)
9328 return false;
9329
9330 // The earliest Node in the DAG.
9331 unsigned EarliestNodeUsed = 0;
9332 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9333 for (unsigned i=1; i<NumElem; ++i) {
9334 // Find a chain for the new wide-store operand. Notice that some
9335 // of the store nodes that we found may not be selected for inclusion
9336 // in the wide store. The chain we use needs to be the chain of the
9337 // earliest store node which is *used* and replaced by the wide store.
9338 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9339 EarliestNodeUsed = i;
9340 }
9341
9342 // Find if it is better to use vectors or integers to load and store
9343 // to memory.
9344 EVT JointMemOpVT;
9345 if (UseVectorTy) {
9346 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9347 } else {
9348 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9349 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9350 }
9351
Andrew Trickef9de2a2013-05-25 02:42:55 +00009352 SDLoc LoadDL(LoadNodes[0].MemNode);
9353 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009354
9355 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9356 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9357 FirstLoad->getChain(),
9358 FirstLoad->getBasePtr(),
9359 FirstLoad->getPointerInfo(),
9360 false, false, false,
9361 FirstLoad->getAlignment());
9362
9363 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9364 FirstInChain->getBasePtr(),
9365 FirstInChain->getPointerInfo(), false, false,
9366 FirstInChain->getAlignment());
9367
Nadav Rotemac920662012-10-03 19:30:31 +00009368 // Replace one of the loads with the new load.
9369 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9370 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9371 SDValue(NewLoad.getNode(), 1));
9372
9373 // Remove the rest of the load chains.
9374 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009375 // Replace all chain users of the old load nodes with the chain of the new
9376 // load node.
9377 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009378 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9379 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009380
Nadav Rotemac920662012-10-03 19:30:31 +00009381 // Replace the first store with the new store.
9382 CombineTo(EarliestOp, NewStore);
9383 // Erase all other stores.
9384 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009385 // Remove all Store nodes.
9386 if (StoreNodes[i].MemNode == EarliestOp)
9387 continue;
9388 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9389 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9390 removeFromWorkList(St);
9391 DAG.DeleteNode(St);
9392 }
9393
9394 return true;
9395}
9396
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009397SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009398 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009399 SDValue Chain = ST->getChain();
9400 SDValue Value = ST->getValue();
9401 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009402
Evan Chenga4cf58a2007-05-07 21:27:48 +00009403 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009404 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009405 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009406 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009407 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009408 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009409 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009410 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009411 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009412 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009413 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009414 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009415 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009416 ST->isNonTemporal(), OrigAlign,
9417 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009418 }
Owen Andersona5192842011-04-14 17:30:49 +00009419
Chris Lattner41c80e82011-04-09 02:32:02 +00009420 // Turn 'store undef, Ptr' -> nothing.
9421 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9422 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009423
Nate Begeman8e20c762006-12-11 02:23:46 +00009424 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009425 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009426 // NOTE: If the original store is volatile, this transform must not increase
9427 // the number of stores. For example, on x86-32 an f64 can be stored in one
9428 // processor operation but an i64 (which is not legal) requires two. So the
9429 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009430 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009431 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009432 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009433 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009434 case MVT::f16: // We don't do this for these yet.
9435 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009436 case MVT::f128:
9437 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009438 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009439 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009440 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009441 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009442 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009443 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009444 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009445 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009446 }
9447 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009448 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009449 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009450 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009451 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009452 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009453 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009454 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009455 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009456 }
Owen Andersona5192842011-04-14 17:30:49 +00009457
Chris Lattner41c80e82011-04-09 02:32:02 +00009458 if (!ST->isVolatile() &&
9459 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009460 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009461 // argument passing. Since this is so common, custom legalize the
9462 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009463 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009464 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9465 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009466 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009467
Dan Gohman2af30632007-07-09 22:18:38 +00009468 unsigned Alignment = ST->getAlignment();
9469 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009470 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009471 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009472
Andrew Trickef9de2a2013-05-25 02:42:55 +00009473 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009474 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009475 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009476 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009477 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009478 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009479 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009480 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009481 Ptr, ST->getPointerInfo().getWithOffset(4),
9482 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009483 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009484 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009485 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009486 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009487
Chris Lattnerb7524b62006-12-12 04:16:14 +00009488 break;
Evan Cheng21836982006-12-11 17:25:19 +00009489 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009490 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009491 }
9492
Evan Cheng43cd9e32010-04-01 06:04:33 +00009493 // Try to infer better alignment information than the store already has.
9494 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009495 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9496 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009497 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009498 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009499 ST->isVolatile(), ST->isNonTemporal(), Align,
9500 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009501 }
9502 }
9503
Evan Chengd42641c2011-02-02 01:06:55 +00009504 // Try transforming a pair floating point load / store ops to integer
9505 // load / store ops.
9506 SDValue NewST = TransformFPLoadStorePair(N);
9507 if (NewST.getNode())
9508 return NewST;
9509
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009510 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9511 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009512#ifndef NDEBUG
9513 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9514 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9515 UseAA = false;
9516#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009517 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009518 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009519 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009520
Jim Laskey708d0db2006-10-04 16:53:27 +00009521 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009522 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009523 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009524
9525 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009526 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009527 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009528 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009529 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009530 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009531 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009532 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009533
Jim Laskeyd07be232006-09-25 16:29:54 +00009534 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009535 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009536 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009537
Nate Begeman879d8f12009-09-15 00:18:30 +00009538 // Make sure the new and old chains are cleaned up.
9539 AddToWorkList(Token.getNode());
9540
Jim Laskeydcf983c2006-10-13 23:32:28 +00009541 // Don't add users to work list.
9542 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009543 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009544 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009545
Evan Cheng33157702006-11-05 09:31:14 +00009546 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009547 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009548 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009549
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009550 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009551 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009552 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009553 // See if we can simplify the input to this truncstore with knowledge that
9554 // only the low bits are being used. For example:
9555 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009556 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009557 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009558 APInt::getLowBitsSet(
9559 Value.getValueType().getScalarType().getSizeInBits(),
9560 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009561 AddToWorkList(Value.getNode());
9562 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009563 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009564 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009565
Chris Lattnerf47e3062007-10-13 06:58:48 +00009566 // Otherwise, see if we can simplify the operation with
9567 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009568 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009569 APInt::getLowBitsSet(
9570 Value.getValueType().getScalarType().getSizeInBits(),
9571 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009572 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009573 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009574
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009575 // If this is a load followed by a store to the same location, then the store
9576 // is dead/noop.
9577 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009578 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009579 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009580 // There can't be any side effects between the load and store, such as
9581 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009582 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009583 // The store is dead, remove it.
9584 return Chain;
9585 }
9586 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009587
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009588 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9589 // truncating store. We can do this even if this is already a truncstore.
9590 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009591 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009592 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009593 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009594 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009595 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009596 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009597
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009598 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009599 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009600 if (!LegalTypes) {
9601 bool EverChanged = false;
9602
9603 do {
9604 // There can be multiple store sequences on the same chain.
9605 // Keep trying to merge store sequences until we are unable to do so
9606 // or until we merge the last store on the chain.
9607 bool Changed = MergeConsecutiveStores(ST);
9608 EverChanged |= Changed;
9609 if (!Changed) break;
9610 } while (ST->getOpcode() != ISD::DELETED_NODE);
9611
9612 if (EverChanged)
9613 return SDValue(N, 0);
9614 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009615
Evan Chenga9cda8a2009-05-28 00:35:15 +00009616 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009617}
9618
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009619SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9620 SDValue InVec = N->getOperand(0);
9621 SDValue InVal = N->getOperand(1);
9622 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009623 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009624
Bob Wilson42603952010-05-19 23:42:58 +00009625 // If the inserted element is an UNDEF, just use the input vector.
9626 if (InVal.getOpcode() == ISD::UNDEF)
9627 return InVec;
9628
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009629 EVT VT = InVec.getValueType();
9630
Owen Andersonb2c80da2011-02-25 21:41:48 +00009631 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009632 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9633 return SDValue();
9634
Eli Friedmanb7910b72011-09-09 21:04:06 +00009635 // Check that we know which element is being inserted
9636 if (!isa<ConstantSDNode>(EltNo))
9637 return SDValue();
9638 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009639
Eli Friedmanb7910b72011-09-09 21:04:06 +00009640 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9641 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9642 // vector elements.
9643 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009644 // Do not combine these two vectors if the output vector will not replace
9645 // the input vector.
9646 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009647 Ops.append(InVec.getNode()->op_begin(),
9648 InVec.getNode()->op_end());
9649 } else if (InVec.getOpcode() == ISD::UNDEF) {
9650 unsigned NElts = VT.getVectorNumElements();
9651 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9652 } else {
9653 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009654 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009655
9656 // Insert the element
9657 if (Elt < Ops.size()) {
9658 // All the operands of BUILD_VECTOR must have the same type;
9659 // we enforce that here.
9660 EVT OpVT = Ops[0].getValueType();
9661 if (InVal.getValueType() != OpVT)
9662 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9663 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9664 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9665 Ops[Elt] = InVal;
9666 }
9667
9668 // Return the new vector
9669 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9670 VT, &Ops[0], Ops.size());
Chris Lattner5336a592006-03-19 01:27:56 +00009671}
9672
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009673SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009674 // (vextract (scalar_to_vector val, 0) -> val
9675 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009676 EVT VT = InVec.getValueType();
9677 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009678
Duncan Sands6be291a2011-05-09 08:03:33 +00009679 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9680 // Check if the result type doesn't match the inserted element type. A
9681 // SCALAR_TO_VECTOR may truncate the inserted element and the
9682 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9683 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009684 if (InOp.getValueType() != NVT) {
9685 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009686 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009687 }
9688 return InOp;
9689 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009690
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009691 SDValue EltNo = N->getOperand(1);
9692 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9693
9694 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9695 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009696 // we may introduce new vector instructions which are not backed by TD
9697 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009698 // without using extract_subvector. However, if we can find an underlying
9699 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009700 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009701 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009702 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9703 int NumElem = VT.getVectorNumElements();
9704 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9705 // Find the new index to extract from.
9706 int OrigElt = SVOp->getMaskElt(Elt);
9707
9708 // Extracting an undef index is undef.
9709 if (OrigElt == -1)
9710 return DAG.getUNDEF(NVT);
9711
9712 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009713 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009714 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009715 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009716 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009717 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009718 OrigElt -= NumElem;
9719 }
9720
Hal Finkel02807592014-03-31 11:43:19 +00009721 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9722 SDValue InOp = SVInVec.getOperand(OrigElt);
9723 if (InOp.getValueType() != NVT) {
9724 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9725 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9726 }
9727
9728 return InOp;
9729 }
9730
9731 // FIXME: We should handle recursing on other vector shuffles and
9732 // scalar_to_vector here as well.
9733
9734 if (!LegalOperations) {
9735 EVT IndexTy = TLI.getVectorIdxTy();
9736 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9737 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9738 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009739 }
9740
Evan Cheng1120279a2008-05-13 08:35:03 +00009741 // Perform only after legalization to ensure build_vector / vector_shuffle
9742 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009743 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009744
Mon P Wangca6d6de2009-01-17 00:07:25 +00009745 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9746 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9747 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009748
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009749 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009750 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009751 bool NewLoad = false;
Mon P Wangb5eb7202008-12-11 00:26:16 +00009752 bool BCNumEltsChanged = false;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009753 EVT ExtVT = VT.getVectorElementType();
9754 EVT LVT = ExtVT;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009755
Evan Cheng7bf83092012-03-13 22:00:52 +00009756 // If the result of load has to be truncated, then it's not necessarily
9757 // profitable.
Evan Chengd5f8e572012-03-13 22:16:11 +00009758 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng7bf83092012-03-13 22:00:52 +00009759 return SDValue();
9760
Wesley Peck527da1b2010-11-23 03:31:01 +00009761 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009762 // Don't duplicate a load with other uses.
9763 if (!InVec.hasOneUse())
9764 return SDValue();
9765
Owen Anderson53aa7a92009-08-10 22:56:29 +00009766 EVT BCVT = InVec.getOperand(0).getValueType();
9767 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009768 return SDValue();
Mon P Wangb5eb7202008-12-11 00:26:16 +00009769 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9770 BCNumEltsChanged = true;
Evan Cheng1120279a2008-05-13 08:35:03 +00009771 InVec = InVec.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009772 ExtVT = BCVT.getVectorElementType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009773 NewLoad = true;
9774 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009775
Craig Topperc0196b12014-04-14 00:51:57 +00009776 LoadSDNode *LN0 = nullptr;
9777 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009778 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009779 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009780 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009781 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009782 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009783 // Don't duplicate a load with other uses.
9784 if (!InVec.hasOneUse())
9785 return SDValue();
9786
Evan Cheng1120279a2008-05-13 08:35:03 +00009787 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009788 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009789 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9790 // =>
9791 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009792
Eli Friedmane96286c2011-12-26 22:49:32 +00009793 // Don't duplicate a load with other uses.
9794 if (!InVec.hasOneUse())
9795 return SDValue();
9796
Mon P Wangb5eb7202008-12-11 00:26:16 +00009797 // If the bit convert changed the number of elements, it is unsafe
9798 // to examine the mask.
9799 if (BCNumEltsChanged)
9800 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009801
9802 // Select the input vector, guarding against out of range extract vector.
9803 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009804 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009805 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9806
Eli Friedmane96286c2011-12-26 22:49:32 +00009807 if (InVec.getOpcode() == ISD::BITCAST) {
9808 // Don't duplicate a load with other uses.
9809 if (!InVec.hasOneUse())
9810 return SDValue();
9811
Evan Cheng1120279a2008-05-13 08:35:03 +00009812 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009813 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009814 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009815 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009816 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009817 }
9818 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009819
Eli Friedmane96286c2011-12-26 22:49:32 +00009820 // Make sure we found a non-volatile load and the extractelement is
9821 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009822 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009823 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009824
Eric Christopherc6418b12010-11-03 20:44:42 +00009825 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9826 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009827 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009828
Evan Cheng1120279a2008-05-13 08:35:03 +00009829 unsigned Align = LN0->getAlignment();
9830 if (NewLoad) {
9831 // Check the resultant load doesn't need a higher alignment than the
9832 // original load.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009833 unsigned NewAlign =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009834 TLI.getDataLayout()
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009835 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendling27d9dd42009-01-30 23:36:47 +00009836
Dan Gohman4aa18462009-01-28 17:46:25 +00009837 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009838 return SDValue();
Bill Wendling27d9dd42009-01-30 23:36:47 +00009839
Evan Cheng1120279a2008-05-13 08:35:03 +00009840 Align = NewAlign;
9841 }
9842
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009843 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009844 unsigned PtrOff = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00009845
Eric Christopherc6418b12010-11-03 20:44:42 +00009846 if (Elt) {
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009847 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009848 EVT PtrType = NewPtr.getValueType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009849 if (TLI.isBigEndian())
Duncan Sands13237ac2008-06-06 12:08:01 +00009850 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009851 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng1120279a2008-05-13 08:35:03 +00009852 DAG.getConstant(PtrOff, PtrType));
9853 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009854
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009855 // The replacement we need to do here is a little tricky: we need to
9856 // replace an extractelement of a load with a load.
9857 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmane96286c2011-12-26 22:49:32 +00009858 // Note that this replacement assumes that the extractvalue is the only
9859 // use of the load; that's okay because we don't want to perform this
9860 // transformation in other cases anyway.
Evan Cheng7bf83092012-03-13 22:00:52 +00009861 SDValue Load;
Evan Chengd5f8e572012-03-13 22:16:11 +00009862 SDValue Chain;
Evan Cheng7bf83092012-03-13 22:00:52 +00009863 if (NVT.bitsGT(LVT)) {
9864 // If the result type of vextract is wider than the load, then issue an
9865 // extending load instead.
9866 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9867 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009868 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng7bf83092012-03-13 22:00:52 +00009869 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009870 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9871 Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009872 Chain = Load.getValue(1);
9873 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009874 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng7bf83092012-03-13 22:00:52 +00009875 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lincfe7f352013-07-08 00:37:03 +00009876 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009877 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009878 Chain = Load.getValue(1);
9879 if (NVT.bitsLT(LVT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009880 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009881 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009882 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009883 }
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009884 WorkListRemover DeadNodes(*this);
9885 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chengd5f8e572012-03-13 22:16:11 +00009886 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009887 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009888 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9889 // worklist explicitly as well.
9890 AddToWorkList(Load.getNode());
Craig Topperaaeae982012-03-20 05:28:39 +00009891 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009892 // Make sure to revisit this node to clean it up; it will usually be dead.
9893 AddToWorkList(N);
9894 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009895 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009896
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009897 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009898}
Evan Cheng0de312d2007-10-06 08:19:55 +00009899
Michael Liao6d106b72012-10-23 23:06:52 +00009900// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9901SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9902 // We perform this optimization post type-legalization because
9903 // the type-legalizer often scalarizes integer-promoted vectors.
9904 // Performing this optimization before may create bit-casts which
9905 // will be type-legalized to complex code sequences.
9906 // We perform this optimization only before the operation legalizer because we
9907 // may introduce illegal operations.
9908 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9909 return SDValue();
9910
Dan Gohmana8665142007-06-25 16:23:39 +00009911 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009912 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009913 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009914
Nadav Rotembf6568b2011-10-29 21:23:04 +00009915 // Check to see if this is a BUILD_VECTOR of a bunch of values
9916 // which come from any_extend or zero_extend nodes. If so, we can create
9917 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009918 // optimizations. We do not handle sign-extend because we can't fill the sign
9919 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009920 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009921 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009922
Craig Topper02cb0fb2012-01-17 09:09:48 +00009923 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009924 SDValue In = N->getOperand(i);
9925 // Ignore undef inputs.
9926 if (In.getOpcode() == ISD::UNDEF) continue;
9927
9928 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9929 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9930
Nadav Rotemf3103612011-10-31 20:08:25 +00009931 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009932 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009933 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009934 break;
9935 }
9936
9937 // The input is a ZeroExt or AnyExt. Check the original type.
9938 EVT InTy = In.getOperand(0).getValueType();
9939
9940 // Check that all of the widened source types are the same.
9941 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009942 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009943 SourceType = InTy;
9944 else if (InTy != SourceType) {
9945 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009946 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009947 break;
9948 }
9949
9950 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009951 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009952 }
9953
Nadav Rotemf3103612011-10-31 20:08:25 +00009954 // In order to have valid types, all of the inputs must be extended from the
9955 // same source type and all of the inputs must be any or zero extend.
9956 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009957 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009958 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +00009959 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9960 isPowerOf2_32(SourceType.getSizeInBits());
9961
Nadav Rotem6fd1d322012-03-15 08:49:06 +00009962 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9963 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +00009964 if (!ValidTypes)
9965 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +00009966
Michael Liao6d106b72012-10-23 23:06:52 +00009967 bool isLE = TLI.isLittleEndian();
9968 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9969 assert(ElemRatio > 1 && "Invalid element size ratio");
9970 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9971 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009972
Michael Liao6d106b72012-10-23 23:06:52 +00009973 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9974 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009975
Michael Liao6d106b72012-10-23 23:06:52 +00009976 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +00009977 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +00009978 SDValue Cast = N->getOperand(i);
9979 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9980 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9981 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9982 SDValue In;
9983 if (Cast.getOpcode() == ISD::UNDEF)
9984 In = DAG.getUNDEF(SourceType);
9985 else
9986 In = Cast->getOperand(0);
9987 unsigned Index = isLE ? (i * ElemRatio) :
9988 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +00009989
Michael Liao6d106b72012-10-23 23:06:52 +00009990 assert(Index < Ops.size() && "Invalid index");
9991 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009992 }
Chris Lattner5336a592006-03-19 01:27:56 +00009993
Michael Liao6d106b72012-10-23 23:06:52 +00009994 // The type of the new BUILD_VECTOR node.
9995 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9996 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9997 "Invalid vector size");
9998 // Check if the new vector type is legal.
9999 if (!isTypeLegal(VecVT)) return SDValue();
10000
10001 // Make the new BUILD_VECTOR.
10002 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10003
10004 // The new BUILD_VECTOR node has the potential to be further optimized.
10005 AddToWorkList(BV.getNode());
10006 // Bitcast to the desired type.
10007 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10008}
10009
Michael Liao59229792012-10-24 04:14:18 +000010010SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10011 EVT VT = N->getValueType(0);
10012
10013 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010014 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010015
10016 EVT SrcVT = MVT::Other;
10017 unsigned Opcode = ISD::DELETED_NODE;
10018 unsigned NumDefs = 0;
10019
10020 for (unsigned i = 0; i != NumInScalars; ++i) {
10021 SDValue In = N->getOperand(i);
10022 unsigned Opc = In.getOpcode();
10023
10024 if (Opc == ISD::UNDEF)
10025 continue;
10026
10027 // If all scalar values are floats and converted from integers.
10028 if (Opcode == ISD::DELETED_NODE &&
10029 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10030 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010031 }
Tom Stellard567f8862013-01-02 22:13:01 +000010032
Michael Liao59229792012-10-24 04:14:18 +000010033 if (Opc != Opcode)
10034 return SDValue();
10035
10036 EVT InVT = In.getOperand(0).getValueType();
10037
10038 // If all scalar values are typed differently, bail out. It's chosen to
10039 // simplify BUILD_VECTOR of integer types.
10040 if (SrcVT == MVT::Other)
10041 SrcVT = InVT;
10042 if (SrcVT != InVT)
10043 return SDValue();
10044 NumDefs++;
10045 }
10046
10047 // If the vector has just one element defined, it's not worth to fold it into
10048 // a vectorized one.
10049 if (NumDefs < 2)
10050 return SDValue();
10051
10052 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10053 && "Should only handle conversion from integer to float.");
10054 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10055
10056 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010057
10058 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10059 return SDValue();
10060
Michael Liao59229792012-10-24 04:14:18 +000010061 SmallVector<SDValue, 8> Opnds;
10062 for (unsigned i = 0; i != NumInScalars; ++i) {
10063 SDValue In = N->getOperand(i);
10064
10065 if (In.getOpcode() == ISD::UNDEF)
10066 Opnds.push_back(DAG.getUNDEF(SrcVT));
10067 else
10068 Opnds.push_back(In.getOperand(0));
10069 }
10070 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10071 &Opnds[0], Opnds.size());
10072 AddToWorkList(BV.getNode());
10073
10074 return DAG.getNode(Opcode, dl, VT, BV);
10075}
10076
Michael Liao6d106b72012-10-23 23:06:52 +000010077SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10078 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010079 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010080 EVT VT = N->getValueType(0);
10081
10082 // A vector built entirely of undefs is undef.
10083 if (ISD::allOperandsUndef(N))
10084 return DAG.getUNDEF(VT);
10085
10086 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10087 if (V.getNode())
10088 return V;
10089
Michael Liao59229792012-10-24 04:14:18 +000010090 V = reduceBuildVecConvertToConvertBuildVec(N);
10091 if (V.getNode())
10092 return V;
10093
Dan Gohmana8665142007-06-25 16:23:39 +000010094 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10095 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10096 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010097
10098 // May only combine to shuffle after legalize if shuffle is legal.
10099 if (LegalOperations &&
10100 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10101 return SDValue();
10102
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010103 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010104 for (unsigned i = 0; i != NumInScalars; ++i) {
10105 // Ignore undef inputs.
10106 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010107
Dan Gohmana8665142007-06-25 16:23:39 +000010108 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010109 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010110 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010111 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010112 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010113 break;
10114 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010115
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010116 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010117 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010118 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10119 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010120
Craig Topperc0196b12014-04-14 00:51:57 +000010121 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010122 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010123 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010124 VecIn2 = ExtractedFromVec;
10125 } else {
10126 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010127 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010128 break;
10129 }
10130 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010131
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010132 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010133 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010134 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010135 for (unsigned i = 0; i != NumInScalars; ++i) {
10136 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010137 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010138 continue;
10139 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010140
Rafael Espindolab93db662009-04-24 12:40:33 +000010141 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010142 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010143 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010144 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010145 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10146 if (ExtIndex > VT.getVectorNumElements())
10147 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010148
Nate Begeman5f829d82009-04-29 05:20:52 +000010149 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010150 continue;
10151 }
10152
10153 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010154 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010155 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010156 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010157
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010158 // We can't generate a shuffle node with mismatched input and output types.
10159 // Attempt to transform a single input vector to the correct type.
10160 if ((VT != VecIn1.getValueType())) {
10161 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010162 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010163 return SDValue();
10164
10165 // We only support widening of vectors which are half the size of the
10166 // output registers. For example XMM->YMM widening on X86 with AVX.
10167 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10168 return SDValue();
10169
James Molloy1e5c6112012-09-10 14:01:21 +000010170 // If the input vector type has a different base type to the output
10171 // vector type, bail out.
10172 if (VecIn1.getValueType().getVectorElementType() !=
10173 VT.getVectorElementType())
10174 return SDValue();
10175
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010176 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010177 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010178 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010179 }
10180
10181 // If VecIn2 is unused then change it to undef.
10182 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10183
Nadav Rotem841c9a82012-09-20 08:53:31 +000010184 // Check that we were able to transform all incoming values to the same
10185 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010186 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10187 VecIn1.getValueType() != VT)
10188 return SDValue();
10189
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010190 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010191 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010192 return SDValue();
10193
Dan Gohmana8665142007-06-25 16:23:39 +000010194 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010195 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010196 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010197 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010198 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010199 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010200
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010201 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010202}
10203
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010204SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010205 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10206 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10207 // inputs come from at most two distinct vectors, turn this into a shuffle
10208 // node.
10209
10210 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010211 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010212 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010213
Nadav Rotem01892102012-07-14 21:30:27 +000010214 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010215 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010216 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010217 return DAG.getUNDEF(VT);
10218
10219 // Optimize concat_vectors where one of the vectors is undef.
10220 if (N->getNumOperands() == 2 &&
10221 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10222 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010223 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010224
10225 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10226 if (In->getOpcode() == ISD::BITCAST &&
10227 !In->getOperand(0)->getValueType(0).isVector()) {
10228 SDValue Scalar = In->getOperand(0);
10229 EVT SclTy = Scalar->getValueType(0);
10230
10231 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10232 return SDValue();
10233
10234 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10235 VT.getSizeInBits() / SclTy.getSizeInBits());
10236 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10237 return SDValue();
10238
10239 SDLoc dl = SDLoc(N);
10240 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10241 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10242 }
10243 }
Nadav Rotem01892102012-07-14 21:30:27 +000010244
Robert Lougher7d9084f2014-02-11 15:42:46 +000010245 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10246 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10247 if (N->getNumOperands() == 2 &&
10248 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10249 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10250 EVT VT = N->getValueType(0);
10251 SDValue N0 = N->getOperand(0);
10252 SDValue N1 = N->getOperand(1);
10253 SmallVector<SDValue, 8> Opnds;
10254 unsigned BuildVecNumElts = N0.getNumOperands();
10255
10256 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10257 Opnds.push_back(N0.getOperand(i));
10258 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10259 Opnds.push_back(N1.getOperand(i));
10260
10261 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10262 Opnds.size());
10263 }
10264
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010265 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10266 // nodes often generate nop CONCAT_VECTOR nodes.
10267 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10268 // place the incoming vectors at the exact same location.
10269 SDValue SingleSource = SDValue();
10270 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10271
10272 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10273 SDValue Op = N->getOperand(i);
10274
10275 if (Op.getOpcode() == ISD::UNDEF)
10276 continue;
10277
10278 // Check if this is the identity extract:
10279 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10280 return SDValue();
10281
10282 // Find the single incoming vector for the extract_subvector.
10283 if (SingleSource.getNode()) {
10284 if (Op.getOperand(0) != SingleSource)
10285 return SDValue();
10286 } else {
10287 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010288
10289 // Check the source type is the same as the type of the result.
10290 // If not, this concat may extend the vector, so we can not
10291 // optimize it away.
10292 if (SingleSource.getValueType() != N->getValueType(0))
10293 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010294 }
10295
10296 unsigned IdentityIndex = i * PartNumElem;
10297 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10298 // The extract index must be constant.
10299 if (!CS)
10300 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010301
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010302 // Check that we are reading from the identity index.
10303 if (CS->getZExtValue() != IdentityIndex)
10304 return SDValue();
10305 }
10306
10307 if (SingleSource.getNode())
10308 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010309
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010310 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010311}
10312
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010313SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10314 EVT NVT = N->getValueType(0);
10315 SDValue V = N->getOperand(0);
10316
Michael Liao7a442c802012-10-17 20:48:33 +000010317 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10318 // Combine:
10319 // (extract_subvec (concat V1, V2, ...), i)
10320 // Into:
10321 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010322 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10323 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010324 if (V->getOperand(0).getValueType() != NVT)
10325 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010326 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10327 unsigned NumElems = NVT.getVectorNumElements();
10328 assert((Idx % NumElems) == 0 &&
10329 "IDX in concat is not a multiple of the result vector length.");
10330 return V->getOperand(Idx / NumElems);
10331 }
10332
Michael Liaobb05a1d2013-03-25 23:47:35 +000010333 // Skip bitcasting
10334 if (V->getOpcode() == ISD::BITCAST)
10335 V = V.getOperand(0);
10336
10337 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010338 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010339 // Handle only simple case where vector being inserted and vector
10340 // being extracted are of same type, and are half size of larger vectors.
10341 EVT BigVT = V->getOperand(0).getValueType();
10342 EVT SmallVT = V->getOperand(1).getValueType();
10343 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10344 return SDValue();
10345
10346 // Only handle cases where both indexes are constants with the same type.
10347 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10348 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10349
10350 if (InsIdx && ExtIdx &&
10351 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10352 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10353 // Combine:
10354 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10355 // Into:
10356 // indices are equal or bit offsets are equal => V1
10357 // otherwise => (extract_subvec V1, ExtIdx)
10358 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10359 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10360 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10361 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10362 DAG.getNode(ISD::BITCAST, dl,
10363 N->getOperand(0).getValueType(),
10364 V->getOperand(0)), N->getOperand(1));
10365 }
10366 }
10367
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010368 return SDValue();
10369}
10370
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010371// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10372static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10373 EVT VT = N->getValueType(0);
10374 unsigned NumElts = VT.getVectorNumElements();
10375
10376 SDValue N0 = N->getOperand(0);
10377 SDValue N1 = N->getOperand(1);
10378 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10379
10380 SmallVector<SDValue, 4> Ops;
10381 EVT ConcatVT = N0.getOperand(0).getValueType();
10382 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10383 unsigned NumConcats = NumElts / NumElemsPerConcat;
10384
10385 // Look at every vector that's inserted. We're looking for exact
10386 // subvector-sized copies from a concatenated vector
10387 for (unsigned I = 0; I != NumConcats; ++I) {
10388 // Make sure we're dealing with a copy.
10389 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010390 bool AllUndef = true, NoUndef = true;
10391 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10392 if (SVN->getMaskElt(J) >= 0)
10393 AllUndef = false;
10394 else
10395 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010396 }
10397
Hao Liubc601962013-05-13 02:07:05 +000010398 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010399 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10400 return SDValue();
10401
10402 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10403 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10404 return SDValue();
10405
10406 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10407 if (FirstElt < N0.getNumOperands())
10408 Ops.push_back(N0.getOperand(FirstElt));
10409 else
10410 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10411
10412 } else if (AllUndef) {
10413 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10414 } else { // Mixed with general masks and undefs, can't do optimization.
10415 return SDValue();
10416 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010417 }
10418
Andrew Trickef9de2a2013-05-25 02:42:55 +000010419 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010420 Ops.size());
10421}
10422
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010423SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010424 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010425 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010426
Mon P Wang25f01062008-11-10 04:46:22 +000010427 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010428 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010429
Craig Topper5894fe42012-04-09 05:16:56 +000010430 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010431
Craig Topper279c77b2012-01-04 08:07:43 +000010432 // Canonicalize shuffle undef, undef -> undef
10433 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10434 return DAG.getUNDEF(VT);
10435
10436 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10437
10438 // Canonicalize shuffle v, v -> v, undef
10439 if (N0 == N1) {
10440 SmallVector<int, 8> NewMask;
10441 for (unsigned i = 0; i != NumElts; ++i) {
10442 int Idx = SVN->getMaskElt(i);
10443 if (Idx >= (int)NumElts) Idx -= NumElts;
10444 NewMask.push_back(Idx);
10445 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010446 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010447 &NewMask[0]);
10448 }
10449
10450 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10451 if (N0.getOpcode() == ISD::UNDEF) {
10452 SmallVector<int, 8> NewMask;
10453 for (unsigned i = 0; i != NumElts; ++i) {
10454 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010455 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010456 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010457 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010458 else
10459 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010460 }
10461 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010462 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010463 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010464 &NewMask[0]);
10465 }
10466
10467 // Remove references to rhs if it is undef
10468 if (N1.getOpcode() == ISD::UNDEF) {
10469 bool Changed = false;
10470 SmallVector<int, 8> NewMask;
10471 for (unsigned i = 0; i != NumElts; ++i) {
10472 int Idx = SVN->getMaskElt(i);
10473 if (Idx >= (int)NumElts) {
10474 Idx = -1;
10475 Changed = true;
10476 }
10477 NewMask.push_back(Idx);
10478 }
10479 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010480 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010481 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010482
Bob Wilsonf63da122010-10-28 17:06:14 +000010483 // If it is a splat, check if the argument vector is another splat or a
10484 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010485 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010486 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010487
Dan Gohmana8665142007-06-25 16:23:39 +000010488 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010489 // not the number of vector elements, look through it. Be careful not to
10490 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010491 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010492 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010493 if (ConvInput.getValueType().isVector() &&
10494 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010495 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010496 }
10497
Dan Gohmana8665142007-06-25 16:23:39 +000010498 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010499 assert(V->getNumOperands() == NumElts &&
10500 "BUILD_VECTOR has wrong number of operands");
10501 SDValue Base;
10502 bool AllSame = true;
10503 for (unsigned i = 0; i != NumElts; ++i) {
10504 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10505 Base = V->getOperand(i);
10506 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010507 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010508 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010509 // Splat of <u, u, u, u>, return <u, u, u, u>
10510 if (!Base.getNode())
10511 return N0;
10512 for (unsigned i = 0; i != NumElts; ++i) {
10513 if (V->getOperand(i) != Base) {
10514 AllSame = false;
10515 break;
10516 }
10517 }
10518 // Splat of <x, x, x, x>, return <x, x, x, x>
10519 if (AllSame)
10520 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010521 }
10522 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010523
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010524 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10525 Level < AfterLegalizeVectorOps &&
10526 (N1.getOpcode() == ISD::UNDEF ||
10527 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10528 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10529 SDValue V = partitionShuffleOfConcats(N, DAG);
10530
10531 if (V.getNode())
10532 return V;
10533 }
10534
Nadav Rotemb0783502012-04-01 19:31:22 +000010535 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010536 // and it reverses the swizzle of the previous shuffle then we can
10537 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010538 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10539 N1.getOpcode() == ISD::UNDEF) {
10540
Nadav Rotemb0783502012-04-01 19:31:22 +000010541 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10542
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010543 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10544 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10545 return SDValue();
10546
Craig Topper5894fe42012-04-09 05:16:56 +000010547 // The incoming shuffle must be of the same type as the result of the
10548 // current shuffle.
10549 assert(OtherSV->getOperand(0).getValueType() == VT &&
10550 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010551
10552 for (unsigned i = 0; i != NumElts; ++i) {
10553 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010554 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010555 // Next, this index comes from the first value, which is the incoming
10556 // shuffle. Adopt the incoming index.
10557 if (Idx >= 0)
10558 Idx = OtherSV->getMaskElt(Idx);
10559
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010560 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010561 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010562 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010563 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010564
10565 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010566 }
10567
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010568 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010569}
10570
Manman Ren413a6cb2014-01-31 01:10:35 +000010571SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10572 SDValue N0 = N->getOperand(0);
10573 SDValue N2 = N->getOperand(2);
10574
10575 // If the input vector is a concatenation, and the insert replaces
10576 // one of the halves, we can optimize into a single concat_vectors.
10577 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10578 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10579 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10580 EVT VT = N->getValueType(0);
10581
10582 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10583 // (concat_vectors Z, Y)
10584 if (InsIdx == 0)
10585 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10586 N->getOperand(1), N0.getOperand(1));
10587
10588 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10589 // (concat_vectors X, Z)
10590 if (InsIdx == VT.getVectorNumElements()/2)
10591 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10592 N0.getOperand(0), N->getOperand(1));
10593 }
10594
10595 return SDValue();
10596}
10597
Evan Chenga320abc2006-04-20 08:56:16 +000010598/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010599/// an AND to a vector_shuffle with the destination vector and a zero vector.
10600/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010601/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010602SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010603 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010604 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010605 SDValue LHS = N->getOperand(0);
10606 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010607 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010608 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010609 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010610 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010611 SmallVector<int, 8> Indices;
10612 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010613 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010614 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010615 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010616 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010617
10618 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010619 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010620 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010621 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010622 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010623 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010624 }
10625
10626 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010627 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010628 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010629 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010630
Dan Gohmana8665142007-06-25 16:23:39 +000010631 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010632 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010633 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010634 DAG.getConstant(0, EltVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010635 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010636 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peck527da1b2010-11-23 03:31:01 +000010637 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010638 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010639 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010640 }
10641 }
Bill Wendling31b50992009-01-30 23:59:18 +000010642
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010643 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010644}
10645
Dan Gohmana8665142007-06-25 16:23:39 +000010646/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010647SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010648 assert(N->getValueType(0).isVector() &&
10649 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010650
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010651 SDValue LHS = N->getOperand(0);
10652 SDValue RHS = N->getOperand(1);
10653 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010654 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010655
Dan Gohmana8665142007-06-25 16:23:39 +000010656 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010657 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010658 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010659 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010660 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010661 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10662 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010663 return SDValue();
10664
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010665 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010666 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010667 SDValue LHSOp = LHS.getOperand(i);
10668 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010669
Evan Cheng64d28462006-05-31 06:08:35 +000010670 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010671 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10672 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010673 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010674 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010675 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010676 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010677 break;
10678 }
Bill Wendling31b50992009-01-30 23:59:18 +000010679
Bob Wilson54081442010-12-17 23:06:49 +000010680 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010681 EVT RVT = RHSOp.getValueType();
10682 if (RVT != VT) {
10683 // Integer BUILD_VECTOR operands may have types larger than the element
10684 // size (e.g., when the element type is not legal). Prior to type
10685 // legalization, the types may not match between the two BUILD_VECTORS.
10686 // Truncate one of the operands to make them match.
10687 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010688 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010689 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010690 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010691 VT = RVT;
10692 }
10693 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010694 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010695 LHSOp, RHSOp);
10696 if (FoldOp.getOpcode() != ISD::UNDEF &&
10697 FoldOp.getOpcode() != ISD::Constant &&
10698 FoldOp.getOpcode() != ISD::ConstantFP)
10699 break;
10700 Ops.push_back(FoldOp);
10701 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010702 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010703
Bob Wilson54081442010-12-17 23:06:49 +000010704 if (Ops.size() == LHS.getNumOperands())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010705 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilson54081442010-12-17 23:06:49 +000010706 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattner0442a182006-04-02 03:25:57 +000010707 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010708
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010709 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010710}
10711
Craig Topper82384612012-09-11 01:45:21 +000010712/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10713SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010714 assert(N->getValueType(0).isVector() &&
10715 "SimplifyVUnaryOp only works on vectors!");
10716
10717 SDValue N0 = N->getOperand(0);
10718
10719 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10720 return SDValue();
10721
10722 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10723 SmallVector<SDValue, 8> Ops;
10724 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10725 SDValue Op = N0.getOperand(i);
10726 if (Op.getOpcode() != ISD::UNDEF &&
10727 Op.getOpcode() != ISD::ConstantFP)
10728 break;
10729 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010730 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010731 if (FoldOp.getOpcode() != ISD::UNDEF &&
10732 FoldOp.getOpcode() != ISD::ConstantFP)
10733 break;
10734 Ops.push_back(FoldOp);
10735 AddToWorkList(FoldOp.getNode());
10736 }
10737
10738 if (Ops.size() != N0.getNumOperands())
10739 return SDValue();
10740
Andrew Trickef9de2a2013-05-25 02:42:55 +000010741 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topper82384612012-09-11 01:45:21 +000010742 N0.getValueType(), &Ops[0], Ops.size());
10743}
10744
Andrew Trickef9de2a2013-05-25 02:42:55 +000010745SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010746 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010747 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010748
Bill Wendling31b50992009-01-30 23:59:18 +000010749 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010750 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010751
Nate Begeman2042aa52005-10-08 00:29:44 +000010752 // If we got a simplified select_cc node back from SimplifySelectCC, then
10753 // break it down into a new SETCC node, and a new SELECT node, and then return
10754 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010755 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010756 // Check to see if we got a select_cc back (to turn into setcc/select).
10757 // Otherwise, just return whatever node we got back, like fabs.
10758 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010759 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010760 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010761 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010762 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010763 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010764 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10765 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010766 }
Bill Wendling31b50992009-01-30 23:59:18 +000010767
Nate Begeman2042aa52005-10-08 00:29:44 +000010768 return SCC;
10769 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010770 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010771}
10772
Chris Lattner6c14c352005-10-18 06:04:22 +000010773/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10774/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010775/// select. Callers of this should assume that TheSelect is deleted if this
10776/// returns true. As such, they should return the appropriate thing (e.g. the
10777/// node) back to the top-level of the DAG combiner loop to avoid it being
10778/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010779bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010780 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010781
Nadav Rotema49a02a2011-02-11 19:57:47 +000010782 // Cannot simplify select with vector condition
10783 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10784
Chris Lattner6c14c352005-10-18 06:04:22 +000010785 // If this is a select from two identical things, try to pull the operation
10786 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010787 if (LHS.getOpcode() != RHS.getOpcode() ||
10788 !LHS.hasOneUse() || !RHS.hasOneUse())
10789 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010790
Chris Lattner254c4452010-09-21 15:46:59 +000010791 // If this is a load and the token chain is identical, replace the select
10792 // of two loads with a load through a select of the address to load from.
10793 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10794 // constants have been dropped into the constant pool.
10795 if (LHS.getOpcode() == ISD::LOAD) {
10796 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10797 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010798
Chris Lattner254c4452010-09-21 15:46:59 +000010799 // Token chains must be identical.
10800 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010801 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010802 LLD->isVolatile() || RLD->isVolatile() ||
10803 // If this is an EXTLOAD, the VT's must match.
10804 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010805 // If this is an EXTLOAD, the kind of extension must match.
10806 (LLD->getExtensionType() != RLD->getExtensionType() &&
10807 // The only exception is if one of the extensions is anyext.
10808 LLD->getExtensionType() != ISD::EXTLOAD &&
10809 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010810 // FIXME: this discards src value information. This is
10811 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010812 // both potential memory locations. Since we are discarding
10813 // src value info, don't do the transformation if the memory
10814 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010815 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010816 RLD->getPointerInfo().getAddrSpace() != 0 ||
10817 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10818 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010819 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010820
Chris Lattnere3267522010-09-21 15:58:55 +000010821 // Check that the select condition doesn't reach either load. If so,
10822 // folding this will induce a cycle into the DAG. If not, this is safe to
10823 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010824 SDValue Addr;
10825 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010826 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10827 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10828 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10829 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010830 // The loads must not depend on one another.
10831 if (LLD->isPredecessorOf(RLD) ||
10832 RLD->isPredecessorOf(LLD))
10833 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010834 Addr = DAG.getSelect(SDLoc(TheSelect),
10835 LLD->getBasePtr().getValueType(),
10836 TheSelect->getOperand(0), LLD->getBasePtr(),
10837 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010838 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010839 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10840 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10841
10842 if ((LLD->hasAnyUseOfValue(1) &&
10843 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010844 (RLD->hasAnyUseOfValue(1) &&
10845 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010846 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010847
Andrew Trickef9de2a2013-05-25 02:42:55 +000010848 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010849 LLD->getBasePtr().getValueType(),
10850 TheSelect->getOperand(0),
10851 TheSelect->getOperand(1),
10852 LLD->getBasePtr(), RLD->getBasePtr(),
10853 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010854 }
10855
Chris Lattnere3267522010-09-21 15:58:55 +000010856 SDValue Load;
10857 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10858 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010859 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010860 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010861 LLD->getChain(), Addr, MachinePointerInfo(),
10862 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010863 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010864 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010865 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10866 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010867 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010868 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010869 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010870 LLD->getChain(), Addr, MachinePointerInfo(),
10871 LLD->getMemoryVT(), LLD->isVolatile(),
10872 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010873 }
Chris Lattnere3267522010-09-21 15:58:55 +000010874
10875 // Users of the select now use the result of the load.
10876 CombineTo(TheSelect, Load);
10877
10878 // Users of the old loads now use the new load's chain. We know the
10879 // old-load value is dead now.
10880 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10881 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10882 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010883 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010884
Chris Lattner6c14c352005-10-18 06:04:22 +000010885 return false;
10886}
10887
Chris Lattner43d63772009-03-11 05:08:08 +000010888/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10889/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010890SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010891 SDValue N2, SDValue N3,
10892 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010893 // (x ? y : y) -> y.
10894 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010895
Owen Anderson53aa7a92009-08-10 22:56:29 +000010896 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010897 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10898 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10899 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010900
10901 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010902 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010903 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010904 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10905 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010906
10907 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010908 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010909 return N2;
10910 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010911 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010912 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010913
Nate Begeman2042aa52005-10-08 00:29:44 +000010914 // Check to see if we can simplify the select into an fabs node
10915 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10916 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010917 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010918 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10919 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10920 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10921 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010922 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010923
Nate Begeman2042aa52005-10-08 00:29:44 +000010924 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10925 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10926 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10927 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010928 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010929 }
10930 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010931
Chris Lattner43d63772009-03-11 05:08:08 +000010932 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10933 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10934 // in it. This is a win when the constant is not otherwise available because
10935 // it replaces two constant pool loads with one. We only do this if the FP
10936 // type is known to be legal, because if it isn't, then we are before legalize
10937 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010938 // messing with soft float) and if the ConstantFP is not legal, because if
10939 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010940 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10941 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10942 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010943 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000010944 TargetLowering::Legal &&
10945 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10946 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010947 // If both constants have multiple uses, then we won't need to do an
10948 // extra load, they are likely around in registers for other users.
10949 (TV->hasOneUse() || FV->hasOneUse())) {
10950 Constant *Elts[] = {
10951 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10952 const_cast<ConstantFP*>(TV->getConstantFPValue())
10953 };
Chris Lattner229907c2011-07-18 04:54:35 +000010954 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010955 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010956
Chris Lattner43d63772009-03-11 05:08:08 +000010957 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010958 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010959 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10960 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000010961 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000010962
10963 // Get the offsets to the 0 and 1 element of the array so that we can
10964 // select between them.
10965 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010966 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000010967 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000010968
Chris Lattner43d63772009-03-11 05:08:08 +000010969 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000010970 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000010971 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010972 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010973 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10974 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010975 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000010976 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000010977 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010978 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000010979 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000010980 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000010981 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000010982
10983 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010984 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010985
Nate Begeman2042aa52005-10-08 00:29:44 +000010986 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000010987 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000010988 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000010989 (N1C->isNullValue() || // (a < 0) ? b : 0
10990 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000010991 EVT XType = N0.getValueType();
10992 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000010993 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000010994 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000010995 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010996 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10997 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000010998 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000010999 SDValue ShCt = DAG.getConstant(ShCtV,
11000 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011001 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011002 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011003 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011004
Duncan Sands11dd4242008-06-08 20:54:56 +000011005 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011006 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011007 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011008 }
Bill Wendling31b50992009-01-30 23:59:18 +000011009
11010 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011011 }
Bill Wendling31b50992009-01-30 23:59:18 +000011012
Andrew Trickef9de2a2013-05-25 02:42:55 +000011013 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011014 XType, N0,
11015 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011016 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000011017 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011018
Duncan Sands11dd4242008-06-08 20:54:56 +000011019 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011020 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011021 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011022 }
Bill Wendling31b50992009-01-30 23:59:18 +000011023
11024 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011025 }
11026 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011027
Owen Anderson3231d132010-09-22 22:58:22 +000011028 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11029 // where y is has a single bit set.
11030 // A plaintext description would be, we can turn the SELECT_CC into an AND
11031 // when the condition can be materialized as an all-ones register. Any
11032 // single bit-test can be materialized as an all-ones register with
11033 // shift-left and shift-right-arith.
11034 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11035 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011036 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011037 N2C && N2C->isNullValue()) {
11038 SDValue AndLHS = N0->getOperand(0);
11039 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11040 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11041 // Shift the tested bit over the sign bit.
11042 APInt AndMask = ConstAndRHS->getAPIntValue();
11043 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011044 DAG.getConstant(AndMask.countLeadingZeros(),
11045 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011046 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011047
Owen Anderson3231d132010-09-22 22:58:22 +000011048 // Now arithmetic right shift it all the way over, so the result is either
11049 // all-ones, or zero.
11050 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011051 DAG.getConstant(AndMask.getBitWidth()-1,
11052 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011053 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011054
Owen Anderson3231d132010-09-22 22:58:22 +000011055 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11056 }
11057 }
11058
Nate Begeman6828ed92005-10-10 21:26:48 +000011059 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011060 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000011061 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11062 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011063
Chris Lattnera083ffc2007-04-11 06:50:51 +000011064 // If the caller doesn't want us to simplify this into a zext of a compare,
11065 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011066 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011067 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011068
Nate Begeman6828ed92005-10-10 21:26:48 +000011069 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011070 // NOTE: Don't create a SETCC if it's not legal on this target.
11071 if (!LegalOperations ||
11072 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011073 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011074 SDValue Temp, SCC;
11075 // cast from setcc result type to select result type
11076 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011077 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011078 N0, N1, CC);
11079 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011080 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011081 N2.getValueType());
11082 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011083 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011084 N2.getValueType(), SCC);
11085 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011086 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11087 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011088 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011089 }
11090
11091 AddToWorkList(SCC.getNode());
11092 AddToWorkList(Temp.getNode());
11093
11094 if (N2C->getAPIntValue() == 1)
11095 return Temp;
11096
11097 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011098 return DAG.getNode(
11099 ISD::SHL, DL, N2.getValueType(), Temp,
11100 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11101 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011102 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011103 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011104
Nate Begeman2042aa52005-10-08 00:29:44 +000011105 // Check to see if this is the equivalent of setcc
11106 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11107 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011108 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011109 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011110 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011111 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11112 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011113 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011114 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011115 return Res;
11116 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011117
Bill Wendling31b50992009-01-30 23:59:18 +000011118 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011119 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011120 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011121 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011122 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011123 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011124 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011125 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011126 }
Bill Wendling31b50992009-01-30 23:59:18 +000011127 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011128 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011129 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011130 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011131 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011132 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011133 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011134 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011135 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011136 }
Bill Wendling31b50992009-01-30 23:59:18 +000011137 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011138 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011139 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011140 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011141 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011142 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011143 }
11144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011145
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011146 // Check to see if this is an integer abs.
11147 // select_cc setg[te] X, 0, X, -X ->
11148 // select_cc setgt X, -1, X, -X ->
11149 // select_cc setl[te] X, 0, -X, X ->
11150 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011151 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011152 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011153 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011154 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11155 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11156 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11157 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11158 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11159 (N1C->isOne() && CC == ISD::SETLT)) &&
11160 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11161 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11162
Owen Anderson53aa7a92009-08-10 22:56:29 +000011163 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011164 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011165 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011166 N0,
11167 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011168 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011169 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011170 XType, N0, Shift);
11171 AddToWorkList(Shift.getNode());
11172 AddToWorkList(Add.getNode());
11173 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011174 }
11175 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011176
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011177 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011178}
11179
Evan Cheng92658d52007-02-08 22:13:59 +000011180/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011181SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011182 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011183 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011184 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011185 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011186 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011187}
11188
Nate Begemanc6f067a2005-10-20 02:15:44 +000011189/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11190/// return a DAG expression to select that will generate the same value by
11191/// multiplying by a magic number. See:
11192/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011193SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011194 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011195 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011196
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011197 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011198 ii != ee; ++ii)
11199 AddToWorkList(*ii);
11200 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011201}
11202
11203/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11204/// return a DAG expression to select that will generate the same value by
11205/// multiplying by a magic number. See:
11206/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011207SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011208 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011209 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011210
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011211 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011212 ii != ee; ++ii)
11213 AddToWorkList(*ii);
11214 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011215}
11216
Nate Begeman18150d52009-09-25 06:05:26 +000011217/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011218// to alias with anything but itself. Provides base object and offset as
11219// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011220static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011221 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011222 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011223 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011224
Jim Laskey0463e082006-10-07 23:37:56 +000011225 // If it's an adding a simple constant then integrate the offset.
11226 if (Base.getOpcode() == ISD::ADD) {
11227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11228 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011229 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011230 }
11231 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011232
Nate Begeman18150d52009-09-25 06:05:26 +000011233 // Return the underlying GlobalValue, and update the Offset. Return false
11234 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11235 // by multiple nodes with different offsets.
11236 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11237 GV = G->getGlobal();
11238 Offset += G->getOffset();
11239 return false;
11240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011241
Nate Begeman18150d52009-09-25 06:05:26 +000011242 // Return the underlying Constant value, and update the Offset. Return false
11243 // for ConstantSDNodes since the same constant pool entry may be represented
11244 // by multiple nodes with different offsets.
11245 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011246 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11247 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011248 Offset += C->getOffset();
11249 return false;
11250 }
Jim Laskey0463e082006-10-07 23:37:56 +000011251 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011252 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011253}
11254
11255/// isAlias - Return true if there is any possibility that the two addresses
11256/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011257bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011258 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011259 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011260
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011261 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011262 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011263
Jim Laskey0463e082006-10-07 23:37:56 +000011264 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011265 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011266 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011267 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011268 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011269 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11270 Base1, Offset1, GV1, CV1);
11271 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11272 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011273
Nate Begeman18150d52009-09-25 06:05:26 +000011274 // If they have a same base address then check to see if they overlap.
11275 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011276 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11277 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011278
Owen Anderson272ff942010-09-20 20:39:59 +000011279 // It is possible for different frame indices to alias each other, mostly
11280 // when tail call optimization reuses return address slots for arguments.
11281 // To catch this case, look up the actual index of frame indices to compute
11282 // the real alias relationship.
11283 if (isFrameIndex1 && isFrameIndex2) {
11284 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11285 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11286 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011287 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11288 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011289 }
11290
Wesley Peck527da1b2010-11-23 03:31:01 +000011291 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011292 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011293 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11294 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011295
Nate Begeman879d8f12009-09-15 00:18:30 +000011296 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11297 // compared to the size and offset of the access, we may be able to prove they
11298 // do not alias. This check is conservative for now to catch cases created by
11299 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011300 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11301 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11302 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11303 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11304 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11305 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11306 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011307
Nate Begeman879d8f12009-09-15 00:18:30 +000011308 // There is no overlap between these relatively aligned accesses of similar
11309 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011310 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11311 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011312 return false;
11313 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011314
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011315 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11316 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011317#ifndef NDEBUG
11318 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11319 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11320 UseAA = false;
11321#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011322 if (UseAA &&
11323 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011324 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011325 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11326 Op1->getSrcValueOffset());
11327 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11328 Op0->getSrcValueOffset() - MinOffset;
11329 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11330 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011331 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011332 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11333 Overlap1,
11334 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11335 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11336 Overlap2,
11337 UseTBAA ? Op1->getTBAAInfo() : nullptr));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011338 if (AAResult == AliasAnalysis::NoAlias)
11339 return false;
11340 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011341
11342 // Otherwise we have to assume they alias.
11343 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011344}
11345
Jim Laskey708d0db2006-10-04 16:53:27 +000011346/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11347/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011348void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011349 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011350 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011351 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011352
Jim Laskeyd07be232006-09-25 16:29:54 +000011353 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011354 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011355
Jim Laskey708d0db2006-10-04 16:53:27 +000011356 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011357 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011358 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011359
Jim Laskey6549d222006-10-05 15:07:25 +000011360 // Look at each chain and determine if it is an alias. If so, add it to the
11361 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011362 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011363 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011364 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011365 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011366
11367 // For TokenFactor nodes, look at each operand and only continue up the
11368 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011369 // find more and revert to original chain since the xform is unlikely to be
11370 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011371 //
11372 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011373 // chain we found before we hit a tokenfactor rather than the original
11374 // chain.
11375 if (Depth > 6 || Aliases.size() == 2) {
11376 Aliases.clear();
11377 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011378 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011379 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011380
Nate Begeman879d8f12009-09-15 00:18:30 +000011381 // Don't bother if we've been before.
11382 if (!Visited.insert(Chain.getNode()))
11383 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011384
Jim Laskey6549d222006-10-05 15:07:25 +000011385 switch (Chain.getOpcode()) {
11386 case ISD::EntryToken:
11387 // Entry token is ideal chain operand, but handled in FindBetterChain.
11388 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011389
Jim Laskey6549d222006-10-05 15:07:25 +000011390 case ISD::LOAD:
11391 case ISD::STORE: {
11392 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011393 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11394 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011395
Jim Laskey6549d222006-10-05 15:07:25 +000011396 // If chain is alias then stop here.
11397 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011398 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011399 Aliases.push_back(Chain);
11400 } else {
11401 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011402 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011403 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011404 }
Jim Laskey6549d222006-10-05 15:07:25 +000011405 break;
11406 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011407
Jim Laskey6549d222006-10-05 15:07:25 +000011408 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011409 // We have to check each of the operands of the token factor for "small"
11410 // token factors, so we queue them up. Adding the operands to the queue
11411 // (stack) in reverse order maintains the original order and increases the
11412 // likelihood that getNode will find a matching token factor (CSE.)
11413 if (Chain.getNumOperands() > 16) {
11414 Aliases.push_back(Chain);
11415 break;
11416 }
Jim Laskey6549d222006-10-05 15:07:25 +000011417 for (unsigned n = Chain.getNumOperands(); n;)
11418 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011419 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011420 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011421
Jim Laskey6549d222006-10-05 15:07:25 +000011422 default:
11423 // For all other instructions we will just have to take what we can get.
11424 Aliases.push_back(Chain);
11425 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011426 }
11427 }
Hal Finkel51a98382014-01-24 20:12:02 +000011428
11429 // We need to be careful here to also search for aliases through the
11430 // value operand of a store, etc. Consider the following situation:
11431 // Token1 = ...
11432 // L1 = load Token1, %52
11433 // S1 = store Token1, L1, %51
11434 // L2 = load Token1, %52+8
11435 // S2 = store Token1, L2, %51+8
11436 // Token2 = Token(S1, S2)
11437 // L3 = load Token2, %53
11438 // S3 = store Token2, L3, %52
11439 // L4 = load Token2, %53+8
11440 // S4 = store Token2, L4, %52+8
11441 // If we search for aliases of S3 (which loads address %52), and we look
11442 // only through the chain, then we'll miss the trivial dependence on L1
11443 // (which also loads from %52). We then might change all loads and
11444 // stores to use Token1 as their chain operand, which could result in
11445 // copying %53 into %52 before copying %52 into %51 (which should
11446 // happen first).
11447 //
11448 // The problem is, however, that searching for such data dependencies
11449 // can become expensive, and the cost is not directly related to the
11450 // chain depth. Instead, we'll rule out such configurations here by
11451 // insisting that we've visited all chain users (except for users
11452 // of the original chain, which is not necessary). When doing this,
11453 // we need to look through nodes we don't care about (otherwise, things
11454 // like register copies will interfere with trivial cases).
11455
11456 SmallVector<const SDNode *, 16> Worklist;
11457 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11458 IE = Visited.end(); I != IE; ++I)
11459 if (*I != OriginalChain.getNode())
11460 Worklist.push_back(*I);
11461
11462 while (!Worklist.empty()) {
11463 const SDNode *M = Worklist.pop_back_val();
11464
11465 // We have already visited M, and want to make sure we've visited any uses
11466 // of M that we care about. For uses that we've not visisted, and don't
11467 // care about, queue them to the worklist.
11468
11469 for (SDNode::use_iterator UI = M->use_begin(),
11470 UIE = M->use_end(); UI != UIE; ++UI)
11471 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11472 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11473 // We've not visited this use, and we care about it (it could have an
11474 // ordering dependency with the original node).
11475 Aliases.clear();
11476 Aliases.push_back(OriginalChain);
11477 return;
11478 }
11479
11480 // We've not visited this use, but we don't care about it. Mark it as
11481 // visited and enqueue it to the worklist.
11482 Worklist.push_back(*UI);
11483 }
11484 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011485}
11486
11487/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11488/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011489SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11490 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011491
Jim Laskey708d0db2006-10-04 16:53:27 +000011492 // Accumulate all the aliases to this node.
11493 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011494
Dan Gohman4298df62011-05-17 22:20:36 +000011495 // If no operands then chain to entry token.
11496 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011497 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011498
11499 // If a single operand then chain to it. We don't need to revisit it.
11500 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011501 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011502
Jim Laskey708d0db2006-10-04 16:53:27 +000011503 // Construct a custom tailored token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011504 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begeman879d8f12009-09-15 00:18:30 +000011505 &Aliases[0], Aliases.size());
Jim Laskeyd07be232006-09-25 16:29:54 +000011506}
11507
Nate Begeman21158fc2005-09-01 00:19:25 +000011508// SelectionDAG::Combine - This is the entry point for the file.
11509//
Bill Wendling084669a2009-04-29 00:15:41 +000011510void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011511 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011512 /// run - This is the main entry point to this class.
11513 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011514 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011515}