blob: c4089446f08df75f53c38c7431d479e4c0e2f327 [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
Benjamin Kramerda4841b2014-04-26 23:09:49 +0000647 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
648 ConstantSDNode *CN = BV->getConstantSplatValue();
649
650 // BuildVectors can truncate their operands. Ignore that case here.
651 if (CN && CN->getValueType(0) == N.getValueType().getScalarType())
652 return CN;
653 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000654
655 return nullptr;
656}
657
Andrew Trickef9de2a2013-05-25 02:42:55 +0000658SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000659 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000660 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000661 if (N0.getOpcode() == Opc) {
662 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
663 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
664 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
665 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
666 if (!OpNode.getNode())
667 return SDValue();
668 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000669 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000670 if (N0.hasOneUse()) {
671 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
672 // use
673 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
674 if (!OpNode.getNode())
675 return SDValue();
676 AddToWorkList(OpNode.getNode());
677 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000678 }
679 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000680 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000681
Juergen Ributzka68402822014-01-13 21:49:25 +0000682 if (N1.getOpcode() == Opc) {
683 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
684 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
685 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
686 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
687 if (!OpNode.getNode())
688 return SDValue();
689 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
690 }
691 if (N1.hasOneUse()) {
692 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
693 // use
694 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
695 if (!OpNode.getNode())
696 return SDValue();
697 AddToWorkList(OpNode.getNode());
698 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
699 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000700 }
701 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000702
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000703 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000704}
705
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000706SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
707 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000708 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
709 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000710 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000711 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000712 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000713 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000714 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000715 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000716 assert((!To[i].getNode() ||
717 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000718 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000719 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000720 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000721 if (AddTo) {
722 // Push the new nodes and any users onto the worklist
723 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000724 if (To[i].getNode()) {
725 AddToWorkList(To[i].getNode());
726 AddUsersToWorkList(To[i].getNode());
727 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000728 }
729 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000730
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000731 // Finally, if the node is now dead, remove it from the graph. The node
732 // may not be dead if the replacement process recursively simplified to
733 // something else needing this node.
734 if (N->use_empty()) {
735 // Nodes can be reintroduced into the worklist. Make sure we do not
736 // process a node that has been replaced.
737 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000738
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000739 // Finally, since the node is now dead, remove it from the graph.
740 DAG.DeleteNode(N);
741 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000742 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000743}
744
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000745void DAGCombiner::
746CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000747 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000748 // are deleted, make sure to remove them from our worklist.
749 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000750 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000751
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000752 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000753 AddToWorkList(TLO.New.getNode());
754 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000755
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000756 // Finally, if the node is now dead, remove it from the graph. The node
757 // may not be dead if the replacement process recursively simplified to
758 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000759 if (TLO.Old.getNode()->use_empty()) {
760 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000761
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000762 // If the operands of this node are only used by the node, they will now
763 // be dead. Make sure to visit them first to delete dead nodes early.
Hal Finkel2c77fe52014-05-28 15:33:19 +0000764 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
765 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
766 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
767
Gabor Greiff304a7a2008-08-28 21:40:38 +0000768 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000769 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000770}
771
772/// SimplifyDemandedBits - Check the specified integer node value to see if
773/// it can be simplified or if things it uses can be simplified by bit
774/// propagation. If so, return true.
775bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000776 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000777 APInt KnownZero, KnownOne;
778 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
779 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000780
Dan Gohmane58ab792009-01-29 01:59:02 +0000781 // Revisit the node.
782 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000783
Dan Gohmane58ab792009-01-29 01:59:02 +0000784 // Replace the old value with the new one.
785 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000786 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000787 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000788 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000789 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000790 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000791
Dan Gohmane58ab792009-01-29 01:59:02 +0000792 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000793 return true;
794}
795
Evan Cheng0abb54d2010-04-24 04:43:44 +0000796void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000797 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000798 EVT VT = Load->getValueType(0);
799 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000800
Evan Cheng0abb54d2010-04-24 04:43:44 +0000801 DEBUG(dbgs() << "\nReplacing.9 ";
802 Load->dump(&DAG);
803 dbgs() << "\nWith: ";
804 Trunc.getNode()->dump(&DAG);
805 dbgs() << '\n');
806 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000807 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
808 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000809 removeFromWorkList(Load);
810 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000811 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000812}
813
814SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
815 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000816 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000817 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000818 EVT MemVT = LD->getMemoryVT();
819 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000820 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000821 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000822 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000823 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000824 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000825 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000826 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000827 }
828
Evan Chenge19aa5c2010-04-19 19:29:22 +0000829 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000830 switch (Opc) {
831 default: break;
832 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000833 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000834 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000835 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000836 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000837 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000838 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000839 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000840 case ISD::Constant: {
841 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000842 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000843 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000844 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000845 }
846
847 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000848 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000849 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000850}
851
Evan Cheng0abb54d2010-04-24 04:43:44 +0000852SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000853 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
854 return SDValue();
855 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000856 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000857 bool Replace = false;
858 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000859 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000860 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000861 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000862
863 if (Replace)
864 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
865 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000866 DAG.getValueType(OldVT));
867}
868
Evan Cheng0abb54d2010-04-24 04:43:44 +0000869SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000870 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000871 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000872 bool Replace = false;
873 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000874 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000875 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000876 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000877
878 if (Replace)
879 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
880 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000881}
882
Evan Chengaf56fac2010-04-16 06:14:10 +0000883/// PromoteIntBinOp - Promote the specified integer binary operation if the
884/// target indicates it is beneficial. e.g. On x86, it's usually better to
885/// promote i16 operations to i32 since i16 instructions are longer.
886SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
887 if (!LegalOperations)
888 return SDValue();
889
890 EVT VT = Op.getValueType();
891 if (VT.isVector() || !VT.isInteger())
892 return SDValue();
893
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000894 // If operation type is 'undesirable', e.g. i16 on x86, consider
895 // promoting it.
896 unsigned Opc = Op.getOpcode();
897 if (TLI.isTypeDesirableForOp(Opc, VT))
898 return SDValue();
899
Evan Chengaf56fac2010-04-16 06:14:10 +0000900 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000901 // Consult target whether it is a good idea to promote this operation and
902 // what's the right type to promote it to.
903 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000904 assert(PVT != VT && "Don't know what type to promote to!");
905
Evan Cheng0abb54d2010-04-24 04:43:44 +0000906 bool Replace0 = false;
907 SDValue N0 = Op.getOperand(0);
908 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000909 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000910 return SDValue();
911
Evan Cheng0abb54d2010-04-24 04:43:44 +0000912 bool Replace1 = false;
913 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000914 SDValue NN1;
915 if (N0 == N1)
916 NN1 = NN0;
917 else {
918 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000919 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000920 return SDValue();
921 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000922
Evan Cheng0abb54d2010-04-24 04:43:44 +0000923 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000924 if (NN1.getNode())
925 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000926
927 if (Replace0)
928 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
929 if (Replace1)
930 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000931
Evan Chenge8136902010-04-27 19:48:13 +0000932 DEBUG(dbgs() << "\nPromoting ";
933 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000934 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000935 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000936 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000937 }
938 return SDValue();
939}
940
941/// PromoteIntShiftOp - Promote the specified integer shift operation if the
942/// target indicates it is beneficial. e.g. On x86, it's usually better to
943/// promote i16 operations to i32 since i16 instructions are longer.
944SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
945 if (!LegalOperations)
946 return SDValue();
947
948 EVT VT = Op.getValueType();
949 if (VT.isVector() || !VT.isInteger())
950 return SDValue();
951
952 // If operation type is 'undesirable', e.g. i16 on x86, consider
953 // promoting it.
954 unsigned Opc = Op.getOpcode();
955 if (TLI.isTypeDesirableForOp(Opc, VT))
956 return SDValue();
957
958 EVT PVT = VT;
959 // Consult target whether it is a good idea to promote this operation and
960 // what's the right type to promote it to.
961 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
962 assert(PVT != VT && "Don't know what type to promote to!");
963
Evan Cheng0abb54d2010-04-24 04:43:44 +0000964 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000965 SDValue N0 = Op.getOperand(0);
966 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000967 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000968 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000969 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000970 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000971 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000972 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000973 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000974
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000975 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000976 if (Replace)
977 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000978
Evan Chenge8136902010-04-27 19:48:13 +0000979 DEBUG(dbgs() << "\nPromoting ";
980 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000981 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000982 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000983 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000984 }
985 return SDValue();
986}
987
Evan Chenge19aa5c2010-04-19 19:29:22 +0000988SDValue DAGCombiner::PromoteExtend(SDValue Op) {
989 if (!LegalOperations)
990 return SDValue();
991
992 EVT VT = Op.getValueType();
993 if (VT.isVector() || !VT.isInteger())
994 return SDValue();
995
996 // If operation type is 'undesirable', e.g. i16 on x86, consider
997 // promoting it.
998 unsigned Opc = Op.getOpcode();
999 if (TLI.isTypeDesirableForOp(Opc, VT))
1000 return SDValue();
1001
1002 EVT PVT = VT;
1003 // Consult target whether it is a good idea to promote this operation and
1004 // what's the right type to promote it to.
1005 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1006 assert(PVT != VT && "Don't know what type to promote to!");
1007 // fold (aext (aext x)) -> (aext x)
1008 // fold (aext (zext x)) -> (zext x)
1009 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001010 DEBUG(dbgs() << "\nPromoting ";
1011 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001012 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001013 }
1014 return SDValue();
1015}
1016
1017bool DAGCombiner::PromoteLoad(SDValue Op) {
1018 if (!LegalOperations)
1019 return false;
1020
1021 EVT VT = Op.getValueType();
1022 if (VT.isVector() || !VT.isInteger())
1023 return false;
1024
1025 // If operation type is 'undesirable', e.g. i16 on x86, consider
1026 // promoting it.
1027 unsigned Opc = Op.getOpcode();
1028 if (TLI.isTypeDesirableForOp(Opc, VT))
1029 return false;
1030
1031 EVT PVT = VT;
1032 // Consult target whether it is a good idea to promote this operation and
1033 // what's the right type to promote it to.
1034 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1035 assert(PVT != VT && "Don't know what type to promote to!");
1036
Andrew Trickef9de2a2013-05-25 02:42:55 +00001037 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001038 SDNode *N = Op.getNode();
1039 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001040 EVT MemVT = LD->getMemoryVT();
1041 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001042 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001043 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001044 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001045 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001046 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001047 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001048 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1049
Evan Cheng0abb54d2010-04-24 04:43:44 +00001050 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001051 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001052 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001053 Result.getNode()->dump(&DAG);
1054 dbgs() << '\n');
1055 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001056 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1057 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001058 removeFromWorkList(N);
1059 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001060 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001061 return true;
1062 }
1063 return false;
1064}
1065
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001066
Chris Lattnere49c9742007-05-14 22:04:50 +00001067//===----------------------------------------------------------------------===//
1068// Main DAG Combiner implementation
1069//===----------------------------------------------------------------------===//
1070
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001071void DAGCombiner::Run(CombineLevel AtLevel) {
1072 // set the instance variables, so that the various visit routines may use it.
1073 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001074 LegalOperations = Level >= AfterLegalizeVectorOps;
1075 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001076
Evan Cheng5e7658c2008-08-29 22:21:44 +00001077 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001078 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1079 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001080 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001081
Evan Cheng5e7658c2008-08-29 22:21:44 +00001082 // Create a dummy node (which is not added to allnodes), that adds a reference
1083 // to the root node, preventing it from being deleted, and tracking any
1084 // changes of the root.
1085 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001086
Jim Laskeye7d2c242006-10-17 19:33:52 +00001087 // The root of the dag may dangle to deleted nodes until the dag combiner is
1088 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001089 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001090
James Molloy67b6b112012-02-16 09:17:04 +00001091 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001092 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001093 while (!WorkListContents.empty()) {
1094 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001095 // The WorkListOrder holds the SDNodes in order, but it may contain
1096 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001097 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1098 // worklist *should* contain, and check the node we want to visit is should
1099 // actually be visited.
1100 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001101 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001102 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001103
Evan Cheng5e7658c2008-08-29 22:21:44 +00001104 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1105 // N is deleted from the DAG, since they too may now be dead or may have a
1106 // reduced number of uses, allowing other xforms.
1107 if (N->use_empty() && N != &Dummy) {
1108 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1109 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001110
Evan Cheng5e7658c2008-08-29 22:21:44 +00001111 DAG.DeleteNode(N);
1112 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001113 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001114
Evan Cheng5e7658c2008-08-29 22:21:44 +00001115 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001116
Craig Topperc0196b12014-04-14 00:51:57 +00001117 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001118 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001119
Evan Cheng5e7658c2008-08-29 22:21:44 +00001120 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001121
Evan Cheng5e7658c2008-08-29 22:21:44 +00001122 // If we get back the same node we passed in, rather than a new node or
1123 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001124 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001125 // mechanics for us, we have no work to do in this case.
1126 if (RV.getNode() == N)
1127 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001128
Evan Cheng5e7658c2008-08-29 22:21:44 +00001129 assert(N->getOpcode() != ISD::DELETED_NODE &&
1130 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1131 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001132
Wesley Peck527da1b2010-11-23 03:31:01 +00001133 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001134 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001135 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001136 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001137 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001138
Devang Patelefec7712011-05-23 22:04:42 +00001139 // Transfer debug value.
1140 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001141 WorkListRemover DeadNodes(*this);
1142 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001143 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001144 else {
1145 assert(N->getValueType(0) == RV.getValueType() &&
1146 N->getNumValues() == 1 && "Type mismatch");
1147 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001148 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001149 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001150
Evan Cheng5e7658c2008-08-29 22:21:44 +00001151 // Push the new node and any users onto the worklist
1152 AddToWorkList(RV.getNode());
1153 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001154
Evan Cheng5e7658c2008-08-29 22:21:44 +00001155 // Add any uses of the old node to the worklist in case this node is the
1156 // last one that uses them. They may become dead after this node is
1157 // deleted.
1158 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1159 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001160
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001161 // Finally, if the node is now dead, remove it from the graph. The node
1162 // may not be dead if the replacement process recursively simplified to
1163 // something else needing this node.
1164 if (N->use_empty()) {
1165 // Nodes can be reintroduced into the worklist. Make sure we do not
1166 // process a node that has been replaced.
1167 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001168
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001169 // Finally, since the node is now dead, remove it from the graph.
1170 DAG.DeleteNode(N);
1171 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001172 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001173
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001174 // If the root changed (e.g. it was a dead load, update the root).
1175 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001176 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001177}
1178
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001179SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001180 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001181 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001182 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001183 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001184 case ISD::ADD: return visitADD(N);
1185 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001186 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001187 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001188 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001189 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001190 case ISD::MUL: return visitMUL(N);
1191 case ISD::SDIV: return visitSDIV(N);
1192 case ISD::UDIV: return visitUDIV(N);
1193 case ISD::SREM: return visitSREM(N);
1194 case ISD::UREM: return visitUREM(N);
1195 case ISD::MULHU: return visitMULHU(N);
1196 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001197 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1198 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001199 case ISD::SMULO: return visitSMULO(N);
1200 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001201 case ISD::SDIVREM: return visitSDIVREM(N);
1202 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001203 case ISD::AND: return visitAND(N);
1204 case ISD::OR: return visitOR(N);
1205 case ISD::XOR: return visitXOR(N);
1206 case ISD::SHL: return visitSHL(N);
1207 case ISD::SRA: return visitSRA(N);
1208 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001209 case ISD::ROTR:
1210 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001211 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001212 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001213 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001214 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001215 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001216 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001217 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001218 case ISD::SELECT_CC: return visitSELECT_CC(N);
1219 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001220 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1221 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001222 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001223 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1224 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001225 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001226 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001227 case ISD::FADD: return visitFADD(N);
1228 case ISD::FSUB: return visitFSUB(N);
1229 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001230 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001231 case ISD::FDIV: return visitFDIV(N);
1232 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001233 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001234 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1235 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1236 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1237 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1238 case ISD::FP_ROUND: return visitFP_ROUND(N);
1239 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1240 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1241 case ISD::FNEG: return visitFNEG(N);
1242 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001243 case ISD::FFLOOR: return visitFFLOOR(N);
1244 case ISD::FCEIL: return visitFCEIL(N);
1245 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001246 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001247 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001248 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001249 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001250 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001251 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001252 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1253 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001254 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001255 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001256 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001257 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001258 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001259}
1260
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001261SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001262 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001263
1264 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001265 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001266 assert(N->getOpcode() != ISD::DELETED_NODE &&
1267 "Node was deleted but visit returned NULL!");
1268
1269 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1270 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1271
1272 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001273 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001274 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001275
1276 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1277 }
1278 }
1279
Evan Chengf1005572010-04-28 07:10:39 +00001280 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001281 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001282 switch (N->getOpcode()) {
1283 default: break;
1284 case ISD::ADD:
1285 case ISD::SUB:
1286 case ISD::MUL:
1287 case ISD::AND:
1288 case ISD::OR:
1289 case ISD::XOR:
1290 RV = PromoteIntBinOp(SDValue(N, 0));
1291 break;
1292 case ISD::SHL:
1293 case ISD::SRA:
1294 case ISD::SRL:
1295 RV = PromoteIntShiftOp(SDValue(N, 0));
1296 break;
1297 case ISD::SIGN_EXTEND:
1298 case ISD::ZERO_EXTEND:
1299 case ISD::ANY_EXTEND:
1300 RV = PromoteExtend(SDValue(N, 0));
1301 break;
1302 case ISD::LOAD:
1303 if (PromoteLoad(SDValue(N, 0)))
1304 RV = SDValue(N, 0);
1305 break;
1306 }
1307 }
1308
Scott Michelcf0da6c2009-02-17 22:15:04 +00001309 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001310 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001311 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001312 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001313 SDValue N0 = N->getOperand(0);
1314 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001315
Evan Cheng31604a62008-03-22 01:55:50 +00001316 // Constant operands are canonicalized to RHS.
1317 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001318 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001319 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
Craig Topper633d99b2014-04-27 23:22:43 +00001320 Ops);
Evan Chengfe7610f2008-03-24 23:55:16 +00001321 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001322 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001323 }
1324 }
1325
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001326 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001327}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001328
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001329/// getInputChainForNode - Given a node, return its input chain if it has one,
1330/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001331static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001332 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001333 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001334 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001335 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001336 return N->getOperand(NumOps-1);
1337 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001338 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001339 return N->getOperand(i);
1340 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001341 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001342}
1343
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001344SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001345 // If N has two operands, where one has an input chain equal to the other,
1346 // the 'other' chain is redundant.
1347 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001348 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001349 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001350 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001351 return N->getOperand(1);
1352 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001353
Chris Lattner48fb92f2007-05-16 06:37:59 +00001354 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001355 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001356 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001357 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001358
Jim Laskey708d0db2006-10-04 16:53:27 +00001359 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001360 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001361
Jim Laskey0463e082006-10-07 23:37:56 +00001362 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001363 // encountered.
1364 for (unsigned i = 0; i < TFs.size(); ++i) {
1365 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001366
Jim Laskey708d0db2006-10-04 16:53:27 +00001367 // Check each of the operands.
1368 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001369 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001370
Jim Laskey708d0db2006-10-04 16:53:27 +00001371 switch (Op.getOpcode()) {
1372 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001373 // Entry tokens don't need to be added to the list. They are
1374 // rededundant.
1375 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001376 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001377
Jim Laskey708d0db2006-10-04 16:53:27 +00001378 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001379 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001380 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001381 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001382 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001383 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001384 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001385 Changed = true;
1386 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001387 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001388 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001389
Jim Laskey708d0db2006-10-04 16:53:27 +00001390 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001391 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001392 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001393 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001394 else
1395 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001396 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001397 }
1398 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001399 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001400
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001401 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001402
1403 // If we've change things around then replace token factor.
1404 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001405 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001406 // The entry token is the only possible outcome.
1407 Result = DAG.getEntryNode();
1408 } else {
1409 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001410 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001411 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001412
Jim Laskeydcf983c2006-10-13 23:32:28 +00001413 // Don't add users to work list.
1414 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001415 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001416
Jim Laskey708d0db2006-10-04 16:53:27 +00001417 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001418}
1419
Chris Lattneree322b42008-02-13 07:25:05 +00001420/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001421SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001422 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001423 // Replacing results may cause a different MERGE_VALUES to suddenly
1424 // be CSE'd with N, and carry its uses with it. Iterate until no
1425 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001426 // First add the users of this node to the work list so that they
1427 // can be tried again once they have new operands.
1428 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001429 do {
1430 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001431 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001432 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001433 removeFromWorkList(N);
1434 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001435 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001436}
1437
Evan Cheng92011002007-01-19 17:51:44 +00001438static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001439SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001440 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001441 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001442 SDValue N00 = N0.getOperand(0);
1443 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001444 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001445
Gabor Greiff304a7a2008-08-28 21:40:38 +00001446 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001447 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001448 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001449 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1450 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001451 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001452 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001453 N00.getOperand(1), N01));
1454 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001455 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001456
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001457 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001458}
1459
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001460SDValue DAGCombiner::visitADD(SDNode *N) {
1461 SDValue N0 = N->getOperand(0);
1462 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001463 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1464 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001465 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001466
1467 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001468 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001469 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001470 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001471
1472 // fold (add x, 0) -> x, vector edition
1473 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1474 return N0;
1475 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1476 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001477 }
Bill Wendling0864a752008-12-10 22:36:00 +00001478
Dan Gohman06563a82007-07-03 14:03:57 +00001479 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001480 if (N0.getOpcode() == ISD::UNDEF)
1481 return N0;
1482 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001483 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001484 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001485 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001486 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001487 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001488 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001489 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001490 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001491 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001492 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001493 // fold (add Sym, c) -> Sym+c
1494 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001495 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001496 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001497 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001498 GA->getOffset() +
1499 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001500 // fold ((c1-A)+c2) -> (c1+c2)-A
1501 if (N1C && N0.getOpcode() == ISD::SUB)
1502 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001503 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001504 DAG.getConstant(N1C->getAPIntValue()+
1505 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001506 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001507 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001508 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001509 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001510 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001511 // fold ((0-A) + B) -> B-A
1512 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1513 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001514 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001515 // fold (A + (0-B)) -> A-B
1516 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1517 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001518 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001519 // fold (A+(B-A)) -> B
1520 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001521 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001522 // fold ((B-A)+A) -> B
1523 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1524 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001525 // fold (A+(B-(A+C))) to (B-C)
1526 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001527 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001528 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001529 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001530 // fold (A+(B-(C+A))) to (B-C)
1531 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001532 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001533 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001534 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001535 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001536 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1537 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001538 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001539 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001540 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001541
Dale Johannesen8c766702008-12-02 01:30:54 +00001542 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1543 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1544 SDValue N00 = N0.getOperand(0);
1545 SDValue N01 = N0.getOperand(1);
1546 SDValue N10 = N1.getOperand(0);
1547 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001548
1549 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001550 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1551 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1552 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001553 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001554
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001555 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1556 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001557
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001558 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001559 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001560 APInt LHSZero, LHSOne;
1561 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001562 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001563
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001564 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001565 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001566
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001567 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1568 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001569 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1570 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1571 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1572 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001573 }
1574 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001575
Evan Cheng92011002007-01-19 17:51:44 +00001576 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001577 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001578 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001579 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001580 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001581 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001582 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001583 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001584 }
1585
Dan Gohman954f4902010-01-19 23:30:49 +00001586 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1587 if (N1.getOpcode() == ISD::SHL &&
1588 N1.getOperand(0).getOpcode() == ISD::SUB)
1589 if (ConstantSDNode *C =
1590 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1591 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001592 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1593 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001594 N1.getOperand(0).getOperand(1),
1595 N1.getOperand(1)));
1596 if (N0.getOpcode() == ISD::SHL &&
1597 N0.getOperand(0).getOpcode() == ISD::SUB)
1598 if (ConstantSDNode *C =
1599 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1600 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001601 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1602 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001603 N0.getOperand(0).getOperand(1),
1604 N0.getOperand(1)));
1605
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001606 if (N1.getOpcode() == ISD::AND) {
1607 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001608 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001609 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1610 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001611
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001612 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1613 // and similar xforms where the inner op is either ~0 or 0.
1614 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001615 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001616 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1617 }
1618 }
1619
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001620 // add (sext i1), X -> sub X, (zext i1)
1621 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1622 N0.getOperand(0).getValueType() == MVT::i1 &&
1623 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001624 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001625 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1626 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1627 }
1628
Evan Chengf1005572010-04-28 07:10:39 +00001629 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001630}
1631
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001632SDValue DAGCombiner::visitADDC(SDNode *N) {
1633 SDValue N0 = N->getOperand(0);
1634 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001635 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1636 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001637 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001638
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001639 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001640 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001641 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001642 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001643 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001644
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001645 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001646 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001647 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001648
Chris Lattner47206662007-03-04 20:40:38 +00001649 // fold (addc x, 0) -> x + no carry out
1650 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001651 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001652 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001653
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001654 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001655 APInt LHSZero, LHSOne;
1656 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001657 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001658
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001659 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001660 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001661
Chris Lattner47206662007-03-04 20:40:38 +00001662 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1663 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001664 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001665 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001666 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001667 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001668 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001669
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001670 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001671}
1672
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001673SDValue DAGCombiner::visitADDE(SDNode *N) {
1674 SDValue N0 = N->getOperand(0);
1675 SDValue N1 = N->getOperand(1);
1676 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001677 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1678 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001679
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001680 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001681 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001682 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001683 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001684
Chris Lattner47206662007-03-04 20:40:38 +00001685 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001686 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001687 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001688
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001689 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001690}
1691
Eric Christophere5ca1e02011-02-16 04:50:12 +00001692// Since it may not be valid to emit a fold to zero for vector initializers
1693// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001694static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001695 SelectionDAG &DAG,
1696 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001697 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001698 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001699 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1700 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001701 return SDValue();
1702}
1703
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001704SDValue DAGCombiner::visitSUB(SDNode *N) {
1705 SDValue N0 = N->getOperand(0);
1706 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001707 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1708 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001709 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001710 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001711 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001712
Dan Gohmana8665142007-06-25 16:23:39 +00001713 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001714 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001715 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001716 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001717
1718 // fold (sub x, 0) -> x, vector edition
1719 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1720 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001721 }
Bill Wendling0864a752008-12-10 22:36:00 +00001722
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001723 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001724 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001725 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001726 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001727 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001728 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001729 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001730 // fold (sub x, c) -> (add x, -c)
1731 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001732 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001733 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001734 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1735 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001736 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001737 // fold A-(A-B) -> B
1738 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1739 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001740 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001741 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001742 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001743 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001744 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001745 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001746 // fold C2-(A+C1) -> (C2-C1)-A
1747 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001748 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1749 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001750 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001751 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001752 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001753 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001754 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001755 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1756 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001757 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001758 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001759 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001760 // fold ((A+(C+B))-B) -> A+C
1761 if (N0.getOpcode() == ISD::ADD &&
1762 N0.getOperand(1).getOpcode() == ISD::ADD &&
1763 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001764 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001765 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001766 // fold ((A-(B-C))-C) -> A-B
1767 if (N0.getOpcode() == ISD::SUB &&
1768 N0.getOperand(1).getOpcode() == ISD::SUB &&
1769 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001770 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001771 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001772
Dan Gohman06563a82007-07-03 14:03:57 +00001773 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001774 if (N0.getOpcode() == ISD::UNDEF)
1775 return N0;
1776 if (N1.getOpcode() == ISD::UNDEF)
1777 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001778
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001779 // If the relocation model supports it, consider symbol offsets.
1780 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001781 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001782 // fold (sub Sym, c) -> Sym-c
1783 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001784 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001785 GA->getOffset() -
1786 (uint64_t)N1C->getSExtValue());
1787 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1788 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1789 if (GA->getGlobal() == GB->getGlobal())
1790 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1791 VT);
1792 }
1793
Evan Chengf1005572010-04-28 07:10:39 +00001794 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001795}
1796
Craig Topper43a1bd62012-01-07 09:06:39 +00001797SDValue DAGCombiner::visitSUBC(SDNode *N) {
1798 SDValue N0 = N->getOperand(0);
1799 SDValue N1 = N->getOperand(1);
1800 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1801 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1802 EVT VT = N0.getValueType();
1803
1804 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001805 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001806 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1807 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001808 MVT::Glue));
1809
1810 // fold (subc x, x) -> 0 + no borrow
1811 if (N0 == N1)
1812 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001813 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001814 MVT::Glue));
1815
1816 // fold (subc x, 0) -> x + no borrow
1817 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001818 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001819 MVT::Glue));
1820
1821 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1822 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001823 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1824 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001825 MVT::Glue));
1826
1827 return SDValue();
1828}
1829
1830SDValue DAGCombiner::visitSUBE(SDNode *N) {
1831 SDValue N0 = N->getOperand(0);
1832 SDValue N1 = N->getOperand(1);
1833 SDValue CarryIn = N->getOperand(2);
1834
1835 // fold (sube x, y, false) -> (subc x, y)
1836 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001837 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001838
1839 return SDValue();
1840}
1841
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001842SDValue DAGCombiner::visitMUL(SDNode *N) {
1843 SDValue N0 = N->getOperand(0);
1844 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001845 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001846
Dan Gohman06563a82007-07-03 14:03:57 +00001847 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001848 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001849 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001850
1851 bool N0IsConst = false;
1852 bool N1IsConst = false;
1853 APInt ConstValue0, ConstValue1;
1854 // fold vector ops
1855 if (VT.isVector()) {
1856 SDValue FoldedVOp = SimplifyVBinOp(N);
1857 if (FoldedVOp.getNode()) return FoldedVOp;
1858
1859 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1860 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1861 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001862 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001863 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1864 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001865 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001866 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1867 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001868 }
1869
Nate Begeman21158fc2005-09-01 00:19:25 +00001870 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001871 if (N0IsConst && N1IsConst)
1872 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1873
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001874 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001875 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001876 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001877 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001878 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001879 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001880 // We require a splat of the entire scalar bit width for non-contiguous
1881 // bit patterns.
1882 bool IsFullSplat =
1883 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001884 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001885 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001886 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001887 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001888 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001889 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001890 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001891 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001892 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001893 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001894 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001895 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001896 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001897 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001898 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001899 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001900 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001901 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001902 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001903 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001904 DAG.getConstant(Log2Val,
1905 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001906 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001907
1908 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001909 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001910 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001911 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1912 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001913 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001914 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001915 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001916 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001917 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001918 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001919
Chris Lattner324871e2006-03-01 03:44:24 +00001920 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1921 // use.
1922 {
Craig Topperc0196b12014-04-14 00:51:57 +00001923 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001924 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001925 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001926 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1927 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001928 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001929 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001930 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001931 isa<ConstantSDNode>(N1.getOperand(1)) &&
1932 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001933 Sh = N1; Y = N0;
1934 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001935
Gabor Greiff304a7a2008-08-28 21:40:38 +00001936 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001937 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001938 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001939 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001940 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001941 }
1942 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001943
Chris Lattnerf29f5202006-03-04 23:33:26 +00001944 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001945 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1946 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1947 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001948 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1949 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001950 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001951 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001952 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001953
Nate Begeman22e251a2006-02-03 06:46:56 +00001954 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001955 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001956 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001957 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001958
Evan Chengf1005572010-04-28 07:10:39 +00001959 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001960}
1961
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001962SDValue DAGCombiner::visitSDIV(SDNode *N) {
1963 SDValue N0 = N->getOperand(0);
1964 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00001965 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1966 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001967 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001968
Dan Gohmana8665142007-06-25 16:23:39 +00001969 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001970 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001971 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001972 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001973 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001974
Nate Begeman21158fc2005-09-01 00:19:25 +00001975 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001976 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001977 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001978 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001979 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001980 return N0;
1981 // fold (sdiv X, -1) -> 0-X
1982 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001983 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00001984 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00001985 // If we know the sign bits of both operands are zero, strength reduce to a
1986 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00001987 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00001988 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001989 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00001990 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00001991 }
Benjamin Kramerad016872014-04-26 13:00:53 +00001992
Nate Begeman57b35672006-02-17 07:26:20 +00001993 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00001994 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
1995 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00001996 // If dividing by powers of two is cheap, then don't perform the following
1997 // fold.
1998 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001999 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002000
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002001 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002002
Chris Lattner471627c2006-02-16 08:02:36 +00002003 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002004 SDValue SGN =
2005 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2006 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2007 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002008 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002009
Chris Lattner471627c2006-02-16 08:02:36 +00002010 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002011 SDValue SRL =
2012 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2013 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2014 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002015 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002016 AddToWorkList(SRL.getNode());
2017 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002018 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002019 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002020
Nate Begeman4dd38312005-10-21 00:02:42 +00002021 // If we're dividing by a positive value, we're done. Otherwise, we must
2022 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002023 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002024 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002025
Gabor Greiff304a7a2008-08-28 21:40:38 +00002026 AddToWorkList(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002027 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002028 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002029
Nate Begemanc6f067a2005-10-20 02:15:44 +00002030 // if integer divide is expensive and we satisfy the requirements, emit an
2031 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002032 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002033 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002034 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002035 }
Dan Gohmana8665142007-06-25 16:23:39 +00002036
Dan Gohman06563a82007-07-03 14:03:57 +00002037 // undef / X -> 0
2038 if (N0.getOpcode() == ISD::UNDEF)
2039 return DAG.getConstant(0, VT);
2040 // X / undef -> undef
2041 if (N1.getOpcode() == ISD::UNDEF)
2042 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002043
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002044 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002045}
2046
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002047SDValue DAGCombiner::visitUDIV(SDNode *N) {
2048 SDValue N0 = N->getOperand(0);
2049 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002050 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2051 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002052 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002053
Dan Gohmana8665142007-06-25 16:23:39 +00002054 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002055 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002056 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002057 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002058 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002059
Nate Begeman21158fc2005-09-01 00:19:25 +00002060 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002061 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002062 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002063 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002064 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002065 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002066 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002067 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002068 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002069 if (N1.getOpcode() == ISD::SHL) {
2070 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002071 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002072 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002073 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002074 N1.getOperand(1),
2075 DAG.getConstant(SHC->getAPIntValue()
2076 .logBase2(),
2077 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002078 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002079 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002080 }
2081 }
2082 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002083 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002084 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002085 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002086 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002087 }
Dan Gohmana8665142007-06-25 16:23:39 +00002088
Dan Gohman06563a82007-07-03 14:03:57 +00002089 // undef / X -> 0
2090 if (N0.getOpcode() == ISD::UNDEF)
2091 return DAG.getConstant(0, VT);
2092 // X / undef -> undef
2093 if (N1.getOpcode() == ISD::UNDEF)
2094 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002095
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002096 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002097}
2098
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002099SDValue DAGCombiner::visitSREM(SDNode *N) {
2100 SDValue N0 = N->getOperand(0);
2101 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002102 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2103 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002104 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002105
Nate Begeman21158fc2005-09-01 00:19:25 +00002106 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002107 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002108 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002109 // If we know the sign bits of both operands are zero, strength reduce to a
2110 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002111 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002112 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002113 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002114 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002115
Dan Gohman9a693412007-11-26 23:46:11 +00002116 // If X/C can be simplified by the division-by-constant logic, lower
2117 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002118 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002119 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002120 AddToWorkList(Div.getNode());
2121 SDValue OptimizedDiv = combine(Div.getNode());
2122 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002123 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002124 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002125 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002126 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002127 return Sub;
2128 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002129 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002130
Dan Gohman06563a82007-07-03 14:03:57 +00002131 // undef % X -> 0
2132 if (N0.getOpcode() == ISD::UNDEF)
2133 return DAG.getConstant(0, VT);
2134 // X % undef -> undef
2135 if (N1.getOpcode() == ISD::UNDEF)
2136 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002137
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002138 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002139}
2140
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002141SDValue DAGCombiner::visitUREM(SDNode *N) {
2142 SDValue N0 = N->getOperand(0);
2143 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002144 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2145 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002146 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002147
Nate Begeman21158fc2005-09-01 00:19:25 +00002148 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002149 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002150 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002151 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002152 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002153 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002154 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002155 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2156 if (N1.getOpcode() == ISD::SHL) {
2157 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002158 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002159 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002160 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002161 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002162 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002163 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002164 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002165 }
2166 }
2167 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002168
Dan Gohman9a693412007-11-26 23:46:11 +00002169 // If X/C can be simplified by the division-by-constant logic, lower
2170 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002171 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002172 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002173 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002174 SDValue OptimizedDiv = combine(Div.getNode());
2175 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002176 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002177 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002178 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002179 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002180 return Sub;
2181 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002182 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002183
Dan Gohman06563a82007-07-03 14:03:57 +00002184 // undef % X -> 0
2185 if (N0.getOpcode() == ISD::UNDEF)
2186 return DAG.getConstant(0, VT);
2187 // X % undef -> undef
2188 if (N1.getOpcode() == ISD::UNDEF)
2189 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002190
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002191 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002192}
2193
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002194SDValue DAGCombiner::visitMULHS(SDNode *N) {
2195 SDValue N0 = N->getOperand(0);
2196 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002197 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002198 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002199 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002200
Nate Begeman21158fc2005-09-01 00:19:25 +00002201 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002202 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002203 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002204 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002205 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002206 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002207 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002208 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002209 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002210 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002211 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002212
Chris Lattner10bd29f2010-12-13 08:39:01 +00002213 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2214 // plus a shift.
2215 if (VT.isSimple() && !VT.isVector()) {
2216 MVT Simple = VT.getSimpleVT();
2217 unsigned SimpleSize = Simple.getSizeInBits();
2218 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2219 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2220 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2221 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2222 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002223 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002224 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002225 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2226 }
2227 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002228
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002229 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002230}
2231
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002232SDValue DAGCombiner::visitMULHU(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002235 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002236 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002237 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002238
Nate Begeman21158fc2005-09-01 00:19:25 +00002239 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002240 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002241 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002242 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002243 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002244 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002245 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002246 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002247 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002248
Chris Lattner10bd29f2010-12-13 08:39:01 +00002249 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2250 // plus a shift.
2251 if (VT.isSimple() && !VT.isVector()) {
2252 MVT Simple = VT.getSimpleVT();
2253 unsigned SimpleSize = Simple.getSizeInBits();
2254 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2255 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2256 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2257 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2258 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2259 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002260 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002261 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2262 }
2263 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002264
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002265 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002266}
2267
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002268/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2269/// compute two values. LoOp and HiOp give the opcodes for the two computations
2270/// that are being performed. Return true if a simplification was made.
2271///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002272SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002273 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002274 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002275 bool HiExists = N->hasAnyUseOfValue(1);
2276 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002277 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002278 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002279 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002280 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002281 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002282 }
2283
2284 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002285 bool LoExists = N->hasAnyUseOfValue(0);
2286 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002287 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002288 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002289 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002290 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002291 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002292 }
2293
Evan Chengece4c682007-11-08 09:25:29 +00002294 // If both halves are used, return as it is.
2295 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002296 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002297
2298 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002299 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002300 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002301 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002302 AddToWorkList(Lo.getNode());
2303 SDValue LoOpt = combine(Lo.getNode());
2304 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002305 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002306 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002307 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002308 }
2309
Evan Chengece4c682007-11-08 09:25:29 +00002310 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002311 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002312 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002313 AddToWorkList(Hi.getNode());
2314 SDValue HiOpt = combine(Hi.getNode());
2315 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002316 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002317 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002318 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002319 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002320
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002321 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002322}
2323
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002324SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2325 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002326 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002327
Chris Lattner15090e12010-12-15 06:04:19 +00002328 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002329 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002330
2331 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2332 // plus a shift.
2333 if (VT.isSimple() && !VT.isVector()) {
2334 MVT Simple = VT.getSimpleVT();
2335 unsigned SimpleSize = Simple.getSizeInBits();
2336 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2337 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2338 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2339 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2340 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2341 // Compute the high part as N1.
2342 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002343 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002344 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2345 // Compute the low part as N0.
2346 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2347 return CombineTo(N, Lo, Hi);
2348 }
2349 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002350
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002351 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002352}
2353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002354SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2355 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002356 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002357
Chris Lattner15090e12010-12-15 06:04:19 +00002358 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002359 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002360
Chris Lattner15090e12010-12-15 06:04:19 +00002361 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2362 // plus a shift.
2363 if (VT.isSimple() && !VT.isVector()) {
2364 MVT Simple = VT.getSimpleVT();
2365 unsigned SimpleSize = Simple.getSizeInBits();
2366 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2367 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2368 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2369 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2370 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2371 // Compute the high part as N1.
2372 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002373 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002374 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2375 // Compute the low part as N0.
2376 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2377 return CombineTo(N, Lo, Hi);
2378 }
2379 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002380
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002381 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002382}
2383
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002384SDValue DAGCombiner::visitSMULO(SDNode *N) {
2385 // (smulo x, 2) -> (saddo x, x)
2386 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2387 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002388 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002389 N->getOperand(0), N->getOperand(0));
2390
2391 return SDValue();
2392}
2393
2394SDValue DAGCombiner::visitUMULO(SDNode *N) {
2395 // (umulo x, 2) -> (uaddo x, x)
2396 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2397 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002398 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002399 N->getOperand(0), N->getOperand(0));
2400
2401 return SDValue();
2402}
2403
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002404SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2405 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002406 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002407
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002408 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002409}
2410
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002411SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2412 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002413 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002414
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002415 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002416}
2417
Chris Lattner8d6fc202006-05-05 05:51:50 +00002418/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2419/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002420SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2421 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002422 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002423 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002424
Dan Gohmandd5286d2010-01-14 03:08:49 +00002425 // Bail early if none of these transforms apply.
2426 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2427
Chris Lattner002ee912006-05-05 06:31:05 +00002428 // For each of OP in AND/OR/XOR:
2429 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2430 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2431 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002432 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002433 //
2434 // do not sink logical op inside of a vector extend, since it may combine
2435 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002436 EVT Op0VT = N0.getOperand(0).getValueType();
2437 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002438 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002439 // Avoid infinite looping with PromoteIntBinOp.
2440 (N0.getOpcode() == ISD::ANY_EXTEND &&
2441 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002442 (N0.getOpcode() == ISD::TRUNCATE &&
2443 (!TLI.isZExtFree(VT, Op0VT) ||
2444 !TLI.isTruncateFree(Op0VT, VT)) &&
2445 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002446 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002447 Op0VT == N1.getOperand(0).getValueType() &&
2448 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002449 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002450 N0.getOperand(0).getValueType(),
2451 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002452 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002453 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002454 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002455
Chris Lattner5ac42932006-05-05 06:10:43 +00002456 // For each of OP in SHL/SRL/SRA/AND...
2457 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2458 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2459 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002460 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002461 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002462 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002463 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002464 N0.getOperand(0).getValueType(),
2465 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002466 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002467 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002468 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002469 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002470
Nadav Rotemb0783502012-04-01 19:31:22 +00002471 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2472 // Only perform this optimization after type legalization and before
2473 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2474 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2475 // we don't want to undo this promotion.
2476 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2477 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002478 if ((N0.getOpcode() == ISD::BITCAST ||
2479 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2480 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002481 SDValue In0 = N0.getOperand(0);
2482 SDValue In1 = N1.getOperand(0);
2483 EVT In0Ty = In0.getValueType();
2484 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002485 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002486 // If both incoming values are integers, and the original types are the
2487 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002488 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002489 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2490 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002491 AddToWorkList(Op.getNode());
2492 return BC;
2493 }
2494 }
2495
2496 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2497 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2498 // If both shuffles use the same mask, and both shuffle within a single
2499 // vector, then it is worthwhile to move the swizzle after the operation.
2500 // The type-legalizer generates this pattern when loading illegal
2501 // vector types from memory. In many cases this allows additional shuffle
2502 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002503 // There are other cases where moving the shuffle after the xor/and/or
2504 // is profitable even if shuffles don't perform a swizzle.
2505 // If both shuffles use the same mask, and both shuffles have the same first
2506 // or second operand, then it might still be profitable to move the shuffle
2507 // after the xor/and/or operation.
2508 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002509 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2510 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002511
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002512 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002513 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002514
Nadav Rotemb0783502012-04-01 19:31:22 +00002515 // Check that both shuffles use the same mask. The masks are known to be of
2516 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002517 // Check also that shuffles have only one use to avoid introducing extra
2518 // instructions.
2519 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2520 SVN0->getMask().equals(SVN1->getMask())) {
2521 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002522
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002523 // Don't try to fold this node if it requires introducing a
2524 // build vector of all zeros that might be illegal at this stage.
2525 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2526 if (!LegalTypes)
2527 ShOp = DAG.getConstant(0, VT);
2528 else
2529 ShOp = SDValue();
2530 }
2531
2532 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2533 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2534 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2535 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2536 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2537 N0->getOperand(0), N1->getOperand(0));
2538 AddToWorkList(NewNode.getNode());
2539 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2540 &SVN0->getMask()[0]);
2541 }
2542
2543 // Don't try to fold this node if it requires introducing a
2544 // build vector of all zeros that might be illegal at this stage.
2545 ShOp = N0->getOperand(0);
2546 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2547 if (!LegalTypes)
2548 ShOp = DAG.getConstant(0, VT);
2549 else
2550 ShOp = SDValue();
2551 }
2552
2553 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2554 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2555 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2556 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2557 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2558 N0->getOperand(1), N1->getOperand(1));
2559 AddToWorkList(NewNode.getNode());
2560 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2561 &SVN0->getMask()[0]);
2562 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002563 }
2564 }
Craig Topper9c3da312012-04-09 07:19:09 +00002565
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002566 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002567}
2568
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002569SDValue DAGCombiner::visitAND(SDNode *N) {
2570 SDValue N0 = N->getOperand(0);
2571 SDValue N1 = N->getOperand(1);
2572 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002573 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2574 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002575 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002576 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002577
Dan Gohmana8665142007-06-25 16:23:39 +00002578 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002579 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002580 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002581 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002582
2583 // fold (and x, 0) -> 0, vector edition
2584 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2585 return N0;
2586 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2587 return N1;
2588
2589 // fold (and x, -1) -> x, vector edition
2590 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2591 return N1;
2592 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2593 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002594 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002595
Dan Gohman06563a82007-07-03 14:03:57 +00002596 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002597 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002598 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002599 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002600 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002601 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002602 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002603 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002604 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002605 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002606 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002607 return N0;
2608 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002609 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002610 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002611 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002612 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002613 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002614 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002615 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002616 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002617 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002618 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002619 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002620 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002621 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2622 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002623 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002624 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002625 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002626 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002627 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002628 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002629
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002630 // Replace uses of the AND with uses of the Zero extend node.
2631 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002632
Chris Lattner49beaf42006-02-02 07:17:31 +00002633 // We actually want to replace all uses of the any_extend with the
2634 // zero_extend, to avoid duplicating things. This will later cause this
2635 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002636 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002637 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002638 }
2639 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002640 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002641 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2642 // already be zero by virtue of the width of the base type of the load.
2643 //
2644 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2645 // more cases.
2646 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2647 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2648 N0.getOpcode() == ISD::LOAD) {
2649 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2650 N0 : N0.getOperand(0) );
2651
2652 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2653 // This can be a pure constant or a vector splat, in which case we treat the
2654 // vector as a scalar and use the splat value.
2655 APInt Constant = APInt::getNullValue(1);
2656 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2657 Constant = C->getAPIntValue();
2658 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2659 APInt SplatValue, SplatUndef;
2660 unsigned SplatBitSize;
2661 bool HasAnyUndefs;
2662 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2663 SplatBitSize, HasAnyUndefs);
2664 if (IsSplat) {
2665 // Undef bits can contribute to a possible optimisation if set, so
2666 // set them.
2667 SplatValue |= SplatUndef;
2668
2669 // The splat value may be something like "0x00FFFFFF", which means 0 for
2670 // the first vector value and FF for the rest, repeating. We need a mask
2671 // that will apply equally to all members of the vector, so AND all the
2672 // lanes of the constant together.
2673 EVT VT = Vector->getValueType(0);
2674 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002675
2676 // If the splat value has been compressed to a bitlength lower
2677 // than the size of the vector lane, we need to re-expand it to
2678 // the lane size.
2679 if (BitWidth > SplatBitSize)
2680 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2681 SplatBitSize < BitWidth;
2682 SplatBitSize = SplatBitSize * 2)
2683 SplatValue |= SplatValue.shl(SplatBitSize);
2684
James Molloy862fe492012-02-20 12:02:38 +00002685 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002686 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002687 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2688 }
2689 }
2690
2691 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2692 // actually legal and isn't going to get expanded, else this is a false
2693 // optimisation.
2694 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2695 Load->getMemoryVT());
2696
2697 // Resize the constant to the same size as the original memory access before
2698 // extension. If it is still the AllOnesValue then this AND is completely
2699 // unneeded.
2700 Constant =
2701 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2702
2703 bool B;
2704 switch (Load->getExtensionType()) {
2705 default: B = false; break;
2706 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2707 case ISD::ZEXTLOAD:
2708 case ISD::NON_EXTLOAD: B = true; break;
2709 }
2710
2711 if (B && Constant.isAllOnesValue()) {
2712 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2713 // preserve semantics once we get rid of the AND.
2714 SDValue NewLoad(Load, 0);
2715 if (Load->getExtensionType() == ISD::EXTLOAD) {
2716 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002717 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002718 Load->getChain(), Load->getBasePtr(),
2719 Load->getOffset(), Load->getMemoryVT(),
2720 Load->getMemOperand());
2721 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002722 if (Load->getNumValues() == 3) {
2723 // PRE/POST_INC loads have 3 values.
2724 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2725 NewLoad.getValue(2) };
2726 CombineTo(Load, To, 3, true);
2727 } else {
2728 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2729 }
James Molloy862fe492012-02-20 12:02:38 +00002730 }
2731
2732 // Fold the AND away, taking care not to fold to the old load node if we
2733 // replaced it.
2734 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2735
2736 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2737 }
2738 }
Nate Begeman049b7482005-09-09 19:49:52 +00002739 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2740 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2741 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2742 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002743
Nate Begeman049b7482005-09-09 19:49:52 +00002744 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002745 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002746 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002747 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002748 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002749 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002750 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002751 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002752 }
Bill Wendling86171912009-01-30 20:43:18 +00002753 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002754 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002755 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002756 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002757 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002758 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002759 }
Bill Wendling86171912009-01-30 20:43:18 +00002760 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002761 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002762 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002763 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002764 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002765 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002766 }
2767 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002768 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2769 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2770 Op0 == Op1 && LL.getValueType().isInteger() &&
2771 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2772 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2773 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2774 cast<ConstantSDNode>(RR)->isNullValue()))) {
2775 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2776 LL, DAG.getConstant(1, LL.getValueType()));
2777 AddToWorkList(ADDNode.getNode());
2778 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2779 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2780 }
Nate Begeman049b7482005-09-09 19:49:52 +00002781 // canonicalize equivalent to ll == rl
2782 if (LL == RR && LR == RL) {
2783 Op1 = ISD::getSetCCSwappedOperands(Op1);
2784 std::swap(RL, RR);
2785 }
2786 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002787 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002788 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002789 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002790 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002791 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2792 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002793 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002794 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002795 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002796 }
2797 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002798
Bill Wendling86171912009-01-30 20:43:18 +00002799 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002800 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002801 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002802 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002803 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002804
Nate Begemandc7bba92006-02-03 22:24:05 +00002805 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2806 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002807 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002808 SimplifyDemandedBits(SDValue(N, 0)))
2809 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002810
Nate Begeman02b23c62005-10-13 03:11:28 +00002811 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002812 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002813 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002814 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002815 // If we zero all the possible extended bits, then we can turn this into
2816 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002817 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002818 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002819 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002820 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002821 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002822 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002823 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002824 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002825 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002826 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002827 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002828 }
2829 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002830 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002831 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002832 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002833 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002834 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002835 // If we zero all the possible extended bits, then we can turn this into
2836 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002837 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002838 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002839 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002840 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002841 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002842 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002843 LN0->getChain(), LN0->getBasePtr(),
2844 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002845 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002846 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002847 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002848 }
2849 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002850
Chris Lattnerf0032b32006-02-28 06:49:37 +00002851 // fold (and (load x), 255) -> (zextload x, i8)
2852 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002853 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2854 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2855 (N0.getOpcode() == ISD::ANY_EXTEND &&
2856 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2857 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2858 LoadSDNode *LN0 = HasAnyExt
2859 ? cast<LoadSDNode>(N0.getOperand(0))
2860 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002861 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002862 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002863 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002864 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2865 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2866 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002867
Evan Cheng166a4e62010-01-06 19:38:29 +00002868 if (ExtVT == LoadedVT &&
2869 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002870 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002871
2872 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002873 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002874 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2875 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002876 AddToWorkList(N);
2877 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2878 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2879 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002880
Chris Lattner88de3842010-01-07 21:53:27 +00002881 // Do not change the width of a volatile load.
2882 // Do not generate loads of non-round integer types since these can
2883 // be expensive (and would be wrong if the type is not byte sized).
2884 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2885 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2886 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002887
Chris Lattner88de3842010-01-07 21:53:27 +00002888 unsigned Alignment = LN0->getAlignment();
2889 SDValue NewPtr = LN0->getBasePtr();
2890
2891 // For big endian targets, we need to add an offset to the pointer
2892 // to load the correct bytes. For little endian systems, we merely
2893 // need to read fewer bytes from the same pointer.
2894 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002895 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2896 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2897 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002898 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002899 NewPtr, DAG.getConstant(PtrOff, PtrType));
2900 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002901 }
Chris Lattner88de3842010-01-07 21:53:27 +00002902
2903 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002904
Chris Lattner88de3842010-01-07 21:53:27 +00002905 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2906 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002907 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002908 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002909 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002910 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002911 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002912 AddToWorkList(N);
2913 CombineTo(LN0, Load, Load.getValue(1));
2914 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002915 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002916 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002917 }
2918 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002919
Evan Chenge6a3b032012-07-17 18:54:11 +00002920 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2921 VT.getSizeInBits() <= 64) {
2922 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2923 APInt ADDC = ADDI->getAPIntValue();
2924 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2925 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2926 // immediate for an add, but it is legal if its top c2 bits are set,
2927 // transform the ADD so the immediate doesn't need to be materialized
2928 // in a register.
2929 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2930 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2931 SRLI->getZExtValue());
2932 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2933 ADDC |= Mask;
2934 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2935 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002936 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002937 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2938 CombineTo(N0.getNode(), NewAdd);
2939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2940 }
2941 }
2942 }
2943 }
2944 }
2945 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002946
Tim Northover819bfb52013-08-27 13:46:45 +00002947 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2948 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2949 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2950 N0.getOperand(1), false);
2951 if (BSwap.getNode())
2952 return BSwap;
2953 }
2954
Evan Chengf1005572010-04-28 07:10:39 +00002955 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002956}
2957
Evan Cheng4c0bd962011-06-21 06:01:08 +00002958/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2959///
2960SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2961 bool DemandHighBits) {
2962 if (!LegalOperations)
2963 return SDValue();
2964
2965 EVT VT = N->getValueType(0);
2966 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2967 return SDValue();
2968 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2969 return SDValue();
2970
2971 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2972 bool LookPassAnd0 = false;
2973 bool LookPassAnd1 = false;
2974 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2975 std::swap(N0, N1);
2976 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2977 std::swap(N0, N1);
2978 if (N0.getOpcode() == ISD::AND) {
2979 if (!N0.getNode()->hasOneUse())
2980 return SDValue();
2981 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2982 if (!N01C || N01C->getZExtValue() != 0xFF00)
2983 return SDValue();
2984 N0 = N0.getOperand(0);
2985 LookPassAnd0 = true;
2986 }
2987
2988 if (N1.getOpcode() == ISD::AND) {
2989 if (!N1.getNode()->hasOneUse())
2990 return SDValue();
2991 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2992 if (!N11C || N11C->getZExtValue() != 0xFF)
2993 return SDValue();
2994 N1 = N1.getOperand(0);
2995 LookPassAnd1 = true;
2996 }
2997
2998 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2999 std::swap(N0, N1);
3000 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3001 return SDValue();
3002 if (!N0.getNode()->hasOneUse() ||
3003 !N1.getNode()->hasOneUse())
3004 return SDValue();
3005
3006 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3007 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3008 if (!N01C || !N11C)
3009 return SDValue();
3010 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3011 return SDValue();
3012
3013 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3014 SDValue N00 = N0->getOperand(0);
3015 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3016 if (!N00.getNode()->hasOneUse())
3017 return SDValue();
3018 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3019 if (!N001C || N001C->getZExtValue() != 0xFF)
3020 return SDValue();
3021 N00 = N00.getOperand(0);
3022 LookPassAnd0 = true;
3023 }
3024
3025 SDValue N10 = N1->getOperand(0);
3026 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3027 if (!N10.getNode()->hasOneUse())
3028 return SDValue();
3029 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3030 if (!N101C || N101C->getZExtValue() != 0xFF00)
3031 return SDValue();
3032 N10 = N10.getOperand(0);
3033 LookPassAnd1 = true;
3034 }
3035
3036 if (N00 != N10)
3037 return SDValue();
3038
Tim Northover819bfb52013-08-27 13:46:45 +00003039 // Make sure everything beyond the low halfword gets set to zero since the SRL
3040 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003041 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003042 if (DemandHighBits && OpSizeInBits > 16) {
3043 // If the left-shift isn't masked out then the only way this is a bswap is
3044 // if all bits beyond the low 8 are 0. In that case the entire pattern
3045 // reduces to a left shift anyway: leave it for other parts of the combiner.
3046 if (!LookPassAnd0)
3047 return SDValue();
3048
3049 // However, if the right shift isn't masked out then it might be because
3050 // it's not needed. See if we can spot that too.
3051 if (!LookPassAnd1 &&
3052 !DAG.MaskedValueIsZero(
3053 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3054 return SDValue();
3055 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003056
Andrew Trickef9de2a2013-05-25 02:42:55 +00003057 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003058 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003059 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003060 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3061 return Res;
3062}
3063
3064/// isBSwapHWordElement - Return true if the specified node is an element
3065/// that makes up a 32-bit packed halfword byteswap. i.e.
3066/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003067static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003068 if (!N.getNode()->hasOneUse())
3069 return false;
3070
3071 unsigned Opc = N.getOpcode();
3072 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3073 return false;
3074
3075 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3076 if (!N1C)
3077 return false;
3078
3079 unsigned Num;
3080 switch (N1C->getZExtValue()) {
3081 default:
3082 return false;
3083 case 0xFF: Num = 0; break;
3084 case 0xFF00: Num = 1; break;
3085 case 0xFF0000: Num = 2; break;
3086 case 0xFF000000: Num = 3; break;
3087 }
3088
3089 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3090 SDValue N0 = N.getOperand(0);
3091 if (Opc == ISD::AND) {
3092 if (Num == 0 || Num == 2) {
3093 // (x >> 8) & 0xff
3094 // (x >> 8) & 0xff0000
3095 if (N0.getOpcode() != ISD::SRL)
3096 return false;
3097 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3098 if (!C || C->getZExtValue() != 8)
3099 return false;
3100 } else {
3101 // (x << 8) & 0xff00
3102 // (x << 8) & 0xff000000
3103 if (N0.getOpcode() != ISD::SHL)
3104 return false;
3105 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3106 if (!C || C->getZExtValue() != 8)
3107 return false;
3108 }
3109 } else if (Opc == ISD::SHL) {
3110 // (x & 0xff) << 8
3111 // (x & 0xff0000) << 8
3112 if (Num != 0 && Num != 2)
3113 return false;
3114 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3115 if (!C || C->getZExtValue() != 8)
3116 return false;
3117 } else { // Opc == ISD::SRL
3118 // (x & 0xff00) >> 8
3119 // (x & 0xff000000) >> 8
3120 if (Num != 1 && Num != 3)
3121 return false;
3122 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3123 if (!C || C->getZExtValue() != 8)
3124 return false;
3125 }
3126
3127 if (Parts[Num])
3128 return false;
3129
3130 Parts[Num] = N0.getOperand(0).getNode();
3131 return true;
3132}
3133
3134/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3135/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3136/// => (rotl (bswap x), 16)
3137SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3138 if (!LegalOperations)
3139 return SDValue();
3140
3141 EVT VT = N->getValueType(0);
3142 if (VT != MVT::i32)
3143 return SDValue();
3144 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3145 return SDValue();
3146
Craig Topperc0196b12014-04-14 00:51:57 +00003147 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003148 // Look for either
3149 // (or (or (and), (and)), (or (and), (and)))
3150 // (or (or (or (and), (and)), (and)), (and))
3151 if (N0.getOpcode() != ISD::OR)
3152 return SDValue();
3153 SDValue N00 = N0.getOperand(0);
3154 SDValue N01 = N0.getOperand(1);
3155
Evan Chengbf0baa92012-12-13 01:34:32 +00003156 if (N1.getOpcode() == ISD::OR &&
3157 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003158 // (or (or (and), (and)), (or (and), (and)))
3159 SDValue N000 = N00.getOperand(0);
3160 if (!isBSwapHWordElement(N000, Parts))
3161 return SDValue();
3162
3163 SDValue N001 = N00.getOperand(1);
3164 if (!isBSwapHWordElement(N001, Parts))
3165 return SDValue();
3166 SDValue N010 = N01.getOperand(0);
3167 if (!isBSwapHWordElement(N010, Parts))
3168 return SDValue();
3169 SDValue N011 = N01.getOperand(1);
3170 if (!isBSwapHWordElement(N011, Parts))
3171 return SDValue();
3172 } else {
3173 // (or (or (or (and), (and)), (and)), (and))
3174 if (!isBSwapHWordElement(N1, Parts))
3175 return SDValue();
3176 if (!isBSwapHWordElement(N01, Parts))
3177 return SDValue();
3178 if (N00.getOpcode() != ISD::OR)
3179 return SDValue();
3180 SDValue N000 = N00.getOperand(0);
3181 if (!isBSwapHWordElement(N000, Parts))
3182 return SDValue();
3183 SDValue N001 = N00.getOperand(1);
3184 if (!isBSwapHWordElement(N001, Parts))
3185 return SDValue();
3186 }
3187
3188 // Make sure the parts are all coming from the same node.
3189 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3190 return SDValue();
3191
Andrew Trickef9de2a2013-05-25 02:42:55 +00003192 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003193 SDValue(Parts[0],0));
3194
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003195 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003196 // do (x << 16) | (x >> 16).
3197 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3198 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003199 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003200 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003201 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3202 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3203 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3204 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003205}
3206
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003207SDValue DAGCombiner::visitOR(SDNode *N) {
3208 SDValue N0 = N->getOperand(0);
3209 SDValue N1 = N->getOperand(1);
3210 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003211 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3212 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003213 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003214
Dan Gohmana8665142007-06-25 16:23:39 +00003215 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003216 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003217 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003218 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003219
3220 // fold (or x, 0) -> x, vector edition
3221 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3222 return N1;
3223 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3224 return N0;
3225
3226 // fold (or x, -1) -> -1, vector edition
3227 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3228 return N0;
3229 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3230 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003231
3232 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3233 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3234 // Do this only if the resulting shuffle is legal.
3235 if (isa<ShuffleVectorSDNode>(N0) &&
3236 isa<ShuffleVectorSDNode>(N1) &&
3237 N0->getOperand(1) == N1->getOperand(1) &&
3238 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3239 bool CanFold = true;
3240 unsigned NumElts = VT.getVectorNumElements();
3241 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3242 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3243 // We construct two shuffle masks:
3244 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3245 // and N1 as the second operand.
3246 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3247 // and N0 as the second operand.
3248 // We do this because OR is commutable and therefore there might be
3249 // two ways to fold this node into a shuffle.
3250 SmallVector<int,4> Mask1;
3251 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003252
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003253 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3254 int M0 = SV0->getMaskElt(i);
3255 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003256
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003257 // Both shuffle indexes are undef. Propagate Undef.
3258 if (M0 < 0 && M1 < 0) {
3259 Mask1.push_back(M0);
3260 Mask2.push_back(M0);
3261 continue;
3262 }
3263
3264 if (M0 < 0 || M1 < 0 ||
3265 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3266 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3267 CanFold = false;
3268 break;
3269 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003270
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003271 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3272 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3273 }
3274
3275 if (CanFold) {
3276 // Fold this sequence only if the resulting shuffle is 'legal'.
3277 if (TLI.isShuffleMaskLegal(Mask1, VT))
3278 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3279 N1->getOperand(0), &Mask1[0]);
3280 if (TLI.isShuffleMaskLegal(Mask2, VT))
3281 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3282 N0->getOperand(0), &Mask2[0]);
3283 }
3284 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003285 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003286
Dan Gohman06563a82007-07-03 14:03:57 +00003287 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003288 if (!LegalOperations &&
3289 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003290 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3291 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3292 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003293 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003294 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003295 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003296 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003297 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003298 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003299 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003300 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003301 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003302 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003303 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003304 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003305 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003306 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003307 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003308
3309 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3310 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003311 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003312 return BSwap;
3313 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003314 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003315 return BSwap;
3316
Nate Begeman22e251a2006-02-03 06:46:56 +00003317 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003318 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003319 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003320 return ROR;
3321 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003322 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003323 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003324 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003325 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003326 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3327 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3328 if (!COR.getNode())
3329 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003330 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3331 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003332 N0.getOperand(0), N1), COR);
3333 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003334 }
Nate Begeman049b7482005-09-09 19:49:52 +00003335 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3336 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3337 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3338 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003339
Nate Begeman049b7482005-09-09 19:49:52 +00003340 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003341 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003342 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3343 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003344 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003345 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003346 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003347 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003348 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003349 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003350 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003351 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3352 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003353 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003354 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003355 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003356 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003357 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003358 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003359 }
3360 }
3361 // canonicalize equivalent to ll == rl
3362 if (LL == RR && LR == RL) {
3363 Op1 = ISD::getSetCCSwappedOperands(Op1);
3364 std::swap(RL, RR);
3365 }
3366 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003367 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003368 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003369 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003370 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003371 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3372 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003373 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003374 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003375 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003376 }
3377 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003378
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003379 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003380 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003381 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003382 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003383 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003384
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003385 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003386 if (N0.getOpcode() == ISD::AND &&
3387 N1.getOpcode() == ISD::AND &&
3388 N0.getOperand(1).getOpcode() == ISD::Constant &&
3389 N1.getOperand(1).getOpcode() == ISD::Constant &&
3390 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003391 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003392 // We can only do this xform if we know that bits from X that are set in C2
3393 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003394 const APInt &LHSMask =
3395 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3396 const APInt &RHSMask =
3397 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003398
Dan Gohman309d3d52007-06-22 14:59:07 +00003399 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3400 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003401 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003402 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003403 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003404 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003405 }
3406 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003407
Chris Lattner97614c82006-09-14 20:50:57 +00003408 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003409 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003410 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003411
Dan Gohman600f62b2010-06-24 14:30:44 +00003412 // Simplify the operands using demanded-bits information.
3413 if (!VT.isVector() &&
3414 SimplifyDemandedBits(SDValue(N, 0)))
3415 return SDValue(N, 0);
3416
Evan Chengf1005572010-04-28 07:10:39 +00003417 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003418}
3419
Chris Lattner97614c82006-09-14 20:50:57 +00003420/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003421static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003422 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003423 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003424 Mask = Op.getOperand(1);
3425 Op = Op.getOperand(0);
3426 } else {
3427 return false;
3428 }
3429 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003430
Chris Lattner97614c82006-09-14 20:50:57 +00003431 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3432 Shift = Op;
3433 return true;
3434 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003435
Scott Michelcf0da6c2009-02-17 22:15:04 +00003436 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003437}
3438
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003439// Return true if we can prove that, whenever Neg and Pos are both in the
3440// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003441// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3442//
3443// (or (shift1 X, Neg), (shift2 X, Pos))
3444//
Adam Nemetc6553a82014-03-07 23:56:24 +00003445// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3446// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3447// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003448static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003449 // If OpSize is a power of 2 then:
3450 //
3451 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3452 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3453 //
3454 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3455 // for the stronger condition:
3456 //
3457 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3458 //
3459 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3460 // we can just replace Neg with Neg' for the rest of the function.
3461 //
3462 // In other cases we check for the even stronger condition:
3463 //
3464 // Neg == OpSize - Pos [B]
3465 //
3466 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3467 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003468 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003469 // We could actually use [A] whenever OpSize is a power of 2, but the
3470 // only extra cases that it would match are those uninteresting ones
3471 // where Neg and Pos are never in range at the same time. E.g. for
3472 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3473 // as well as (sub 32, Pos), but:
3474 //
3475 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3476 //
3477 // always invokes undefined behavior for 32-bit X.
3478 //
3479 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003480 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003481 if (Neg.getOpcode() == ISD::AND &&
3482 isPowerOf2_64(OpSize) &&
3483 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3484 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3485 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003486 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003487 }
3488
Richard Sandiford0f264db2014-01-09 10:49:40 +00003489 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3490 if (Neg.getOpcode() != ISD::SUB)
3491 return 0;
3492 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3493 if (!NegC)
3494 return 0;
3495 SDValue NegOp1 = Neg.getOperand(1);
3496
Adam Nemet5117f5d2014-03-07 23:56:28 +00003497 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3498 // Pos'. The truncation is redundant for the purpose of the equality.
3499 if (MaskLoBits &&
3500 Pos.getOpcode() == ISD::AND &&
3501 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3502 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3503 Pos = Pos.getOperand(0);
3504
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003505 // The condition we need is now:
3506 //
3507 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3508 //
3509 // If NegOp1 == Pos then we need:
3510 //
3511 // OpSize & Mask == NegC & Mask
3512 //
3513 // (because "x & Mask" is a truncation and distributes through subtraction).
3514 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003515 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003516 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003517 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3518 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003519 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003520 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3521 //
3522 // which, again because "x & Mask" is a truncation, becomes:
3523 //
3524 // NegC & Mask == (OpSize - PosC) & Mask
3525 // OpSize & Mask == (NegC + PosC) & Mask
3526 else if (Pos.getOpcode() == ISD::ADD &&
3527 Pos.getOperand(0) == NegOp1 &&
3528 Pos.getOperand(1).getOpcode() == ISD::Constant)
3529 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3530 NegC->getAPIntValue());
3531 else
3532 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003533
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003534 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003535 if (MaskLoBits)
3536 // Opsize & Mask is 0 since Mask is Opsize - 1.
3537 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003538 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003539}
3540
Richard Sandiford95c864d2014-01-08 15:40:47 +00003541// A subroutine of MatchRotate used once we have found an OR of two opposite
3542// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3543// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3544// former being preferred if supported. InnerPos and InnerNeg are Pos and
3545// Neg with outer conversions stripped away.
3546SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3547 SDValue Neg, SDValue InnerPos,
3548 SDValue InnerNeg, unsigned PosOpcode,
3549 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003550 // fold (or (shl x, (*ext y)),
3551 // (srl x, (*ext (sub 32, y)))) ->
3552 // (rotl x, y) or (rotr x, (sub 32, y))
3553 //
3554 // fold (or (shl x, (*ext (sub 32, y))),
3555 // (srl x, (*ext y))) ->
3556 // (rotr x, y) or (rotl x, (sub 32, y))
3557 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003558 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003559 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3560 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3561 HasPos ? Pos : Neg).getNode();
3562 }
3563
Craig Topperc0196b12014-04-14 00:51:57 +00003564 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003565}
3566
Chris Lattner97614c82006-09-14 20:50:57 +00003567// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3568// idioms for rotate, and if the target supports rotation instructions, generate
3569// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003570SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003571 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003572 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003573 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003574
3575 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003576 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3577 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003578 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003579
Chris Lattner97614c82006-09-14 20:50:57 +00003580 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003581 SDValue LHSShift; // The shift.
3582 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003583 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003584 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003585
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003586 SDValue RHSShift; // The shift.
3587 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003588 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003589 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003590
Chris Lattner97614c82006-09-14 20:50:57 +00003591 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003592 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003593
3594 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003595 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003596
Chris Lattner97614c82006-09-14 20:50:57 +00003597 // Canonicalize shl to left side in a shl/srl pair.
3598 if (RHSShift.getOpcode() == ISD::SHL) {
3599 std::swap(LHS, RHS);
3600 std::swap(LHSShift, RHSShift);
3601 std::swap(LHSMask , RHSMask );
3602 }
3603
Duncan Sands13237ac2008-06-06 12:08:01 +00003604 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003605 SDValue LHSShiftArg = LHSShift.getOperand(0);
3606 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003607 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003608 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003609
3610 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3611 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003612 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3613 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003614 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3615 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003616 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003617 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003618
Craig Topper65161fa2012-09-29 06:54:22 +00003619 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3620 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003621
Chris Lattner97614c82006-09-14 20:50:57 +00003622 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003623 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003624 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003625
Gabor Greiff304a7a2008-08-28 21:40:38 +00003626 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003627 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3628 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003629 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003630 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003631 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3632 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003633 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003634
Bill Wendling35972a92009-01-30 21:14:50 +00003635 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003636 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003637
Gabor Greiff304a7a2008-08-28 21:40:38 +00003638 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003639 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003640
Chris Lattner97614c82006-09-14 20:50:57 +00003641 // If there is a mask here, and we have a variable shift, we can't be sure
3642 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003643 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003644 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003645
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003646 // If the shift amount is sign/zext/any-extended just peel it off.
3647 SDValue LExtOp0 = LHSShiftAmt;
3648 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003649 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3650 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3651 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3652 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3653 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3654 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3655 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3656 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003657 LExtOp0 = LHSShiftAmt.getOperand(0);
3658 RExtOp0 = RHSShiftAmt.getOperand(0);
3659 }
3660
Richard Sandiford95c864d2014-01-08 15:40:47 +00003661 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3662 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3663 if (TryL)
3664 return TryL;
3665
3666 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3667 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3668 if (TryR)
3669 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003670
Craig Topperc0196b12014-04-14 00:51:57 +00003671 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003672}
3673
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003674SDValue DAGCombiner::visitXOR(SDNode *N) {
3675 SDValue N0 = N->getOperand(0);
3676 SDValue N1 = N->getOperand(1);
3677 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003678 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3679 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003680 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003681
Dan Gohmana8665142007-06-25 16:23:39 +00003682 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003683 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003684 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003685 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003686
3687 // fold (xor x, 0) -> x, vector edition
3688 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3689 return N1;
3690 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3691 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003692 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003693
Evan Chengdf1690d2008-03-25 20:08:07 +00003694 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3695 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3696 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003697 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003698 if (N0.getOpcode() == ISD::UNDEF)
3699 return N0;
3700 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003701 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003702 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003703 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003704 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003705 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003706 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003707 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003708 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003709 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003710 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003711 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003712 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003713 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003714 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003715
Nate Begeman21158fc2005-09-01 00:19:25 +00003716 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003717 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003718 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003719 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3720 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003721
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003722 if (!LegalOperations ||
3723 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003724 switch (N0.getOpcode()) {
3725 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003726 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003727 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003728 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003729 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003730 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003731 N0.getOperand(3), NotCC);
3732 }
3733 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003734 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003735
Chris Lattner58c227b2007-09-10 21:39:07 +00003736 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003737 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003738 N0.getNode()->hasOneUse() &&
3739 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003740 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003741 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003742 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003743 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003744 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003745 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003746
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003747 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003748 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003749 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003750 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003751 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3752 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003753 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3754 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003755 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003756 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003757 }
3758 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003759 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003760 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003761 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003762 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003763 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3764 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003765 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3766 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003767 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003768 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003769 }
3770 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003771 // fold (xor (and x, y), y) -> (and (not x), y)
3772 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003773 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003774 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003775 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003776 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003777 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003778 }
Bill Wendling35972a92009-01-30 21:14:50 +00003779 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003780 if (N1C && N0.getOpcode() == ISD::XOR) {
3781 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3782 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3783 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003784 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003785 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003786 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003787 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003788 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003789 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003790 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003791 }
3792 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003793 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003794 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003795
Chris Lattner8d6fc202006-05-05 05:51:50 +00003796 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3797 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003798 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003799 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003800 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003801
Chris Lattner098c01e2006-04-08 04:15:24 +00003802 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003803 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003804 SimplifyDemandedBits(SDValue(N, 0)))
3805 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003806
Evan Chengf1005572010-04-28 07:10:39 +00003807 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003808}
3809
Chris Lattner7c709a52007-12-06 07:33:36 +00003810/// visitShiftByConstant - Handle transforms common to the three shifts, when
3811/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003812SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003813 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003814 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003815 return SDValue();
3816
Gabor Greiff304a7a2008-08-28 21:40:38 +00003817 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003818 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003819
Chris Lattner7c709a52007-12-06 07:33:36 +00003820 // We want to pull some binops through shifts, so that we have (and (shift))
3821 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3822 // thing happens with address calculations, so it's important to canonicalize
3823 // it.
3824 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003825
Chris Lattner7c709a52007-12-06 07:33:36 +00003826 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003827 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003828 case ISD::OR:
3829 case ISD::XOR:
3830 HighBitSet = false; // We can only transform sra if the high bit is clear.
3831 break;
3832 case ISD::AND:
3833 HighBitSet = true; // We can only transform sra if the high bit is set.
3834 break;
3835 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003836 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003837 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003838 HighBitSet = false; // We can only transform sra if the high bit is clear.
3839 break;
3840 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003841
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003842 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003843 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003844 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003845
3846 // FIXME: disable this unless the input to the binop is a shift by a constant.
3847 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003848 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003849 // void foo(int *X, int i) { X[i & 1235] = 1; }
3850 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003851 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003852 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003853 BinOpLHSVal->getOpcode() != ISD::SRA &&
3854 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3855 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003856 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003857
Owen Anderson53aa7a92009-08-10 22:56:29 +00003858 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003859
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003860 // If this is a signed shift right, and the high bit is modified by the
3861 // logical operation, do not perform the transformation. The highBitSet
3862 // boolean indicates the value of the high bit of the constant which would
3863 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003864 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003865 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3866 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003867 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003868 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003869
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003870 if (!TLI.isDesirableToCommuteWithShift(LHS))
3871 return SDValue();
3872
Chris Lattner7c709a52007-12-06 07:33:36 +00003873 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003874 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003875 N->getValueType(0),
3876 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003877 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003878
3879 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003880 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003881 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003882 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003883
3884 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003885 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003886}
3887
Adam Nemet67483892014-03-04 23:28:31 +00003888SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3889 assert(N->getOpcode() == ISD::TRUNCATE);
3890 assert(N->getOperand(0).getOpcode() == ISD::AND);
3891
3892 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3893 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3894 SDValue N01 = N->getOperand(0).getOperand(1);
3895
Matt Arsenault985b9de2014-03-17 18:58:01 +00003896 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003897 EVT TruncVT = N->getValueType(0);
3898 SDValue N00 = N->getOperand(0).getOperand(0);
3899 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003900 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003901
3902 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3903 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3904 DAG.getConstant(TruncC, TruncVT));
3905 }
3906 }
3907
3908 return SDValue();
3909}
Adam Nemet7f928f12014-03-07 23:56:30 +00003910
3911SDValue DAGCombiner::visitRotate(SDNode *N) {
3912 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3913 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3914 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3915 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3916 if (NewOp1.getNode())
3917 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3918 N->getOperand(0), NewOp1);
3919 }
3920 return SDValue();
3921}
3922
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003923SDValue DAGCombiner::visitSHL(SDNode *N) {
3924 SDValue N0 = N->getOperand(0);
3925 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003926 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3927 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003928 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003929 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003930
Daniel Sandersa1840d22013-11-11 17:23:41 +00003931 // fold vector ops
3932 if (VT.isVector()) {
3933 SDValue FoldedVOp = SimplifyVBinOp(N);
3934 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003935
3936 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3937 // If setcc produces all-one true value then:
3938 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003939 if (N1CV && N1CV->isConstant()) {
3940 if (N0.getOpcode() == ISD::AND &&
3941 TLI.getBooleanContents(true) ==
3942 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3943 SDValue N00 = N0->getOperand(0);
3944 SDValue N01 = N0->getOperand(1);
3945 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003946
Matt Arsenault985b9de2014-03-17 18:58:01 +00003947 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3948 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3949 if (C.getNode())
3950 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3951 }
3952 } else {
3953 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003954 }
3955 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003956 }
3957
Nate Begeman21158fc2005-09-01 00:19:25 +00003958 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003959 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003960 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003961 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003962 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003963 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003964 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003965 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003966 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003967 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003968 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003969 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003970 // fold (shl undef, x) -> 0
3971 if (N0.getOpcode() == ISD::UNDEF)
3972 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003973 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003974 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003975 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003976 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003977 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003978 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00003979 N1.getOperand(0).getOpcode() == ISD::AND) {
3980 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3981 if (NewOp1.getNode())
3982 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003983 }
3984
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003985 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3986 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003987
3988 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00003989 if (N1C && N0.getOpcode() == ISD::SHL) {
3990 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3991 uint64_t c1 = N0C1->getZExtValue();
3992 uint64_t c2 = N1C->getZExtValue();
3993 if (c1 + c2 >= OpSizeInBits)
3994 return DAG.getConstant(0, VT);
3995 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3996 DAG.getConstant(c1 + c2, N1.getValueType()));
3997 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003998 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00003999
4000 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4001 // For this to be valid, the second form must not preserve any of the bits
4002 // that are shifted out by the inner shift in the first form. This means
4003 // the outer shift size must be >= the number of bits added by the ext.
4004 // As a corollary, we don't care what kind of ext it is.
4005 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4006 N0.getOpcode() == ISD::ANY_EXTEND ||
4007 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004008 N0.getOperand(0).getOpcode() == ISD::SHL) {
4009 SDValue N0Op0 = N0.getOperand(0);
4010 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4011 uint64_t c1 = N0Op0C1->getZExtValue();
4012 uint64_t c2 = N1C->getZExtValue();
4013 EVT InnerShiftVT = N0Op0.getValueType();
4014 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4015 if (c2 >= OpSizeInBits - InnerShiftSize) {
4016 if (c1 + c2 >= OpSizeInBits)
4017 return DAG.getConstant(0, VT);
4018 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4019 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4020 N0Op0->getOperand(0)),
4021 DAG.getConstant(c1 + c2, N1.getValueType()));
4022 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004023 }
4024 }
4025
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004026 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4027 // Only fold this if the inner zext has no other uses to avoid increasing
4028 // the total number of instructions.
4029 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004030 N0.getOperand(0).getOpcode() == ISD::SRL) {
4031 SDValue N0Op0 = N0.getOperand(0);
4032 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4033 uint64_t c1 = N0Op0C1->getZExtValue();
4034 if (c1 < VT.getScalarSizeInBits()) {
4035 uint64_t c2 = N1C->getZExtValue();
4036 if (c1 == c2) {
4037 SDValue NewOp0 = N0.getOperand(0);
4038 EVT CountVT = NewOp0.getOperand(1).getValueType();
4039 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4040 NewOp0, DAG.getConstant(c2, CountVT));
4041 AddToWorkList(NewSHL.getNode());
4042 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4043 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004044 }
4045 }
4046 }
4047
Eli Friedman1877ac92011-06-09 22:14:44 +00004048 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4049 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004050 // Only fold this if the inner shift has no other uses -- if it does, folding
4051 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004052 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4053 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4054 uint64_t c1 = N0C1->getZExtValue();
4055 if (c1 < OpSizeInBits) {
4056 uint64_t c2 = N1C->getZExtValue();
4057 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4058 SDValue Shift;
4059 if (c2 > c1) {
4060 Mask = Mask.shl(c2 - c1);
4061 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4062 DAG.getConstant(c2 - c1, N1.getValueType()));
4063 } else {
4064 Mask = Mask.lshr(c1 - c2);
4065 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4066 DAG.getConstant(c1 - c2, N1.getValueType()));
4067 }
4068 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4069 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004070 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004071 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004072 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004073 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004074 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004075 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004076 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004077 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4078 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004079 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004080 HiBitsMask);
4081 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004082
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004083 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004084 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004085 if (NewSHL.getNode())
4086 return NewSHL;
4087 }
4088
Evan Chengf1005572010-04-28 07:10:39 +00004089 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004090}
4091
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004092SDValue DAGCombiner::visitSRA(SDNode *N) {
4093 SDValue N0 = N->getOperand(0);
4094 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004095 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004097 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004098 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004099
Daniel Sandersa1840d22013-11-11 17:23:41 +00004100 // fold vector ops
4101 if (VT.isVector()) {
4102 SDValue FoldedVOp = SimplifyVBinOp(N);
4103 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004104
4105 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004106 }
4107
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004108 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004109 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004110 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004111 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004112 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004113 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004114 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004115 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004116 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004117 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004118 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004119 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004120 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004121 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004122 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004123 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4124 // sext_inreg.
4125 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004126 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004127 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4128 if (VT.isVector())
4129 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4130 ExtVT, VT.getVectorNumElements());
4131 if ((!LegalOperations ||
4132 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004133 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004134 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004135 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004136
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004137 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004138 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004139 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004140 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004141 if (Sum >= OpSizeInBits)
4142 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004143 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004144 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004145 }
4146 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004147
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004148 // fold (sra (shl X, m), (sub result_size, n))
4149 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004150 // result_size - n != m.
4151 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004152 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004153 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004154 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004155 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4156 if (N01C) {
4157 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004158 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004159 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4160
4161 if (VT.isVector())
4162 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4163
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004164 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004165 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004166
Scott Michelcf0da6c2009-02-17 22:15:04 +00004167 // If the shift is not a no-op (in which case this should be just a sign
4168 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004169 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004170 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004171 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004172 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4173 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004174 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004175
Owen Andersonb2c80da2011-02-25 21:41:48 +00004176 SDValue Amt = DAG.getConstant(ShiftAmt,
4177 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004178 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004179 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004180 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004181 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004182 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004183 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004184 }
4185 }
4186 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004187
Duncan Sands3ed76882009-02-01 18:06:53 +00004188 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004189 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004190 N1.getOperand(0).getOpcode() == ISD::AND) {
4191 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4192 if (NewOp1.getNode())
4193 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004194 }
4195
Matt Arsenault985b9de2014-03-17 18:58:01 +00004196 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004197 // if c1 is equal to the number of bits the trunc removes
4198 if (N0.getOpcode() == ISD::TRUNCATE &&
4199 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4200 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4201 N0.getOperand(0).hasOneUse() &&
4202 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004203 N1C) {
4204 SDValue N0Op0 = N0.getOperand(0);
4205 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4206 unsigned LargeShiftVal = LargeShift->getZExtValue();
4207 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004208
Matt Arsenault985b9de2014-03-17 18:58:01 +00004209 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4210 SDValue Amt =
4211 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4212 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4213 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4214 N0Op0.getOperand(0), Amt);
4215 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4216 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004217 }
4218 }
4219
Scott Michelcf0da6c2009-02-17 22:15:04 +00004220 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004221 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4222 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004223
4224
Nate Begeman21158fc2005-09-01 00:19:25 +00004225 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004226 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004227 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004228
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004229 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004230 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004231 if (NewSRA.getNode())
4232 return NewSRA;
4233 }
4234
Evan Chengf1005572010-04-28 07:10:39 +00004235 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004236}
4237
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004238SDValue DAGCombiner::visitSRL(SDNode *N) {
4239 SDValue N0 = N->getOperand(0);
4240 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004241 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4242 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004243 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004244 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004245
Daniel Sandersa1840d22013-11-11 17:23:41 +00004246 // fold vector ops
4247 if (VT.isVector()) {
4248 SDValue FoldedVOp = SimplifyVBinOp(N);
4249 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004250
4251 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004252 }
4253
Nate Begeman21158fc2005-09-01 00:19:25 +00004254 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004255 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004256 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004257 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004258 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004259 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004260 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004261 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004262 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004263 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004264 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004265 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004266 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004267 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004268 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004269 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004270
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004271 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004272 if (N1C && N0.getOpcode() == ISD::SRL) {
4273 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4274 uint64_t c1 = N01C->getZExtValue();
4275 uint64_t c2 = N1C->getZExtValue();
4276 if (c1 + c2 >= OpSizeInBits)
4277 return DAG.getConstant(0, VT);
4278 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4279 DAG.getConstant(c1 + c2, N1.getValueType()));
4280 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004281 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004282
Dale Johannesencd538af2010-12-17 21:45:49 +00004283 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004284 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4285 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004286 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004287 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004288 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4289 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004290 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4291 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004292 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004293 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004294 if (c1 + OpSizeInBits == InnerShiftSize) {
4295 if (c1 + c2 >= InnerShiftSize)
4296 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004297 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4298 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004299 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004300 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004301 }
4302 }
4303
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004304 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004305 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4306 unsigned BitSize = N0.getScalarValueSizeInBits();
4307 if (BitSize <= 64) {
4308 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4309 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4310 DAG.getConstant(~0ULL >> ShAmt, VT));
4311 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004312 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004313
Michael Liao62ebfd82013-06-21 18:45:27 +00004314 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004315 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4316 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004317 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004318 unsigned BitSize = SmallVT.getScalarSizeInBits();
4319 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004320 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004321
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004322 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004323 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004324 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004325 N0.getOperand(0),
4326 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004327 AddToWorkList(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004328 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004329 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4330 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4331 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004332 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004333 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004334
Chris Lattner2e33fb42006-10-12 20:23:19 +00004335 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4336 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004337 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004338 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004339 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004340 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004341
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004342 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004343 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004344 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004345 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004346 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004347
Chris Lattner49932492006-04-02 06:11:11 +00004348 // If any of the input bits are KnownOne, then the input couldn't be all
4349 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004350 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004351
Chris Lattner49932492006-04-02 06:11:11 +00004352 // If all of the bits input the to ctlz node are known to be zero, then
4353 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004354 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004355 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004356
Chris Lattner49932492006-04-02 06:11:11 +00004357 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004358 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004359 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004360 // could be set on input to the CTLZ node. If this bit is set, the SRL
4361 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4362 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004363 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004364 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004365
Chris Lattner49932492006-04-02 06:11:11 +00004366 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004367 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004368 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004369 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004370 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004371
Andrew Trickef9de2a2013-05-25 02:42:55 +00004372 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004373 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004374 }
4375 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004376
Duncan Sands3ed76882009-02-01 18:06:53 +00004377 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004378 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004379 N1.getOperand(0).getOpcode() == ISD::AND) {
4380 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4381 if (NewOp1.getNode())
4382 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004383 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004384
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004385 // fold operands of srl based on knowledge that the low bits are not
4386 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004387 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4388 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004389
Evan Chengb175de62009-12-18 21:31:31 +00004390 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004391 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004392 if (NewSRL.getNode())
4393 return NewSRL;
4394 }
4395
Dan Gohman600f62b2010-06-24 14:30:44 +00004396 // Attempt to convert a srl of a load into a narrower zero-extending load.
4397 SDValue NarrowLoad = ReduceLoadWidth(N);
4398 if (NarrowLoad.getNode())
4399 return NarrowLoad;
4400
Evan Chengb175de62009-12-18 21:31:31 +00004401 // Here is a common situation. We want to optimize:
4402 //
4403 // %a = ...
4404 // %b = and i32 %a, 2
4405 // %c = srl i32 %b, 1
4406 // brcond i32 %c ...
4407 //
4408 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004409 //
Evan Chengb175de62009-12-18 21:31:31 +00004410 // %a = ...
4411 // %b = and %a, 2
4412 // %c = setcc eq %b, 0
4413 // brcond %c ...
4414 //
4415 // However when after the source operand of SRL is optimized into AND, the SRL
4416 // itself may not be optimized further. Look for it and add the BRCOND into
4417 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004418 if (N->hasOneUse()) {
4419 SDNode *Use = *N->use_begin();
4420 if (Use->getOpcode() == ISD::BRCOND)
4421 AddToWorkList(Use);
4422 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4423 // Also look pass the truncate.
4424 Use = *Use->use_begin();
4425 if (Use->getOpcode() == ISD::BRCOND)
4426 AddToWorkList(Use);
4427 }
4428 }
Evan Chengb175de62009-12-18 21:31:31 +00004429
Evan Chengf1005572010-04-28 07:10:39 +00004430 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004431}
4432
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004433SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4434 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004435 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004436
4437 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004438 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004439 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004440 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004441}
4442
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004443SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4444 SDValue N0 = N->getOperand(0);
4445 EVT VT = N->getValueType(0);
4446
4447 // fold (ctlz_zero_undef c1) -> c2
4448 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004449 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004450 return SDValue();
4451}
4452
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004453SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4454 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004455 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004456
Nate Begeman21158fc2005-09-01 00:19:25 +00004457 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004458 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004459 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004460 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004461}
4462
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004463SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4464 SDValue N0 = N->getOperand(0);
4465 EVT VT = N->getValueType(0);
4466
4467 // fold (cttz_zero_undef c1) -> c2
4468 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004469 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004470 return SDValue();
4471}
4472
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004473SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4474 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004475 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004476
Nate Begeman21158fc2005-09-01 00:19:25 +00004477 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004478 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004479 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004480 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004481}
4482
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004483SDValue DAGCombiner::visitSELECT(SDNode *N) {
4484 SDValue N0 = N->getOperand(0);
4485 SDValue N1 = N->getOperand(1);
4486 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004487 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4489 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004490 EVT VT = N->getValueType(0);
4491 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004492
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004493 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004494 if (N1 == N2)
4495 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004496 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004497 if (N0C && !N0C->isNullValue())
4498 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004499 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004500 if (N0C && N0C->isNullValue())
4501 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004502 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004503 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004504 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004505 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004506 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004507 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004508 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004509 TLI.getBooleanContents(false) ==
4510 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004511 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004512 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004513 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004514 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004515 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004516 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004517 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004518 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004519 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004520 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4521 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004522 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004523 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004524 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004525 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004526 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004527 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004528 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004529 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004530 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004531 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004532 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004533 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004534 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004535 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004536 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004537 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004538 // fold (select X, X, Y) -> (or X, Y)
4539 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004540 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004541 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004542 // fold (select X, Y, X) -> (and X, Y)
4543 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004544 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004545 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004546
Chris Lattner6c14c352005-10-18 06:04:22 +00004547 // If we can fold this based on the true/false value, do so.
4548 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004549 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004550
Nate Begemanc760f802005-09-19 22:34:01 +00004551 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004552 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004553 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004554 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004555 // having to say they don't support SELECT_CC on every type the DAG knows
4556 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004557 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004558 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004559 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004560 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004561 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004562 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004563 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004564
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004565 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004566}
4567
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004568static
4569std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4570 SDLoc DL(N);
4571 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004572 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004573
4574 // Split the inputs.
4575 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004576 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4577 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004578
4579 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4580 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4581
4582 return std::make_pair(Lo, Hi);
4583}
4584
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004585SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4586 SDValue N0 = N->getOperand(0);
4587 SDValue N1 = N->getOperand(1);
4588 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004589 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004590
4591 // Canonicalize integer abs.
4592 // vselect (setg[te] X, 0), X, -X ->
4593 // vselect (setgt X, -1), X, -X ->
4594 // vselect (setl[te] X, 0), -X, X ->
4595 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4596 if (N0.getOpcode() == ISD::SETCC) {
4597 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4598 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4599 bool isAbs = false;
4600 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4601
4602 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4603 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4604 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4605 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4606 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4607 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4608 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4609
4610 if (isAbs) {
4611 EVT VT = LHS.getValueType();
4612 SDValue Shift = DAG.getNode(
4613 ISD::SRA, DL, VT, LHS,
4614 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4615 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4616 AddToWorkList(Shift.getNode());
4617 AddToWorkList(Add.getNode());
4618 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4619 }
4620 }
4621
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004622 // If the VSELECT result requires splitting and the mask is provided by a
4623 // SETCC, then split both nodes and its operands before legalization. This
4624 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4625 // and enables future optimizations (e.g. min/max pattern matching on X86).
4626 if (N0.getOpcode() == ISD::SETCC) {
4627 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004628
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004629 // Check if any splitting is required.
4630 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4631 TargetLowering::TypeSplitVector)
4632 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004633
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004634 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004635 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4636 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4637 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004638
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004639 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4640 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004641
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004642 // Add the new VSELECT nodes to the work list in case they need to be split
4643 // again.
4644 AddToWorkList(Lo.getNode());
4645 AddToWorkList(Hi.getNode());
4646
4647 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004648 }
4649
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004650 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4651 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4652 return N1;
4653 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4654 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4655 return N2;
4656
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004657 return SDValue();
4658}
4659
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004660SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4661 SDValue N0 = N->getOperand(0);
4662 SDValue N1 = N->getOperand(1);
4663 SDValue N2 = N->getOperand(2);
4664 SDValue N3 = N->getOperand(3);
4665 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004666 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004667
Nate Begemanc760f802005-09-19 22:34:01 +00004668 // fold select_cc lhs, rhs, x, x, cc -> x
4669 if (N2 == N3)
4670 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004671
Chris Lattner8b68dec2006-09-20 06:19:26 +00004672 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004673 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004674 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004675 if (SCC.getNode()) {
4676 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004677
Stephen Lin605207f2013-06-15 04:03:33 +00004678 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4679 if (!SCCC->isNullValue())
4680 return N2; // cond always true -> true val
4681 else
4682 return N3; // cond always false -> false val
4683 }
4684
4685 // Fold to a simpler select_cc
4686 if (SCC.getOpcode() == ISD::SETCC)
4687 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4688 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4689 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004690 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004691
Chris Lattner6c14c352005-10-18 06:04:22 +00004692 // If we can fold this based on the true/false value, do so.
4693 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004694 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004695
Nate Begemanc760f802005-09-19 22:34:01 +00004696 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004697 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004698}
4699
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004700SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004701 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004702 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004703 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004704}
4705
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004706// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4707// dag node into a ConstantSDNode or a build_vector of constants.
4708// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004709// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004710// Vector extends are not folded if operations are legal; this is to
4711// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004712static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4713 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004714 bool LegalOperations) {
4715 unsigned Opcode = N->getOpcode();
4716 SDValue N0 = N->getOperand(0);
4717 EVT VT = N->getValueType(0);
4718
4719 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4720 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4721
4722 // fold (sext c1) -> c1
4723 // fold (zext c1) -> c1
4724 // fold (aext c1) -> c1
4725 if (isa<ConstantSDNode>(N0))
4726 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4727
4728 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4729 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4730 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004731 EVT SVT = VT.getScalarType();
4732 if (!(VT.isVector() &&
4733 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004734 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004735 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004736
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004737 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004738 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004739 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4740 unsigned ShAmt = VTBits - EVTBits;
4741 SmallVector<SDValue, 8> Elts;
4742 unsigned NumElts = N0->getNumOperands();
4743 SDLoc DL(N);
4744
4745 for (unsigned i=0; i != NumElts; ++i) {
4746 SDValue Op = N0->getOperand(i);
4747 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004748 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004749 continue;
4750 }
4751
4752 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4753 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4754 if (Opcode == ISD::SIGN_EXTEND)
4755 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004756 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004757 else
4758 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004759 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004760 }
4761
Craig Topper48d114b2014-04-26 18:35:24 +00004762 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004763}
4764
Evan Chenge106e2f2007-10-29 19:58:20 +00004765// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004766// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004767// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004768// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004769static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004770 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004771 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004772 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004773 bool HasCopyToRegUses = false;
4774 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004775 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4776 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004777 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004778 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004779 if (User == N)
4780 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004781 if (UI.getUse().getResNo() != N0.getResNo())
4782 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004783 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004784 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004785 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4786 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4787 // Sign bits will be lost after a zext.
4788 return false;
4789 bool Add = false;
4790 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004791 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004792 if (UseOp == N0)
4793 continue;
4794 if (!isa<ConstantSDNode>(UseOp))
4795 return false;
4796 Add = true;
4797 }
4798 if (Add)
4799 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004800 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004801 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004802 // If truncates aren't free and there are users we can't
4803 // extend, it isn't worthwhile.
4804 if (!isTruncFree)
4805 return false;
4806 // Remember if this value is live-out.
4807 if (User->getOpcode() == ISD::CopyToReg)
4808 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004809 }
4810
4811 if (HasCopyToRegUses) {
4812 bool BothLiveOut = false;
4813 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4814 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004815 SDUse &Use = UI.getUse();
4816 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4817 BothLiveOut = true;
4818 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004819 }
4820 }
4821 if (BothLiveOut)
4822 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004823 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004824 return ExtendNodes.size();
4825 }
4826 return true;
4827}
4828
Craig Toppere0b71182013-07-13 07:43:40 +00004829void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004830 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004831 ISD::NodeType ExtType) {
4832 // Extend SetCC uses if necessary.
4833 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4834 SDNode *SetCC = SetCCs[i];
4835 SmallVector<SDValue, 4> Ops;
4836
4837 for (unsigned j = 0; j != 2; ++j) {
4838 SDValue SOp = SetCC->getOperand(j);
4839 if (SOp == Trunc)
4840 Ops.push_back(ExtLoad);
4841 else
4842 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4843 }
4844
4845 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00004846 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004847 }
4848}
4849
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004850SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4851 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004852 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004853
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004854 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4855 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004856 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004857
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004858 // fold (sext (sext x)) -> (sext x)
4859 // fold (sext (aext x)) -> (sext x)
4860 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004861 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004862 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004863
Chris Lattnerfce448f2007-02-26 03:13:59 +00004864 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004865 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4866 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004867 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4868 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004869 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4870 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004871 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004872 // CombineTo deleted the truncate, if needed, but not what's under it.
4873 AddToWorkList(oye);
4874 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004875 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004876 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004877
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004878 // See if the value being truncated is already sign extended. If so, just
4879 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004880 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004881 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4882 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4883 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004884 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004885
Chris Lattnerfce448f2007-02-26 03:13:59 +00004886 if (OpBits == DestBits) {
4887 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4888 // bits, it is already ready.
4889 if (NumSignBits > DestBits-MidBits)
4890 return Op;
4891 } else if (OpBits < DestBits) {
4892 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4893 // bits, just sext from i32.
4894 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004895 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004896 } else {
4897 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4898 // bits, just truncate to i32.
4899 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004900 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004901 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004902
Chris Lattnerfce448f2007-02-26 03:13:59 +00004903 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004904 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4905 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004906 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004907 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004908 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004909 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4910 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004911 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004912 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004913 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004914
Evan Chengbce7c472005-12-14 02:19:23 +00004915 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004916 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004917 // on vectors in one instruction. We only perform this transformation on
4918 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004919 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004920 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004921 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004922 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004923 bool DoXform = true;
4924 SmallVector<SDNode*, 4> SetCCs;
4925 if (!N0.hasOneUse())
4926 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4927 if (DoXform) {
4928 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004929 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004930 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004931 LN0->getBasePtr(), N0.getValueType(),
4932 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004933 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004934 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004935 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004936 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004937 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004938 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004939 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004940 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004941 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004942
4943 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4944 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004945 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4946 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004947 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004948 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004949 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004950 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004951 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004952 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004953 LN0->getBasePtr(), MemVT,
4954 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004955 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004956 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004957 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004958 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004959 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004961 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004962 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004963
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004964 // fold (sext (and/or/xor (load x), cst)) ->
4965 // (and/or/xor (sextload x), (sext cst))
4966 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4967 N0.getOpcode() == ISD::XOR) &&
4968 isa<LoadSDNode>(N0.getOperand(0)) &&
4969 N0.getOperand(1).getOpcode() == ISD::Constant &&
4970 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4971 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4972 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004973 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004974 bool DoXform = true;
4975 SmallVector<SDNode*, 4> SetCCs;
4976 if (!N0.hasOneUse())
4977 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4978 SetCCs, TLI);
4979 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004980 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004981 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004982 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004983 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004984 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4985 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004986 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004987 ExtLoad, DAG.getConstant(Mask, VT));
4988 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004989 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004990 N0.getOperand(0).getValueType(), ExtLoad);
4991 CombineTo(N, And);
4992 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004993 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004994 ISD::SIGN_EXTEND);
4995 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4996 }
4997 }
4998 }
4999
Chris Lattner65786b02007-04-11 05:32:27 +00005000 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00005001 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005002 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005003 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00005004 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00005005 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00005006 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00005007 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5008 // of the same size as the compared operands. Only optimize sext(setcc())
5009 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005010 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005011
5012 // We know that the # elements of the results is the same as the
5013 // # elements of the compare (and the # elements of the compare result
5014 // for that matter). Check to see that they are the same size. If so,
5015 // we know that the element size of the sext'd result matches the
5016 // element size of the compare operands.
5017 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005018 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005019 N0.getOperand(1),
5020 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005021
Dan Gohmane82c25e2010-04-30 17:19:19 +00005022 // If the desired elements are smaller or larger than the source
5023 // elements we can use a matching integer vector type and then
5024 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005025 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005026 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005027 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005028 N0.getOperand(0), N0.getOperand(1),
5029 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005030 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005031 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005032 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005033
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005034 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005035 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005036 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005037 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005038 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005039 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005040 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005041 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005042 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005043
5044 if (!VT.isVector()) {
5045 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5046 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5047 SDLoc DL(N);
5048 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5049 SDValue SetCC = DAG.getSetCC(DL,
5050 SetCCVT,
5051 N0.getOperand(0), N0.getOperand(1), CC);
5052 EVT SelectVT = getSetCCResultType(VT);
5053 return DAG.getSelect(DL, VT,
5054 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5055 NegOne, DAG.getConstant(0, VT));
5056
5057 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005058 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005059 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005060
Dan Gohman3eb10f72008-04-28 16:58:24 +00005061 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005062 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005063 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005064 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005065
Evan Chengf1005572010-04-28 07:10:39 +00005066 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005067}
5068
Rafael Espindola8f62b322012-04-09 16:06:03 +00005069// isTruncateOf - If N is a truncate of some other value, return true, record
5070// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5071// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005072// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005073static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5074 APInt &KnownZero) {
5075 APInt KnownOne;
5076 if (N->getOpcode() == ISD::TRUNCATE) {
5077 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005078 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005079 return true;
5080 }
5081
5082 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5083 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5084 return false;
5085
5086 SDValue Op0 = N->getOperand(0);
5087 SDValue Op1 = N->getOperand(1);
5088 assert(Op0.getValueType() == Op1.getValueType());
5089
5090 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5091 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005092 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005093 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005094 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005095 Op = Op0;
5096 else
5097 return false;
5098
Jay Foada0653a32014-05-14 21:14:37 +00005099 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005100
5101 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5102 return false;
5103
5104 return true;
5105}
5106
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005107SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5108 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005109 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005110
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005111 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5112 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005113 return SDValue(Res, 0);
5114
Nate Begeman21158fc2005-09-01 00:19:25 +00005115 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005116 // fold (zext (aext x)) -> (zext x)
5117 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005118 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005119 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005120
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005121 // fold (zext (truncate x)) -> (zext x) or
5122 // (zext (truncate x)) -> (truncate x)
5123 // This is valid when the truncated bits of x are already zero.
5124 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005125 SDValue Op;
5126 APInt KnownZero;
5127 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5128 APInt TruncatedBits =
5129 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5130 APInt(Op.getValueSizeInBits(), 0) :
5131 APInt::getBitsSet(Op.getValueSizeInBits(),
5132 N0.getValueSizeInBits(),
5133 std::min(Op.getValueSizeInBits(),
5134 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005135 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005136 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005137 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005138 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005139 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005140
5141 return Op;
5142 }
5143 }
5144
Evan Cheng464dc9b2007-03-22 01:54:19 +00005145 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5146 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005147 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005148 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5149 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005150 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5151 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005152 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005153 // CombineTo deleted the truncate, if needed, but not what's under it.
5154 AddToWorkList(oye);
5155 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005156 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005157 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005158 }
5159
Chris Lattnera31f0a62006-09-21 06:00:20 +00005160 // fold (zext (truncate x)) -> (and x, mask)
5161 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005162 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005163
5164 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5165 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5166 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5167 if (NarrowLoad.getNode()) {
5168 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5169 if (NarrowLoad.getNode() != N0.getNode()) {
5170 CombineTo(N0.getNode(), NarrowLoad);
5171 // CombineTo deleted the truncate, if needed, but not what's under it.
5172 AddToWorkList(oye);
5173 }
5174 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5175 }
5176
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005177 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005178 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005179 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005180 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005181 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005182 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005183 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005184 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005185 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005186 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005187 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005188
Dan Gohmanad3e5492009-04-08 00:15:30 +00005189 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5190 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005191 if (N0.getOpcode() == ISD::AND &&
5192 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005193 N0.getOperand(1).getOpcode() == ISD::Constant &&
5194 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5195 N0.getValueType()) ||
5196 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005197 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005198 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005199 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005200 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005201 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005202 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005203 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005204 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005205 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005206 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005207 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005208
Evan Chengbce7c472005-12-14 02:19:23 +00005209 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005210 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005211 // on vectors in one instruction. We only perform this transformation on
5212 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005213 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005214 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005215 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005216 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005217 bool DoXform = true;
5218 SmallVector<SDNode*, 4> SetCCs;
5219 if (!N0.hasOneUse())
5220 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5221 if (DoXform) {
5222 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005223 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005224 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005225 LN0->getBasePtr(), N0.getValueType(),
5226 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005227 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005228 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005229 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005230 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005231
Andrew Trickef9de2a2013-05-25 02:42:55 +00005232 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005233 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005234 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005235 }
Evan Chengbce7c472005-12-14 02:19:23 +00005236 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005237
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005238 // fold (zext (and/or/xor (load x), cst)) ->
5239 // (and/or/xor (zextload x), (zext cst))
5240 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5241 N0.getOpcode() == ISD::XOR) &&
5242 isa<LoadSDNode>(N0.getOperand(0)) &&
5243 N0.getOperand(1).getOpcode() == ISD::Constant &&
5244 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5245 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5246 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005247 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005248 bool DoXform = true;
5249 SmallVector<SDNode*, 4> SetCCs;
5250 if (!N0.hasOneUse())
5251 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5252 SetCCs, TLI);
5253 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005254 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005255 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005256 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005257 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005258 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5259 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005260 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005261 ExtLoad, DAG.getConstant(Mask, VT));
5262 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005263 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005264 N0.getOperand(0).getValueType(), ExtLoad);
5265 CombineTo(N, And);
5266 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005267 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005268 ISD::ZERO_EXTEND);
5269 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5270 }
5271 }
5272 }
5273
Chris Lattner7dac1082005-12-14 19:05:06 +00005274 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5275 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005276 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5277 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005278 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005279 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005280 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005281 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005282 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005283 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005284 LN0->getBasePtr(), MemVT,
5285 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005286 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005287 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005288 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005289 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005290 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005291 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005292 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005293 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005294
Chris Lattner65786b02007-04-11 05:32:27 +00005295 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005296 if (!LegalOperations && VT.isVector() &&
5297 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005298 EVT N0VT = N0.getOperand(0).getValueType();
5299 if (getSetCCResultType(N0VT) == N0.getValueType())
5300 return SDValue();
5301
Evan Chengabd0ad52010-05-19 01:08:17 +00005302 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5303 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005304 EVT EltVT = VT.getVectorElementType();
5305 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5306 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005307 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005308 // We know that the # elements of the results is the same as the
5309 // # elements of the compare (and the # elements of the compare result
5310 // for that matter). Check to see that they are the same size. If so,
5311 // we know that the element size of the sext'd result matches the
5312 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005313 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5314 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005315 N0.getOperand(1),
5316 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005317 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005318 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005319
5320 // If the desired elements are smaller or larger than the source
5321 // elements we can use a matching integer vector type and then
5322 // truncate/sign extend
5323 EVT MatchingElementType =
5324 EVT::getIntegerVT(*DAG.getContext(),
5325 N0VT.getScalarType().getSizeInBits());
5326 EVT MatchingVectorType =
5327 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5328 N0VT.getVectorNumElements());
5329 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005330 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005331 N0.getOperand(1),
5332 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005333 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5334 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005335 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005336 }
5337
5338 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005339 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005340 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005341 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005342 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005343 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005344 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005345
Evan Cheng852c4862009-12-15 03:00:32 +00005346 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005347 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005348 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005349 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5350 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005351 SDValue ShAmt = N0.getOperand(1);
5352 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005353 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005354 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005355 // If the original shl may be shifting out bits, do not perform this
5356 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005357 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5358 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5359 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005360 return SDValue();
5361 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005362
Andrew Trickef9de2a2013-05-25 02:42:55 +00005363 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005364
5365 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005366 if (VT.getSizeInBits() >= 256)
5367 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005368
Chris Lattnere95d1952011-02-13 19:09:16 +00005369 return DAG.getNode(N0.getOpcode(), DL, VT,
5370 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5371 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005372 }
5373
Evan Chengf1005572010-04-28 07:10:39 +00005374 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005375}
5376
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005377SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5378 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005379 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005380
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005381 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5382 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005383 return SDValue(Res, 0);
5384
Chris Lattner812646a2006-05-05 05:58:59 +00005385 // fold (aext (aext x)) -> (aext x)
5386 // fold (aext (zext x)) -> (zext x)
5387 // fold (aext (sext x)) -> (sext x)
5388 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5389 N0.getOpcode() == ISD::ZERO_EXTEND ||
5390 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005391 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005392
Evan Cheng464dc9b2007-03-22 01:54:19 +00005393 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5394 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5395 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005396 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5397 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005398 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5399 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005400 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005401 // CombineTo deleted the truncate, if needed, but not what's under it.
5402 AddToWorkList(oye);
5403 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005404 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005405 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005406 }
5407
Chris Lattner8746e2c2006-09-20 06:29:17 +00005408 // fold (aext (truncate x))
5409 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005410 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005411 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005412 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005413 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005414 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5415 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005416 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005417
Dan Gohmanad3e5492009-04-08 00:15:30 +00005418 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5419 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005420 if (N0.getOpcode() == ISD::AND &&
5421 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005422 N0.getOperand(1).getOpcode() == ISD::Constant &&
5423 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5424 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005425 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005426 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005427 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005428 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005429 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005430 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005431 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005432 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005433 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005434 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005435 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005436
Chris Lattner812646a2006-05-05 05:58:59 +00005437 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005438 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005439 // on vectors in one instruction. We only perform this transformation on
5440 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005441 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005442 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005443 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005444 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005445 bool DoXform = true;
5446 SmallVector<SDNode*, 4> SetCCs;
5447 if (!N0.hasOneUse())
5448 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5449 if (DoXform) {
5450 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005451 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005452 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005453 LN0->getBasePtr(), N0.getValueType(),
5454 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005455 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005456 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005457 N0.getValueType(), ExtLoad);
5458 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005459 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005460 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005461 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5462 }
Chris Lattner812646a2006-05-05 05:58:59 +00005463 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005464
Chris Lattner812646a2006-05-05 05:58:59 +00005465 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5466 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5467 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005468 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005469 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005470 N0.hasOneUse()) {
5471 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005472 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005473 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005474 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5475 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5476 VT, LN0->getChain(), LN0->getBasePtr(),
5477 MemVT, LN0->getMemOperand());
5478 CombineTo(N, ExtLoad);
5479 CombineTo(N0.getNode(),
5480 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5481 N0.getValueType(), ExtLoad),
5482 ExtLoad.getValue(1));
5483 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5484 }
Chris Lattner812646a2006-05-05 05:58:59 +00005485 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005486
Chris Lattner65786b02007-04-11 05:32:27 +00005487 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005488 // For vectors:
5489 // aext(setcc) -> vsetcc
5490 // aext(setcc) -> truncate(vsetcc)
5491 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005492 // Only do this before legalize for now.
5493 if (VT.isVector() && !LegalOperations) {
5494 EVT N0VT = N0.getOperand(0).getValueType();
5495 // We know that the # elements of the results is the same as the
5496 // # elements of the compare (and the # elements of the compare result
5497 // for that matter). Check to see that they are the same size. If so,
5498 // we know that the element size of the sext'd result matches the
5499 // element size of the compare operands.
5500 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005501 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005502 N0.getOperand(1),
5503 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005504 // If the desired elements are smaller or larger than the source
5505 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005506 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005507 else {
Hao Liuc636d152014-04-22 09:57:06 +00005508 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005509 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005510 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005511 N0.getOperand(1),
5512 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005513 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005514 }
5515 }
5516
5517 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005518 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005519 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005520 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005521 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005522 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005523 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005524 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005525
Evan Chengf1005572010-04-28 07:10:39 +00005526 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005527}
5528
Chris Lattner5e6fe052007-10-13 06:35:54 +00005529/// GetDemandedBits - See if the specified operand can be simplified with the
5530/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005531/// simpler operand, otherwise return a null SDValue.
5532SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005533 switch (V.getOpcode()) {
5534 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005535 case ISD::Constant: {
5536 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005537 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005538 const APInt &CVal = CV->getAPIntValue();
5539 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005540 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005541 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005542 break;
5543 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005544 case ISD::OR:
5545 case ISD::XOR:
5546 // If the LHS or RHS don't contribute bits to the or, drop them.
5547 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5548 return V.getOperand(1);
5549 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5550 return V.getOperand(0);
5551 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005552 case ISD::SRL:
5553 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005554 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005555 break;
5556 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5557 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005558 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005559
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005560 // Watch out for shift count overflow though.
5561 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005562 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005563 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005564 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005565 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005566 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005567 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005568 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005569 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005570}
5571
Evan Cheng464dc9b2007-03-22 01:54:19 +00005572/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5573/// bits and then truncated to a narrower type and where N is a multiple
5574/// of number of bits of the narrower type, transform it to a narrower load
5575/// from address + N / num of bits of new type. If the result is to be
5576/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005577SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005578 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005579
Evan Cheng464dc9b2007-03-22 01:54:19 +00005580 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005581 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005582 EVT VT = N->getValueType(0);
5583 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005584
Dan Gohman550c9af2008-08-14 20:04:46 +00005585 // This transformation isn't valid for vector loads.
5586 if (VT.isVector())
5587 return SDValue();
5588
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005589 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005590 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005591 if (Opc == ISD::SIGN_EXTEND_INREG) {
5592 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005593 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005594 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005595 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005596 ExtType = ISD::ZEXTLOAD;
5597 N0 = SDValue(N, 0);
5598 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5599 if (!N01) return SDValue();
5600 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5601 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005602 }
Richard Osborne272e0842011-01-31 17:41:44 +00005603 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5604 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005605
Owen Anderson53aa7a92009-08-10 22:56:29 +00005606 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005607
Chris Lattner9a499e92010-12-22 08:01:44 +00005608 // Do not generate loads of non-round integer types since these can
5609 // be expensive (and would be wrong if the type is not byte sized).
5610 if (!ExtVT.isRound())
5611 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005612
Evan Cheng464dc9b2007-03-22 01:54:19 +00005613 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005614 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005615 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005616 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005617 // Is the shift amount a multiple of size of VT?
5618 if ((ShAmt & (EVTBits-1)) == 0) {
5619 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005620 // Is the load width a multiple of size of VT?
5621 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005622 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005623 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005624
Chris Lattnercafc1e62010-12-22 08:02:57 +00005625 // At this point, we must have a load or else we can't do the transform.
5626 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005627
Chandler Carruthb27041c2012-12-11 00:36:57 +00005628 // Because a SRL must be assumed to *need* to zero-extend the high bits
5629 // (as opposed to anyext the high bits), we can't combine the zextload
5630 // lowering of SRL and an sextload.
5631 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5632 return SDValue();
5633
Chris Lattnera2050552010-10-01 05:36:09 +00005634 // If the shift amount is larger than the input type then we're not
5635 // accessing any of the loaded bytes. If the load was a zextload/extload
5636 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005637 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005638 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005639 }
5640 }
5641
Dan Gohman68fb0042010-11-03 01:47:46 +00005642 // If the load is shifted left (and the result isn't shifted back right),
5643 // we can fold the truncate through the shift.
5644 unsigned ShLeftAmt = 0;
5645 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005646 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005647 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5648 ShLeftAmt = N01->getZExtValue();
5649 N0 = N0.getOperand(0);
5650 }
5651 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005652
Chris Lattner222374d2010-12-22 07:36:50 +00005653 // If we haven't found a load, we can't narrow it. Don't transform one with
5654 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005655 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5656 return SDValue();
5657
5658 // Don't change the width of a volatile load.
5659 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5660 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005661 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005662
Chris Lattner9a499e92010-12-22 08:01:44 +00005663 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005664 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005665 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005666
Bill Schmidtd006c692013-01-14 22:04:38 +00005667 // For the transform to be legal, the load must produce only two values
5668 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005669 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005670 // transformation is not equivalent, and the downstream logic to replace
5671 // uses gets things wrong.
5672 if (LN0->getNumValues() > 2)
5673 return SDValue();
5674
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005675 // If the load that we're shrinking is an extload and we're not just
5676 // discarding the extension we can't simply shrink the load. Bail.
5677 // TODO: It would be possible to merge the extensions in some cases.
5678 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5679 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5680 return SDValue();
5681
Chris Lattner222374d2010-12-22 07:36:50 +00005682 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005683
Evan Cheng4c6f9172012-06-26 01:19:33 +00005684 if (PtrType == MVT::Untyped || PtrType.isExtended())
5685 // It's not possible to generate a constant of extended or untyped type.
5686 return SDValue();
5687
Chris Lattner222374d2010-12-22 07:36:50 +00005688 // For big endian targets, we need to adjust the offset to the pointer to
5689 // load the correct bytes.
5690 if (TLI.isBigEndian()) {
5691 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5692 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5693 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005694 }
5695
Chris Lattner222374d2010-12-22 07:36:50 +00005696 uint64_t PtrOff = ShAmt / 8;
5697 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005698 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005699 PtrType, LN0->getBasePtr(),
5700 DAG.getConstant(PtrOff, PtrType));
5701 AddToWorkList(NewPtr.getNode());
5702
Chris Lattner9a499e92010-12-22 08:01:44 +00005703 SDValue Load;
5704 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005705 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005706 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005707 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005708 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005709 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005710 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005711 LN0->getPointerInfo().getWithOffset(PtrOff),
5712 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005713 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005714
5715 // Replace the old load's chain with the new load's chain.
5716 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005717 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005718
5719 // Shift the result left, if we've swallowed a left shift.
5720 SDValue Result = Load;
5721 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005722 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005723 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5724 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005725 // If the shift amount is as large as the result size (but, presumably,
5726 // no larger than the source) then the useful bits of the result are
5727 // zero; we can't simply return the shortened shift, because the result
5728 // of that operation is undefined.
5729 if (ShLeftAmt >= VT.getSizeInBits())
5730 Result = DAG.getConstant(0, VT);
5731 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005732 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005733 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005734 }
5735
5736 // Return the new loaded value.
5737 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005738}
5739
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005740SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5741 SDValue N0 = N->getOperand(0);
5742 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005743 EVT VT = N->getValueType(0);
5744 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005745 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005746 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005747
Nate Begeman21158fc2005-09-01 00:19:25 +00005748 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005749 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005750 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005751
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005752 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005753 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005754 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005755
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005756 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5757 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005758 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005759 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005760 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005761
Dan Gohman345d63c2008-07-31 00:50:31 +00005762 // fold (sext_in_reg (sext x)) -> (sext x)
5763 // fold (sext_in_reg (aext x)) -> (sext x)
5764 // if x is small enough.
5765 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5766 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005767 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5768 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005769 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005770 }
5771
Chris Lattner9ad59152007-04-17 19:03:21 +00005772 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005773 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005774 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005775
Chris Lattner9ad59152007-04-17 19:03:21 +00005776 // fold operands of sext_in_reg based on knowledge that the top bits are not
5777 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005778 if (SimplifyDemandedBits(SDValue(N, 0)))
5779 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005780
Evan Cheng464dc9b2007-03-22 01:54:19 +00005781 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5782 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005783 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005784 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005785 return NarrowLoad;
5786
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005787 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005788 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005789 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5790 if (N0.getOpcode() == ISD::SRL) {
5791 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005792 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005793 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005794 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005795 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005796 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005797 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005798 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005799 }
5800 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005801
Nate Begeman02b23c62005-10-13 03:11:28 +00005802 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005803 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005804 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005805 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005806 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005807 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005808 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005809 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005810 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005811 LN0->getBasePtr(), EVT,
5812 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005813 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005814 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005815 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005816 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005817 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005818 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005819 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005820 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005821 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005822 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005823 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005824 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005825 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005826 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005827 LN0->getBasePtr(), EVT,
5828 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005829 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005830 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005831 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005832 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005833
5834 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5835 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5836 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5837 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005838 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005839 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005840 BSwap, N1);
5841 }
5842
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005843 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5844 // into a build_vector.
5845 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5846 SmallVector<SDValue, 8> Elts;
5847 unsigned NumElts = N0->getNumOperands();
5848 unsigned ShAmt = VTBits - EVTBits;
5849
5850 for (unsigned i = 0; i != NumElts; ++i) {
5851 SDValue Op = N0->getOperand(i);
5852 if (Op->getOpcode() == ISD::UNDEF) {
5853 Elts.push_back(Op);
5854 continue;
5855 }
5856
5857 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005858 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5859 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005860 Op.getValueType()));
5861 }
5862
Craig Topper48d114b2014-04-26 18:35:24 +00005863 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005864 }
5865
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005866 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005867}
5868
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005869SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5870 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005871 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005872 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005873
5874 // noop truncate
5875 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005876 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005877 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005878 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005879 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005880 // fold (truncate (truncate x)) -> (truncate x)
5881 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005882 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005883 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005884 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5885 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005886 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005887 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005888 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005889 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005890 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005891 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005892 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005893 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005894 // if the source and dest are the same type, we can drop both the extend
5895 // and the truncate.
5896 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005897 }
Evan Chengd63baea2007-03-21 20:14:05 +00005898
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005899 // Fold extract-and-trunc into a narrow extract. For example:
5900 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5901 // i32 y = TRUNCATE(i64 x)
5902 // -- becomes --
5903 // v16i8 b = BITCAST (v2i64 val)
5904 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5905 //
5906 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005907 // creates this pattern) and before operation legalization after which
5908 // we need to be more careful about the vector instructions that we generate.
5909 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005910 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005911
5912 EVT VecTy = N0.getOperand(0).getValueType();
5913 EVT ExTy = N0.getValueType();
5914 EVT TrTy = N->getValueType(0);
5915
5916 unsigned NumElem = VecTy.getVectorNumElements();
5917 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5918
5919 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5920 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5921
5922 SDValue EltNo = N0->getOperand(1);
5923 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5924 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005925 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005926 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5927
Andrew Trickef9de2a2013-05-25 02:42:55 +00005928 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005929 NVT, N0.getOperand(0));
5930
5931 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005932 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005933 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005934 }
5935 }
5936
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005937 // Fold a series of buildvector, bitcast, and truncate if possible.
5938 // For example fold
5939 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5940 // (2xi32 (buildvector x, y)).
5941 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5942 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5943 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5944 N0.getOperand(0).hasOneUse()) {
5945
5946 SDValue BuildVect = N0.getOperand(0);
5947 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5948 EVT TruncVecEltTy = VT.getVectorElementType();
5949
5950 // Check that the element types match.
5951 if (BuildVectEltTy == TruncVecEltTy) {
5952 // Now we only need to compute the offset of the truncated elements.
5953 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5954 unsigned TruncVecNumElts = VT.getVectorNumElements();
5955 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5956
5957 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5958 "Invalid number of elements");
5959
5960 SmallVector<SDValue, 8> Opnds;
5961 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5962 Opnds.push_back(BuildVect.getOperand(i));
5963
Craig Topper48d114b2014-04-26 18:35:24 +00005964 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005965 }
5966 }
5967
Chris Lattner5e6fe052007-10-13 06:35:54 +00005968 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00005969 // only the low bits are being used.
5970 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00005971 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00005972 // may have different active low bits.
5973 if (!VT.isVector()) {
5974 SDValue Shorter =
5975 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5976 VT.getSizeInBits()));
5977 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005978 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00005979 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005980 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00005981 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00005982 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5983 SDValue Reduced = ReduceLoadWidth(N);
5984 if (Reduced.getNode())
5985 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00005986 // Handle the case where the load remains an extending load even
5987 // after truncation.
5988 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5989 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5990 if (!LN0->isVolatile() &&
5991 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5992 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5993 VT, LN0->getChain(), LN0->getBasePtr(),
5994 LN0->getMemoryVT(),
5995 LN0->getMemOperand());
5996 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5997 return NewLoad;
5998 }
5999 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006000 }
Michael Liao3ac82012012-10-17 23:45:54 +00006001 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6002 // where ... are all 'undef'.
6003 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6004 SmallVector<EVT, 8> VTs;
6005 SDValue V;
6006 unsigned Idx = 0;
6007 unsigned NumDefs = 0;
6008
6009 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6010 SDValue X = N0.getOperand(i);
6011 if (X.getOpcode() != ISD::UNDEF) {
6012 V = X;
6013 Idx = i;
6014 NumDefs++;
6015 }
6016 // Stop if more than one members are non-undef.
6017 if (NumDefs > 1)
6018 break;
6019 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6020 VT.getVectorElementType(),
6021 X.getValueType().getVectorNumElements()));
6022 }
6023
6024 if (NumDefs == 0)
6025 return DAG.getUNDEF(VT);
6026
6027 if (NumDefs == 1) {
6028 assert(V.getNode() && "The single defined operand is empty!");
6029 SmallVector<SDValue, 8> Opnds;
6030 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6031 if (i != Idx) {
6032 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6033 continue;
6034 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006035 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00006036 AddToWorkList(NV.getNode());
6037 Opnds.push_back(NV);
6038 }
Craig Topper48d114b2014-04-26 18:35:24 +00006039 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006040 }
6041 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006042
6043 // Simplify the operands using demanded-bits information.
6044 if (!VT.isVector() &&
6045 SimplifyDemandedBits(SDValue(N, 0)))
6046 return SDValue(N, 0);
6047
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006048 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006049}
6050
Evan Chengb980f6f2008-05-12 23:04:07 +00006051static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006052 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006053 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006054 return Elt.getNode();
6055 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006056}
6057
6058/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006059/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006060SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006061 assert(N->getOpcode() == ISD::BUILD_PAIR);
6062
Nate Begeman624690c2009-06-05 21:37:30 +00006063 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6064 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006065 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006066 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006067 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006068 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006069
Evan Chengb980f6f2008-05-12 23:04:07 +00006070 if (ISD::isNON_EXTLoad(LD2) &&
6071 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006072 // If both are volatile this would reduce the number of volatile loads.
6073 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006074 !LD1->isVolatile() &&
6075 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006076 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006077 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006078 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006079 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006080
Duncan Sands8651e9c2008-06-13 19:07:40 +00006081 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006082 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006083 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006084 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006085 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006086 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006087
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006088 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006089}
6090
Wesley Peck527da1b2010-11-23 03:31:01 +00006091SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006092 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006093 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006094
Dan Gohmana8665142007-06-25 16:23:39 +00006095 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6096 // Only do this before legalize, since afterward the target may be depending
6097 // on the bitconvert.
6098 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006099 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006100 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006101 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006102 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006103
Owen Anderson53aa7a92009-08-10 22:56:29 +00006104 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006105 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006106 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006107 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006108 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006109 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006110
Dan Gohman921ddd62008-09-05 01:58:21 +00006111 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006112 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006113 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006114 if (Res.getNode() != N) {
6115 if (!LegalOperations ||
6116 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6117 return Res;
6118
6119 // Folding it resulted in an illegal node, and it's too late to
6120 // do that. Clean up the old node and forego the transformation.
6121 // Ideally this won't happen very often, because instcombine
6122 // and the earlier dagcombine runs (where illegal nodes are
6123 // permitted) should have folded most of them already.
6124 DAG.DeleteNode(Res.getNode());
6125 }
Chris Lattnera1874602005-12-23 05:30:37 +00006126 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006127
Bill Wendling4e0a6152009-01-30 22:44:24 +00006128 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006129 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006130 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006131 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006132
Chris Lattner54560f62005-12-23 05:44:41 +00006133 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006134 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006135 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006136 // Do not change the width of a volatile load.
6137 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006138 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6139 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006140 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006141 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006142 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006143 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006144
Evan Chenga4cf58a2007-05-07 21:27:48 +00006145 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006146 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006147 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006148 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006149 LN0->isInvariant(), OrigAlign,
6150 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006151 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006152 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006153 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006154 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006155 Load.getValue(1));
6156 return Load;
6157 }
Chris Lattner54560f62005-12-23 05:44:41 +00006158 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006159
Bill Wendling4e0a6152009-01-30 22:44:24 +00006160 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6161 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006162 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006163 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6164 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006165 N0.getNode()->hasOneUse() && VT.isInteger() &&
6166 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006167 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006168 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006169 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006170
Duncan Sands13237ac2008-06-06 12:08:01 +00006171 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006172 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006173 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006174 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006175 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006176 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006177 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006178 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006179
Bill Wendling4e0a6152009-01-30 22:44:24 +00006180 // fold (bitconvert (fcopysign cst, x)) ->
6181 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6182 // Note that we don't handle (copysign x, cst) because this can always be
6183 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006184 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006185 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006186 VT.isInteger() && !VT.isVector()) {
6187 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006188 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006189 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006190 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006191 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006192 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006193
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006194 // If X has a different width than the result/lhs, sext it or truncate it.
6195 unsigned VTWidth = VT.getSizeInBits();
6196 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006197 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006198 AddToWorkList(X.getNode());
6199 } else if (OrigXWidth > VTWidth) {
6200 // To get the sign bit in the right place, we have to shift it right
6201 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006202 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006203 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006204 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6205 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006206 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006207 AddToWorkList(X.getNode());
6208 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006209
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006210 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006211 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006212 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006213 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006214
Andrew Trickef9de2a2013-05-25 02:42:55 +00006215 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006216 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006217 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006218 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006219 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006220
Andrew Trickef9de2a2013-05-25 02:42:55 +00006221 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006222 }
Chris Lattner888560d2008-01-27 17:42:27 +00006223 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006224
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006225 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006226 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006227 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6228 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006229 return CombineLD;
6230 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006231
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006232 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006233}
6234
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006235SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006236 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006237 return CombineConsecutiveLoads(N, VT);
6238}
6239
Wesley Peck527da1b2010-11-23 03:31:01 +00006240/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006241/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006242/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006243SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006244ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006245 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006246
Chris Lattnere4e64b62006-04-02 02:53:43 +00006247 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006248 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006249
Duncan Sands13237ac2008-06-06 12:08:01 +00006250 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6251 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006252
Chris Lattnere4e64b62006-04-02 02:53:43 +00006253 // If this is a conversion of N elements of one type to N elements of another
6254 // type, convert each element. This handles FP<->INT cases.
6255 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006256 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6257 BV->getValueType(0).getVectorNumElements());
6258
6259 // Due to the FP element handling below calling this routine recursively,
6260 // we can end up with a scalar-to-vector node here.
6261 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006262 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6263 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006264 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006265
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006266 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006267 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006268 SDValue Op = BV->getOperand(i);
6269 // If the vector element type is not legal, the BUILD_VECTOR operands
6270 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006271 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006272 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6273 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006274 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006275 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006276 }
Craig Topper48d114b2014-04-26 18:35:24 +00006277 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006278 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006279
Chris Lattnere4e64b62006-04-02 02:53:43 +00006280 // Otherwise, we're growing or shrinking the elements. To avoid having to
6281 // handle annoying details of growing/shrinking FP values, we convert them to
6282 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006283 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006284 // Convert the input float vector to a int vector where the elements are the
6285 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006286 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006287 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006288 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006289 SrcEltVT = IntVT;
6290 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006291
Chris Lattnere4e64b62006-04-02 02:53:43 +00006292 // Now we know the input is an integer vector. If the output is a FP type,
6293 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006294 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006295 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006296 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006297 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006298
Chris Lattnere4e64b62006-04-02 02:53:43 +00006299 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006300 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006301 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006302
Chris Lattnere4e64b62006-04-02 02:53:43 +00006303 // Okay, we know the src/dst types are both integers of differing types.
6304 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006305 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006306 if (SrcBitSize < DstBitSize) {
6307 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006308
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006309 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006310 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006311 i += NumInputsPerOutput) {
6312 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006313 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006314 bool EltIsUndef = true;
6315 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6316 // Shift the previously computed bits over.
6317 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006318 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006319 if (Op.getOpcode() == ISD::UNDEF) continue;
6320 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006321
Jay Foad583abbc2010-12-07 08:25:19 +00006322 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006323 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006324 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006325
Chris Lattnere4e64b62006-04-02 02:53:43 +00006326 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006327 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006328 else
6329 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6330 }
6331
Owen Anderson117c9e82009-08-12 00:36:31 +00006332 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006333 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006334 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006335
Chris Lattnere4e64b62006-04-02 02:53:43 +00006336 // Finally, this must be the case where we are shrinking elements: each input
6337 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006338 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006339 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006340 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6341 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006342 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006343
Dan Gohmana8665142007-06-25 16:23:39 +00006344 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006345 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6346 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006347 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006348 continue;
6349 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006350
Jay Foad583abbc2010-12-07 08:25:19 +00006351 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6352 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006353
Chris Lattnere4e64b62006-04-02 02:53:43 +00006354 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006355 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006356 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006357 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006358 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006359 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006360 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006361 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006362 }
6363
6364 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006365 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006366 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6367 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006368
Craig Topper48d114b2014-04-26 18:35:24 +00006369 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006370}
6371
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006372SDValue DAGCombiner::visitFADD(SDNode *N) {
6373 SDValue N0 = N->getOperand(0);
6374 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006375 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6376 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006377 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006378
Dan Gohmana8665142007-06-25 16:23:39 +00006379 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006380 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006381 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006382 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006383 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006384
Lang Hamesa33db652012-06-14 20:37:15 +00006385 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006386 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006387 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006388 // canonicalize constant to RHS
6389 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006390 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006391 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006392 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6393 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006394 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006395 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006396 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006397 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006398 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006399 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006400 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006401 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006402 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006403 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006404 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006405
Chris Lattner0199fd62007-01-08 23:04:05 +00006406 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006407 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6408 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6409 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006410 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6411 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006412 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006413
Shuxin Yang93b1f122013-03-25 22:52:29 +00006414 // No FP constant should be created after legalization as Instruction
6415 // Selection pass has hard time in dealing with FP constant.
6416 //
6417 // We don't need test this condition for transformation like following, as
6418 // the DAG being transformed implies it is legal to take FP constant as
6419 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006420 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006421 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006422 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006423 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6424
Owen Andersonb351c8d2012-11-01 02:00:53 +00006425 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006426 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006427 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006428 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006429
6430 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006431 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006432 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006433 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006434
Owen Andersoncc61f872012-08-30 23:35:16 +00006435 // In unsafe math mode, we can fold chains of FADD's of the same value
6436 // into multiplications. This transform is not safe in general because
6437 // we are reducing the number of rounding steps.
6438 if (DAG.getTarget().Options.UnsafeFPMath &&
6439 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6440 !N0CFP && !N1CFP) {
6441 if (N0.getOpcode() == ISD::FMUL) {
6442 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6443 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6444
Stephen Line31f2d22013-06-14 18:17:35 +00006445 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006446 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006447 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006448 SDValue(CFP00, 0),
6449 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006450 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006451 N1, NewCFP);
6452 }
6453
Stephen Line31f2d22013-06-14 18:17:35 +00006454 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006455 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006456 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006457 SDValue(CFP01, 0),
6458 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006459 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006460 N1, NewCFP);
6461 }
6462
Stephen Line31f2d22013-06-14 18:17:35 +00006463 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006464 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6465 N1.getOperand(0) == N1.getOperand(1) &&
6466 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006467 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006468 SDValue(CFP00, 0),
6469 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006470 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006471 N0.getOperand(1), NewCFP);
6472 }
6473
Stephen Line31f2d22013-06-14 18:17:35 +00006474 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006475 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6476 N1.getOperand(0) == N1.getOperand(1) &&
6477 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006478 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006479 SDValue(CFP01, 0),
6480 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006481 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006482 N0.getOperand(0), NewCFP);
6483 }
6484 }
6485
6486 if (N1.getOpcode() == ISD::FMUL) {
6487 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6488 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6489
Stephen Line31f2d22013-06-14 18:17:35 +00006490 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006491 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006492 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006493 SDValue(CFP10, 0),
6494 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006495 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006496 N0, NewCFP);
6497 }
6498
Stephen Line31f2d22013-06-14 18:17:35 +00006499 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006500 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006501 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006502 SDValue(CFP11, 0),
6503 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006504 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006505 N0, NewCFP);
6506 }
6507
Owen Andersoncc61f872012-08-30 23:35:16 +00006508
Stephen Line31f2d22013-06-14 18:17:35 +00006509 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6510 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6511 N0.getOperand(0) == N0.getOperand(1) &&
6512 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006513 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006514 SDValue(CFP10, 0),
6515 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006516 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006517 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006518 }
6519
Stephen Line31f2d22013-06-14 18:17:35 +00006520 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6521 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6522 N0.getOperand(0) == N0.getOperand(1) &&
6523 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006524 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006525 SDValue(CFP11, 0),
6526 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006527 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006528 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006529 }
6530 }
6531
Shuxin Yang93b1f122013-03-25 22:52:29 +00006532 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006533 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006534 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006535 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006536 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006538 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006539 }
6540
Shuxin Yang93b1f122013-03-25 22:52:29 +00006541 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006542 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006543 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006544 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006545 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006546 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006547 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006548 }
6549
Stephen Lin4e69d012013-06-14 21:33:58 +00006550 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006551 if (AllowNewFpConst &&
6552 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006553 N0.getOperand(0) == N0.getOperand(1) &&
6554 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006555 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006556 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006557 N0.getOperand(0),
6558 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006559 }
6560
Lang Hames39fb1d02012-06-19 22:51:23 +00006561 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006562 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006563 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006564 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6565 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006566
6567 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006568 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006569 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006570 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006571
Michael Liaoec3850122012-09-01 04:09:16 +00006572 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006573 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006574 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006575 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006576 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006577 }
6578
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006579 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006580}
6581
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006582SDValue DAGCombiner::visitFSUB(SDNode *N) {
6583 SDValue N0 = N->getOperand(0);
6584 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006585 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6586 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006587 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006588 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006589
Dan Gohmana8665142007-06-25 16:23:39 +00006590 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006591 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006592 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006593 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006594 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006595
Nate Begeman418c6e42005-10-18 00:28:13 +00006596 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006597 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006598 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006599 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006600 if (DAG.getTarget().Options.UnsafeFPMath &&
6601 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006602 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006603 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006604 if (DAG.getTarget().Options.UnsafeFPMath &&
6605 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006606 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006607 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006608 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006609 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006610 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006611 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006612 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006613 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006614 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006615
Bill Wendlingdf170db2012-03-15 05:12:00 +00006616 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006617 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006618 // (fsub x, (fadd x, y)) -> (fneg y) &
6619 // (fsub x, (fadd y, x)) -> (fneg y)
6620 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006621 if (N0 == N1)
6622 return DAG.getConstantFP(0.0f, VT);
6623
Bill Wendlingdf170db2012-03-15 05:12:00 +00006624 if (N1.getOpcode() == ISD::FADD) {
6625 SDValue N10 = N1->getOperand(0);
6626 SDValue N11 = N1->getOperand(1);
6627
6628 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6629 &DAG.getTarget().Options))
6630 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006631
Stephen Lin8e8424e2013-07-09 00:44:49 +00006632 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6633 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006634 return GetNegatedExpression(N10, DAG, LegalOperations);
6635 }
6636 }
6637
Lang Hames39fb1d02012-06-19 22:51:23 +00006638 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006639 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006640 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006641 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6642 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006643
6644 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006645 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006646 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006647 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006648 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006649
6650 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6651 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006652 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006653 return DAG.getNode(ISD::FMA, dl, VT,
6654 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006655 N1.getOperand(0)),
6656 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006657
Stephen Lin8e8424e2013-07-09 00:44:49 +00006658 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006659 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006660 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6661 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6662 SDValue N00 = N0.getOperand(0).getOperand(0);
6663 SDValue N01 = N0.getOperand(0).getOperand(1);
6664 return DAG.getNode(ISD::FMA, dl, VT,
6665 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6666 DAG.getNode(ISD::FNEG, dl, VT, N1));
6667 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006668 }
6669
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006670 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006671}
6672
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006673SDValue DAGCombiner::visitFMUL(SDNode *N) {
6674 SDValue N0 = N->getOperand(0);
6675 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006676 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6677 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006678 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006680
Dan Gohmana8665142007-06-25 16:23:39 +00006681 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006682 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006683 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006684 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006685 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006686
Nate Begemanec48a1b2005-10-17 20:40:11 +00006687 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006688 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006689 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006690 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006691 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006692 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006693 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006694 if (DAG.getTarget().Options.UnsafeFPMath &&
6695 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006696 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006697 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006698 if (DAG.getTarget().Options.UnsafeFPMath &&
6699 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006700 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006701 // fold (fmul A, 1.0) -> A
6702 if (N1CFP && N1CFP->isExactlyValue(1.0))
6703 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006704 // fold (fmul X, 2.0) -> (fadd X, X)
6705 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006706 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006707 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006708 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006709 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006710 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006711
Bill Wendling3dc5d242009-01-30 22:57:07 +00006712 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006713 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006714 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006715 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006716 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006717 // Both can be negated for free, check to see if at least one is cheaper
6718 // negated.
6719 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006720 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006721 GetNegatedExpression(N0, DAG, LegalOperations),
6722 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006723 }
6724 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006725
Chris Lattner0199fd62007-01-08 23:04:05 +00006726 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006727 if (DAG.getTarget().Options.UnsafeFPMath &&
6728 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006729 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006730 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6731 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006732 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006733
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006734 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006735}
6736
Owen Anderson41b06652012-05-02 22:17:40 +00006737SDValue DAGCombiner::visitFMA(SDNode *N) {
6738 SDValue N0 = N->getOperand(0);
6739 SDValue N1 = N->getOperand(1);
6740 SDValue N2 = N->getOperand(2);
6741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6742 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6743 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006744 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006745
Owen Andersonb351c8d2012-11-01 02:00:53 +00006746 if (DAG.getTarget().Options.UnsafeFPMath) {
6747 if (N0CFP && N0CFP->isZero())
6748 return N2;
6749 if (N1CFP && N1CFP->isZero())
6750 return N2;
6751 }
Owen Anderson41b06652012-05-02 22:17:40 +00006752 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006753 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006754 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006755 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006756
Owen Andersonc7aaf522012-05-30 18:50:39 +00006757 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006758 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006759 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006760
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006761 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6762 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6763 N2.getOpcode() == ISD::FMUL &&
6764 N0 == N2.getOperand(0) &&
6765 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6766 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6767 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6768 }
6769
6770
6771 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6772 if (DAG.getTarget().Options.UnsafeFPMath &&
6773 N0.getOpcode() == ISD::FMUL && N1CFP &&
6774 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6775 return DAG.getNode(ISD::FMA, dl, VT,
6776 N0.getOperand(0),
6777 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6778 N2);
6779 }
6780
6781 // (fma x, 1, y) -> (fadd x, y)
6782 // (fma x, -1, y) -> (fadd (fneg x), y)
6783 if (N1CFP) {
6784 if (N1CFP->isExactlyValue(1.0))
6785 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6786
6787 if (N1CFP->isExactlyValue(-1.0) &&
6788 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6789 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6790 AddToWorkList(RHSNeg.getNode());
6791 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6792 }
6793 }
6794
6795 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006796 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6797 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006798 DAG.getNode(ISD::FADD, dl, VT,
6799 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006800
6801 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6802 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006803 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6804 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006805 DAG.getNode(ISD::FADD, dl, VT,
6806 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006807
6808
Owen Anderson41b06652012-05-02 22:17:40 +00006809 return SDValue();
6810}
6811
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006812SDValue DAGCombiner::visitFDIV(SDNode *N) {
6813 SDValue N0 = N->getOperand(0);
6814 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006815 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6816 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006817 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006818 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006819
Dan Gohmana8665142007-06-25 16:23:39 +00006820 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006821 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006822 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006823 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006825
Nate Begeman569c4392006-01-18 22:35:16 +00006826 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006827 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006828 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006829
Duncan Sands2f1dc382012-04-08 18:08:12 +00006830 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006831 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006832 // Compute the reciprocal 1.0 / c2.
6833 APFloat N1APF = N1CFP->getValueAPF();
6834 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6835 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006836 // Only do the transform if the reciprocal is a legal fp immediate that
6837 // isn't too nasty (eg NaN, denormal, ...).
6838 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006839 (!LegalOperations ||
6840 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6841 // backend)... we should handle this gracefully after Legalize.
6842 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6843 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6844 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006845 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006846 DAG.getConstantFP(Recip, VT));
6847 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006848
Bill Wendling3dc5d242009-01-30 22:57:07 +00006849 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006850 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006851 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006852 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006853 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006854 // Both can be negated for free, check to see if at least one is cheaper
6855 // negated.
6856 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006857 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006858 GetNegatedExpression(N0, DAG, LegalOperations),
6859 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006860 }
6861 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006862
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006863 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006864}
6865
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006866SDValue DAGCombiner::visitFREM(SDNode *N) {
6867 SDValue N0 = N->getOperand(0);
6868 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006869 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6870 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006871 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006872
Nate Begeman569c4392006-01-18 22:35:16 +00006873 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006874 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006875 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006876
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006877 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006878}
6879
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006880SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6881 SDValue N0 = N->getOperand(0);
6882 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006883 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6884 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006885 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006886
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006887 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006888 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006889
Chris Lattner3bc40502006-03-05 05:30:57 +00006890 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006891 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006892 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6893 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006894 if (!V.isNegative()) {
6895 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006896 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006897 } else {
6898 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006899 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6900 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006901 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006902 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006903
Chris Lattner3bc40502006-03-05 05:30:57 +00006904 // copysign(fabs(x), y) -> copysign(x, y)
6905 // copysign(fneg(x), y) -> copysign(x, y)
6906 // copysign(copysign(x,z), y) -> copysign(x, y)
6907 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6908 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006909 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006910 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006911
6912 // copysign(x, abs(y)) -> abs(x)
6913 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006914 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006915
Chris Lattner3bc40502006-03-05 05:30:57 +00006916 // copysign(x, copysign(y,z)) -> copysign(x, z)
6917 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006918 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006919 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006920
Chris Lattner3bc40502006-03-05 05:30:57 +00006921 // copysign(x, fp_extend(y)) -> copysign(x, y)
6922 // copysign(x, fp_round(y)) -> copysign(x, y)
6923 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006924 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006925 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006926
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006927 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006928}
6929
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006930SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6931 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006932 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006933 EVT VT = N->getValueType(0);
6934 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006935
Nate Begeman21158fc2005-09-01 00:19:25 +00006936 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006937 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006938 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006939 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006940 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006941 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006942
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006943 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6944 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006945 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6946 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006947 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006948 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006949 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006950 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006951
Alp Tokercb402912014-01-24 17:20:08 +00006952 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006953 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6954 // having to say they don't support SELECT_CC on every type the DAG knows
6955 // about, since there is no way to mark an opcode illegal at all value types
6956 // (See also visitSELECT)
6957 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6958 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6959 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6960 !VT.isVector() &&
6961 (!LegalOperations ||
6962 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6963 SDValue Ops[] =
6964 { N0.getOperand(0), N0.getOperand(1),
6965 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6966 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00006967 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00006968 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006969
Nadav Rotem90560762012-07-23 07:59:50 +00006970 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6971 // (select_cc x, y, 1.0, 0.0,, cc)
6972 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6973 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6974 (!LegalOperations ||
6975 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6976 SDValue Ops[] =
6977 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6978 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6979 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00006980 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00006981 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006982 }
6983
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006984 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006985}
6986
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006987SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6988 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006989 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006990 EVT VT = N->getValueType(0);
6991 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00006992
Nate Begeman21158fc2005-09-01 00:19:25 +00006993 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006994 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006995 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006996 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006997 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006998 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006999
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007000 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7001 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007002 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7003 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007004 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007005 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007006 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007007 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007008
Alp Tokercb402912014-01-24 17:20:08 +00007009 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00007010 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7011 // having to say they don't support SELECT_CC on every type the DAG knows
7012 // about, since there is no way to mark an opcode illegal at all value types
7013 // (See also visitSELECT)
7014 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7015 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007016
Nadav Rotem90560762012-07-23 07:59:50 +00007017 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7018 (!LegalOperations ||
7019 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7020 SDValue Ops[] =
7021 { N0.getOperand(0), N0.getOperand(1),
7022 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7023 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007024 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007025 }
7026 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007027
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007028 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007029}
7030
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007031SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7032 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007033 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007034 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007035
Nate Begeman21158fc2005-09-01 00:19:25 +00007036 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007037 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007038 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007039
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007040 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007041}
7042
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007043SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7044 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007045 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007046 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007047
Nate Begeman21158fc2005-09-01 00:19:25 +00007048 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007049 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007050 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007051
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007052 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007053}
7054
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007055SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7056 SDValue N0 = N->getOperand(0);
7057 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007058 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007059 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007060
Nate Begeman21158fc2005-09-01 00:19:25 +00007061 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007062 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007063 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007064
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007065 // fold (fp_round (fp_extend x)) -> x
7066 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7067 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007068
Chris Lattner0feb1b02008-01-24 06:45:35 +00007069 // fold (fp_round (fp_round x)) -> (fp_round x)
7070 if (N0.getOpcode() == ISD::FP_ROUND) {
7071 // This is a value preserving truncation if both round's are.
7072 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007073 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007074 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007075 DAG.getIntPtrConstant(IsTrunc));
7076 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007077
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007078 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007079 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007080 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007081 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007082 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007083 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007084 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007085 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007086
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007087 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007088}
7089
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007090SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7091 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007092 EVT VT = N->getValueType(0);
7093 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007094 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007095
Nate Begeman21158fc2005-09-01 00:19:25 +00007096 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007097 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007098 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007099 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007100 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007101
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007102 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007103}
7104
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007105SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7106 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007107 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007108 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007109
Chris Lattner5919b482007-12-29 06:55:23 +00007110 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007111 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007112 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007113 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007114
Nate Begeman21158fc2005-09-01 00:19:25 +00007115 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007116 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007117 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007118
7119 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7120 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007121 if (N0.getOpcode() == ISD::FP_ROUND
7122 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007123 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007124 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007125 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007126 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007127 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007128 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007129 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007130
Chris Lattner72733e52008-01-17 07:00:52 +00007131 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007132 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007133 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007134 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007135 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007136 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007137 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007138 LN0->getBasePtr(), N0.getValueType(),
7139 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007140 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007141 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007142 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007143 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007144 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007145 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007146 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007147
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007148 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007149}
7150
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007151SDValue DAGCombiner::visitFNEG(SDNode *N) {
7152 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007153 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007154
Craig Topper82384612012-09-11 01:45:21 +00007155 if (VT.isVector()) {
7156 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7157 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007158 }
7159
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007160 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7161 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007162 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007163
Chris Lattner888560d2008-01-27 17:42:27 +00007164 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7165 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007166 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007167 !VT.isVector() &&
7168 N0.getNode()->hasOneUse() &&
7169 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007170 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007171 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007172 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007173 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007174 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007175 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007176 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007177 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007178 }
7179 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007180
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007181 // (fneg (fmul c, x)) -> (fmul -c, x)
7182 if (N0.getOpcode() == ISD::FMUL) {
7183 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007184 if (CFP1) {
7185 APFloat CVal = CFP1->getValueAPF();
7186 CVal.changeSign();
7187 if (Level >= AfterLegalizeDAG &&
7188 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7189 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7190 return DAG.getNode(
7191 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7192 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7193 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007194 }
7195
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007196 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007197}
7198
Owen Andersona40319b2012-08-13 23:32:49 +00007199SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7200 SDValue N0 = N->getOperand(0);
7201 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7202 EVT VT = N->getValueType(0);
7203
7204 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007205 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007206 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007207
7208 return SDValue();
7209}
7210
7211SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7212 SDValue N0 = N->getOperand(0);
7213 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7214 EVT VT = N->getValueType(0);
7215
7216 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007217 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007218 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007219
7220 return SDValue();
7221}
7222
7223SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7224 SDValue N0 = N->getOperand(0);
7225 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7226 EVT VT = N->getValueType(0);
7227
7228 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007229 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007230 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007231
7232 return SDValue();
7233}
7234
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007235SDValue DAGCombiner::visitFABS(SDNode *N) {
7236 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007237 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007238 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007239
Craig Topper82384612012-09-11 01:45:21 +00007240 if (VT.isVector()) {
7241 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7242 if (FoldedVOp.getNode()) return FoldedVOp;
7243 }
7244
Nate Begeman21158fc2005-09-01 00:19:25 +00007245 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007246 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007247 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007248 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007249 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007250 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007251 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007252 // fold (fabs (fcopysign x, y)) -> (fabs x)
7253 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007254 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007255
Chris Lattner888560d2008-01-27 17:42:27 +00007256 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7257 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007258 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007259 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007260 N0.getOperand(0).getValueType().isInteger() &&
7261 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007262 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007263 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007264 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007265 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007266 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007267 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007268 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007269 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007270 }
7271 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007272
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007273 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007274}
7275
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007276SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7277 SDValue Chain = N->getOperand(0);
7278 SDValue N1 = N->getOperand(1);
7279 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007280
Dan Gohman82e80012009-11-17 00:47:23 +00007281 // If N is a constant we could fold this into a fallthrough or unconditional
7282 // branch. However that doesn't happen very often in normal code, because
7283 // Instcombine/SimplifyCFG should have handled the available opportunities.
7284 // If we did this folding here, it would be necessary to update the
7285 // MachineBasicBlock CFG, which is awkward.
7286
Nate Begeman7e7f4392006-02-01 07:19:44 +00007287 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7288 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007289 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007290 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7291 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007292 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007293 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007294 N1.getOperand(0), N1.getOperand(1), N2);
7295 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007296
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007297 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7298 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7299 (N1.getOperand(0).hasOneUse() &&
7300 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007301 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007302 if (N1.getOpcode() == ISD::TRUNCATE) {
7303 // Look pass the truncate.
7304 Trunc = N1.getNode();
7305 N1 = N1.getOperand(0);
7306 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007307
Bill Wendlingaa28be62009-03-26 06:14:09 +00007308 // Match this pattern so that we can generate simpler code:
7309 //
7310 // %a = ...
7311 // %b = and i32 %a, 2
7312 // %c = srl i32 %b, 1
7313 // brcond i32 %c ...
7314 //
7315 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007316 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007317 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007318 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007319 // %c = setcc eq %b, 0
7320 // brcond %c ...
7321 //
7322 // This applies only when the AND constant value has one bit set and the
7323 // SRL constant is equal to the log2 of the AND constant. The back-end is
7324 // smart enough to convert the result into a TEST/JMP sequence.
7325 SDValue Op0 = N1.getOperand(0);
7326 SDValue Op1 = N1.getOperand(1);
7327
7328 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007329 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007330 SDValue AndOp1 = Op0.getOperand(1);
7331
7332 if (AndOp1.getOpcode() == ISD::Constant) {
7333 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7334
7335 if (AndConst.isPowerOf2() &&
7336 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7337 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007338 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007339 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007340 Op0, DAG.getConstant(0, Op0.getValueType()),
7341 ISD::SETNE);
7342
Andrew Trickef9de2a2013-05-25 02:42:55 +00007343 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007344 MVT::Other, Chain, SetCC, N2);
7345 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7346 // will convert it back to (X & C1) >> C2.
7347 CombineTo(N, NewBRCond, false);
7348 // Truncate is dead.
7349 if (Trunc) {
7350 removeFromWorkList(Trunc);
7351 DAG.DeleteNode(Trunc);
7352 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007353 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007354 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007355 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007356 removeFromWorkList(N1.getNode());
7357 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007358 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007359 }
7360 }
7361 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007362
7363 if (Trunc)
7364 // Restore N1 if the above transformation doesn't match.
7365 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007366 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007367
Evan Cheng228c31f2010-02-27 07:36:59 +00007368 // Transform br(xor(x, y)) -> br(x != y)
7369 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7370 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7371 SDNode *TheXor = N1.getNode();
7372 SDValue Op0 = TheXor->getOperand(0);
7373 SDValue Op1 = TheXor->getOperand(1);
7374 if (Op0.getOpcode() == Op1.getOpcode()) {
7375 // Avoid missing important xor optimizations.
7376 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007377 if (Tmp.getNode()) {
7378 if (Tmp.getNode() != TheXor) {
7379 DEBUG(dbgs() << "\nReplacing.8 ";
7380 TheXor->dump(&DAG);
7381 dbgs() << "\nWith: ";
7382 Tmp.getNode()->dump(&DAG);
7383 dbgs() << '\n');
7384 WorkListRemover DeadNodes(*this);
7385 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7386 removeFromWorkList(TheXor);
7387 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007388 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007389 MVT::Other, Chain, Tmp, N2);
7390 }
7391
Benjamin Kramer93354432013-03-30 21:28:18 +00007392 // visitXOR has changed XOR's operands or replaced the XOR completely,
7393 // bail out.
7394 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007395 }
7396 }
7397
7398 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7399 bool Equal = false;
7400 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7401 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7402 Op0.getOpcode() == ISD::XOR) {
7403 TheXor = Op0.getNode();
7404 Equal = true;
7405 }
7406
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007407 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007408 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007409 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007410 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007411 SetCCVT,
7412 Op0, Op1,
7413 Equal ? ISD::SETEQ : ISD::SETNE);
7414 // Replace the uses of XOR with SETCC
7415 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007416 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007417 removeFromWorkList(N1.getNode());
7418 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007419 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007420 MVT::Other, Chain, SetCC, N2);
7421 }
7422 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007423
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007424 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007425}
7426
Chris Lattnera49e16f2005-10-05 06:47:48 +00007427// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7428//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007429SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007430 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007431 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007432
Dan Gohman82e80012009-11-17 00:47:23 +00007433 // If N is a constant we could fold this into a fallthrough or unconditional
7434 // branch. However that doesn't happen very often in normal code, because
7435 // Instcombine/SimplifyCFG should have handled the available opportunities.
7436 // If we did this folding here, it would be necessary to update the
7437 // MachineBasicBlock CFG, which is awkward.
7438
Duncan Sands93b66092008-06-09 11:32:28 +00007439 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007440 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007441 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007442 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007443 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007444
Nate Begemanbd7df032005-10-05 21:43:42 +00007445 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007446 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007447 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007448 N->getOperand(0), Simp.getOperand(2),
7449 Simp.getOperand(0), Simp.getOperand(1),
7450 N->getOperand(4));
7451
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007452 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007453}
7454
Evan Chengfa832632012-01-13 01:37:24 +00007455/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7456/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007457/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007458static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7459 SelectionDAG &DAG,
7460 const TargetLowering &TLI) {
7461 EVT VT;
7462 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7463 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7464 return false;
7465 VT = Use->getValueType(0);
7466 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7467 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7468 return false;
7469 VT = ST->getValue().getValueType();
7470 } else
7471 return false;
7472
Chandler Carruth95f83e02013-01-07 15:14:13 +00007473 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007474 if (N->getOpcode() == ISD::ADD) {
7475 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7476 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007477 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007478 AM.BaseOffs = Offset->getSExtValue();
7479 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007480 // [reg +/- reg]
7481 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007482 } else if (N->getOpcode() == ISD::SUB) {
7483 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7484 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007485 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007486 AM.BaseOffs = -Offset->getSExtValue();
7487 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007488 // [reg +/- reg]
7489 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007490 } else
7491 return false;
7492
7493 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7494}
7495
Duncan Sands075293f2008-06-15 20:12:31 +00007496/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7497/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007498/// and it has other uses besides the load / store. After the
7499/// transformation, the new indexed load / store has effectively folded
7500/// the add / subtract in and all of its other uses are redirected to the
7501/// new load / store.
7502bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007503 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007504 return false;
7505
7506 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007507 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007508 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007509 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007510 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007511 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007512 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007513 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007514 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7515 return false;
7516 Ptr = LD->getBasePtr();
7517 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007518 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007519 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007520 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007521 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7522 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7523 return false;
7524 Ptr = ST->getBasePtr();
7525 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007526 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007527 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007528 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007529
Chris Lattnereabc15c2006-11-11 00:56:29 +00007530 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7531 // out. There is no reason to make this a preinc/predec.
7532 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007533 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007534 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007535
Chris Lattnereabc15c2006-11-11 00:56:29 +00007536 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007537 SDValue BasePtr;
7538 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007539 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7540 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7541 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007542
7543 // Backends without true r+i pre-indexed forms may need to pass a
7544 // constant base with a variable offset so that constant coercion
7545 // will work with the patterns in canonical form.
7546 bool Swapped = false;
7547 if (isa<ConstantSDNode>(BasePtr)) {
7548 std::swap(BasePtr, Offset);
7549 Swapped = true;
7550 }
7551
Evan Cheng044a0a82007-05-03 23:52:19 +00007552 // Don't create a indexed load / store with zero offset.
7553 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007554 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007555 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007556
Chris Lattnera0a80032006-11-11 01:00:15 +00007557 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007558 // 1) The new base ptr is a frame index.
7559 // 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 +00007560 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007561 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007562 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007563 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007564
Chris Lattnera0a80032006-11-11 01:00:15 +00007565 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7566 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007567 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007568 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007569
Chris Lattnera0a80032006-11-11 01:00:15 +00007570 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007571 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007572 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007573 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007574 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007575 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007576
Hal Finkel25819052013-02-08 21:35:47 +00007577 // If the offset is a constant, there may be other adds of constants that
7578 // can be folded with this one. We should do this to avoid having to keep
7579 // a copy of the original base pointer.
7580 SmallVector<SDNode *, 16> OtherUses;
7581 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007582 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007583 if (Use == Ptr.getNode())
7584 continue;
7585
7586 if (Use->isPredecessorOf(N))
7587 continue;
7588
7589 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7590 OtherUses.clear();
7591 break;
7592 }
7593
7594 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7595 if (Op1.getNode() == BasePtr.getNode())
7596 std::swap(Op0, Op1);
7597 assert(Op0.getNode() == BasePtr.getNode() &&
7598 "Use of ADD/SUB but not an operand");
7599
7600 if (!isa<ConstantSDNode>(Op1)) {
7601 OtherUses.clear();
7602 break;
7603 }
7604
7605 // FIXME: In some cases, we can be smarter about this.
7606 if (Op1.getValueType() != Offset.getValueType()) {
7607 OtherUses.clear();
7608 break;
7609 }
7610
7611 OtherUses.push_back(Use);
7612 }
7613
7614 if (Swapped)
7615 std::swap(BasePtr, Offset);
7616
Evan Chenga4d187b2007-05-24 02:35:39 +00007617 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007618 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007619
7620 // Caches for hasPredecessorHelper
7621 SmallPtrSet<const SDNode *, 32> Visited;
7622 SmallVector<const SDNode *, 16> Worklist;
7623
Jim Grosbache8160032014-04-11 01:13:13 +00007624 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007625 if (Use == N)
7626 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007627 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007628 return false;
7629
Evan Chengfa832632012-01-13 01:37:24 +00007630 // If Ptr may be folded in addressing mode of other use, then it's
7631 // not profitable to do this transformation.
7632 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007633 RealUse = true;
7634 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007635
Chris Lattnereabc15c2006-11-11 00:56:29 +00007636 if (!RealUse)
7637 return false;
7638
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007639 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007640 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007641 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007642 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007643 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007644 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007645 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007646 ++PreIndexedNodes;
7647 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007648 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007649 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007650 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007651 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007652 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007653 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007654 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007655 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7656 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007657 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007658 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007659 }
7660
Chris Lattnereabc15c2006-11-11 00:56:29 +00007661 // Finally, since the node is now dead, remove it from the graph.
7662 DAG.DeleteNode(N);
7663
Hal Finkel25819052013-02-08 21:35:47 +00007664 if (Swapped)
7665 std::swap(BasePtr, Offset);
7666
7667 // Replace other uses of BasePtr that can be updated to use Ptr
7668 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7669 unsigned OffsetIdx = 1;
7670 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7671 OffsetIdx = 0;
7672 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7673 BasePtr.getNode() && "Expected BasePtr operand");
7674
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007675 // We need to replace ptr0 in the following expression:
7676 // x0 * offset0 + y0 * ptr0 = t0
7677 // knowing that
7678 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007679 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007680 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7681 // indexed load/store and the expresion that needs to be re-written.
7682 //
7683 // Therefore, we have:
7684 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007685
7686 ConstantSDNode *CN =
7687 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007688 int X0, X1, Y0, Y1;
7689 APInt Offset0 = CN->getAPIntValue();
7690 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007691
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007692 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7693 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7694 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7695 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007696
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007697 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7698
7699 APInt CNV = Offset0;
7700 if (X0 < 0) CNV = -CNV;
7701 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7702 else CNV = CNV - Offset1;
7703
7704 // We can now generate the new expression.
7705 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7706 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7707
7708 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007709 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007710 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7711 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7712 removeFromWorkList(OtherUses[i]);
7713 DAG.DeleteNode(OtherUses[i]);
7714 }
7715
Chris Lattnereabc15c2006-11-11 00:56:29 +00007716 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007717 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007718 removeFromWorkList(Ptr.getNode());
7719 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007720
7721 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007722}
7723
Duncan Sands075293f2008-06-15 20:12:31 +00007724/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007725/// add / sub of the base pointer node into a post-indexed load / store.
7726/// The transformation folded the add / subtract into the new indexed
7727/// load / store effectively and all of its uses are redirected to the
7728/// new load / store.
7729bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007730 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007731 return false;
7732
7733 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007734 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007735 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007736 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007737 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007738 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007739 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007740 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7741 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7742 return false;
7743 Ptr = LD->getBasePtr();
7744 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007745 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007746 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007747 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007748 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7749 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7750 return false;
7751 Ptr = ST->getBasePtr();
7752 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007753 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007754 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007755 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007756
Gabor Greiff304a7a2008-08-28 21:40:38 +00007757 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007758 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007759
Jim Grosbache8160032014-04-11 01:13:13 +00007760 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007761 if (Op == N ||
7762 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7763 continue;
7764
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007765 SDValue BasePtr;
7766 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007767 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7768 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007769 // Don't create a indexed load / store with zero offset.
7770 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007771 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007772 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007773
Chris Lattnereabc15c2006-11-11 00:56:29 +00007774 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007775 // 1) All uses are load / store ops that use it as base ptr (and
7776 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007777 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7778 // nor a successor of N. Otherwise, if Op is folded that would
7779 // create a cycle.
7780
Evan Chengcfc05132009-05-06 18:25:01 +00007781 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7782 continue;
7783
Chris Lattnereabc15c2006-11-11 00:56:29 +00007784 // Check for #1.
7785 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007786 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007787 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007788 continue;
7789
Chris Lattnereabc15c2006-11-11 00:56:29 +00007790 // If all the uses are load / store addresses, then don't do the
7791 // transformation.
7792 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7793 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007794 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007795 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007796 RealUse = true;
7797 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007798
Chris Lattnereabc15c2006-11-11 00:56:29 +00007799 if (!RealUse) {
7800 TryNext = true;
7801 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007802 }
7803 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007804 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007805
Chris Lattnereabc15c2006-11-11 00:56:29 +00007806 if (TryNext)
7807 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007808
Chris Lattnereabc15c2006-11-11 00:56:29 +00007809 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007810 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007811 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007812 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007813 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007814 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007815 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007816 ++PostIndexedNodes;
7817 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007818 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007819 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007820 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007821 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007822 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007823 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007824 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007825 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7826 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007827 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007828 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007829 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007830
Chris Lattnereabc15c2006-11-11 00:56:29 +00007831 // Finally, since the node is now dead, remove it from the graph.
7832 DAG.DeleteNode(N);
7833
7834 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007835 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007836 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007837 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007838 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007839 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007840 }
7841 }
7842 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007843
Chris Lattnerffad2162006-11-11 00:39:41 +00007844 return false;
7845}
7846
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007847SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007848 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007849 SDValue Chain = LD->getChain();
7850 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007851
Evan Chenga684cd22007-05-01 00:38:21 +00007852 // If load is not volatile and there are no uses of the loaded value (and
7853 // the updated indexed value in case of indexed loads), change uses of the
7854 // chain value into uses of the chain input (i.e. delete the dead load).
7855 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007856 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007857 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007858 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007859 // It's not safe to use the two value CombineTo variant here. e.g.
7860 // v1, chain2 = load chain1, loc
7861 // v2, chain3 = load chain2, loc
7862 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007863 // Now we replace use of chain2 with chain1. This makes the second load
7864 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007865 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007866 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007867 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007868 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007869 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007870 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007871 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007872
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007873 if (N->use_empty()) {
7874 removeFromWorkList(N);
7875 DAG.DeleteNode(N);
7876 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007877
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007878 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007879 }
Evan Chengb68343c2007-05-01 08:53:39 +00007880 } else {
7881 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007882 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel2c77fe52014-05-28 15:33:19 +00007883 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007884 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007885 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007886 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007887 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007888 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007889 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007890 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007891 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel2c77fe52014-05-28 15:33:19 +00007892 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7893 DAG.getUNDEF(N->getValueType(1)));
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007894 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007895 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007896 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007897 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007898 }
Evan Chenga684cd22007-05-01 00:38:21 +00007899 }
7900 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007901
Chris Lattnere260ed82005-10-10 22:04:48 +00007902 // If this load is directly stored, replace the load value with the stored
7903 // value.
7904 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007905 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007906 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007907 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007908 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7909 if (PrevST->getBasePtr() == Ptr &&
7910 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007911 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007912 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007913 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007914
Evan Cheng43cd9e32010-04-01 06:04:33 +00007915 // Try to infer better alignment information than the load already has.
7916 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007917 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007918 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7919 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007920 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007921 LD->getValueType(0),
7922 Chain, Ptr, LD->getPointerInfo(),
7923 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007924 LD->isVolatile(), LD->isNonTemporal(), Align,
7925 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007926 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7927 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007928 }
7929 }
7930
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007931 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7932 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00007933#ifndef NDEBUG
7934 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7935 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7936 UseAA = false;
7937#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00007938 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007939 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007940 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007941
Jim Laskey708d0db2006-10-04 16:53:27 +00007942 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007943 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007944 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007945
Jim Laskeyd07be232006-09-25 16:29:54 +00007946 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007947 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007948 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007949 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007950 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007951 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007952 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007953 BetterChain, Ptr, LD->getMemoryVT(),
7954 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007955 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007956
Jim Laskey708d0db2006-10-04 16:53:27 +00007957 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007958 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007959 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007960
Nate Begeman879d8f12009-09-15 00:18:30 +00007961 // Make sure the new and old chains are cleaned up.
7962 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007963
Jim Laskeydcf983c2006-10-13 23:32:28 +00007964 // Replace uses with load result and token factor. Don't add users
7965 // to work list.
7966 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00007967 }
7968 }
7969
Evan Cheng357017f2006-11-03 03:06:21 +00007970 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00007971 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007972 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00007973
Quentin Colombetde0e0622013-10-11 18:29:42 +00007974 // Try to slice up N to more direct loads if the slices are mapped to
7975 // different register banks or pairing can take place.
7976 if (SliceUpLoad(N))
7977 return SDValue(N, 0);
7978
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007979 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00007980}
7981
Quentin Colombetde0e0622013-10-11 18:29:42 +00007982namespace {
7983/// \brief Helper structure used to slice a load in smaller loads.
7984/// Basically a slice is obtained from the following sequence:
7985/// Origin = load Ty1, Base
7986/// Shift = srl Ty1 Origin, CstTy Amount
7987/// Inst = trunc Shift to Ty2
7988///
7989/// Then, it will be rewriten into:
7990/// Slice = load SliceTy, Base + SliceOffset
7991/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7992///
7993/// SliceTy is deduced from the number of bits that are actually used to
7994/// build Inst.
7995struct LoadedSlice {
7996 /// \brief Helper structure used to compute the cost of a slice.
7997 struct Cost {
7998 /// Are we optimizing for code size.
7999 bool ForCodeSize;
8000 /// Various cost.
8001 unsigned Loads;
8002 unsigned Truncates;
8003 unsigned CrossRegisterBanksCopies;
8004 unsigned ZExts;
8005 unsigned Shift;
8006
8007 Cost(bool ForCodeSize = false)
8008 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8009 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8010
8011 /// \brief Get the cost of one isolated slice.
8012 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8013 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8014 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8015 EVT TruncType = LS.Inst->getValueType(0);
8016 EVT LoadedType = LS.getLoadedType();
8017 if (TruncType != LoadedType &&
8018 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8019 ZExts = 1;
8020 }
8021
8022 /// \brief Account for slicing gain in the current cost.
8023 /// Slicing provide a few gains like removing a shift or a
8024 /// truncate. This method allows to grow the cost of the original
8025 /// load with the gain from this slice.
8026 void addSliceGain(const LoadedSlice &LS) {
8027 // Each slice saves a truncate.
8028 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8029 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8030 LS.Inst->getOperand(0).getValueType()))
8031 ++Truncates;
8032 // If there is a shift amount, this slice gets rid of it.
8033 if (LS.Shift)
8034 ++Shift;
8035 // If this slice can merge a cross register bank copy, account for it.
8036 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8037 ++CrossRegisterBanksCopies;
8038 }
8039
8040 Cost &operator+=(const Cost &RHS) {
8041 Loads += RHS.Loads;
8042 Truncates += RHS.Truncates;
8043 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8044 ZExts += RHS.ZExts;
8045 Shift += RHS.Shift;
8046 return *this;
8047 }
8048
8049 bool operator==(const Cost &RHS) const {
8050 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8051 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8052 ZExts == RHS.ZExts && Shift == RHS.Shift;
8053 }
8054
8055 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8056
8057 bool operator<(const Cost &RHS) const {
8058 // Assume cross register banks copies are as expensive as loads.
8059 // FIXME: Do we want some more target hooks?
8060 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8061 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8062 // Unless we are optimizing for code size, consider the
8063 // expensive operation first.
8064 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8065 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8066 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8067 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8068 }
8069
8070 bool operator>(const Cost &RHS) const { return RHS < *this; }
8071
8072 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8073
8074 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8075 };
8076 // The last instruction that represent the slice. This should be a
8077 // truncate instruction.
8078 SDNode *Inst;
8079 // The original load instruction.
8080 LoadSDNode *Origin;
8081 // The right shift amount in bits from the original load.
8082 unsigned Shift;
8083 // The DAG from which Origin came from.
8084 // This is used to get some contextual information about legal types, etc.
8085 SelectionDAG *DAG;
8086
Craig Topperc0196b12014-04-14 00:51:57 +00008087 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8088 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008089 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8090
8091 LoadedSlice(const LoadedSlice &LS)
8092 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8093
8094 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8095 /// \return Result is \p BitWidth and has used bits set to 1 and
8096 /// not used bits set to 0.
8097 APInt getUsedBits() const {
8098 // Reproduce the trunc(lshr) sequence:
8099 // - Start from the truncated value.
8100 // - Zero extend to the desired bit width.
8101 // - Shift left.
8102 assert(Origin && "No original load to compare against.");
8103 unsigned BitWidth = Origin->getValueSizeInBits(0);
8104 assert(Inst && "This slice is not bound to an instruction");
8105 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8106 "Extracted slice is bigger than the whole type!");
8107 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8108 UsedBits.setAllBits();
8109 UsedBits = UsedBits.zext(BitWidth);
8110 UsedBits <<= Shift;
8111 return UsedBits;
8112 }
8113
8114 /// \brief Get the size of the slice to be loaded in bytes.
8115 unsigned getLoadedSize() const {
8116 unsigned SliceSize = getUsedBits().countPopulation();
8117 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8118 return SliceSize / 8;
8119 }
8120
8121 /// \brief Get the type that will be loaded for this slice.
8122 /// Note: This may not be the final type for the slice.
8123 EVT getLoadedType() const {
8124 assert(DAG && "Missing context");
8125 LLVMContext &Ctxt = *DAG->getContext();
8126 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8127 }
8128
8129 /// \brief Get the alignment of the load used for this slice.
8130 unsigned getAlignment() const {
8131 unsigned Alignment = Origin->getAlignment();
8132 unsigned Offset = getOffsetFromBase();
8133 if (Offset != 0)
8134 Alignment = MinAlign(Alignment, Alignment + Offset);
8135 return Alignment;
8136 }
8137
8138 /// \brief Check if this slice can be rewritten with legal operations.
8139 bool isLegal() const {
8140 // An invalid slice is not legal.
8141 if (!Origin || !Inst || !DAG)
8142 return false;
8143
8144 // Offsets are for indexed load only, we do not handle that.
8145 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8146 return false;
8147
8148 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8149
8150 // Check that the type is legal.
8151 EVT SliceType = getLoadedType();
8152 if (!TLI.isTypeLegal(SliceType))
8153 return false;
8154
8155 // Check that the load is legal for this type.
8156 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8157 return false;
8158
8159 // Check that the offset can be computed.
8160 // 1. Check its type.
8161 EVT PtrType = Origin->getBasePtr().getValueType();
8162 if (PtrType == MVT::Untyped || PtrType.isExtended())
8163 return false;
8164
8165 // 2. Check that it fits in the immediate.
8166 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8167 return false;
8168
8169 // 3. Check that the computation is legal.
8170 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8171 return false;
8172
8173 // Check that the zext is legal if it needs one.
8174 EVT TruncateType = Inst->getValueType(0);
8175 if (TruncateType != SliceType &&
8176 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8177 return false;
8178
8179 return true;
8180 }
8181
8182 /// \brief Get the offset in bytes of this slice in the original chunk of
8183 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008184 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008185 uint64_t getOffsetFromBase() const {
8186 assert(DAG && "Missing context.");
8187 bool IsBigEndian =
8188 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8189 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8190 uint64_t Offset = Shift / 8;
8191 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8192 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8193 "The size of the original loaded type is not a multiple of a"
8194 " byte.");
8195 // If Offset is bigger than TySizeInBytes, it means we are loading all
8196 // zeros. This should have been optimized before in the process.
8197 assert(TySizeInBytes > Offset &&
8198 "Invalid shift amount for given loaded size");
8199 if (IsBigEndian)
8200 Offset = TySizeInBytes - Offset - getLoadedSize();
8201 return Offset;
8202 }
8203
8204 /// \brief Generate the sequence of instructions to load the slice
8205 /// represented by this object and redirect the uses of this slice to
8206 /// this new sequence of instructions.
8207 /// \pre this->Inst && this->Origin are valid Instructions and this
8208 /// object passed the legal check: LoadedSlice::isLegal returned true.
8209 /// \return The last instruction of the sequence used to load the slice.
8210 SDValue loadSlice() const {
8211 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8212 const SDValue &OldBaseAddr = Origin->getBasePtr();
8213 SDValue BaseAddr = OldBaseAddr;
8214 // Get the offset in that chunk of bytes w.r.t. the endianess.
8215 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8216 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8217 if (Offset) {
8218 // BaseAddr = BaseAddr + Offset.
8219 EVT ArithType = BaseAddr.getValueType();
8220 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8221 DAG->getConstant(Offset, ArithType));
8222 }
8223
8224 // Create the type of the loaded slice according to its size.
8225 EVT SliceType = getLoadedType();
8226
8227 // Create the load for the slice.
8228 SDValue LastInst = DAG->getLoad(
8229 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8230 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8231 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8232 // If the final type is not the same as the loaded type, this means that
8233 // we have to pad with zero. Create a zero extend for that.
8234 EVT FinalType = Inst->getValueType(0);
8235 if (SliceType != FinalType)
8236 LastInst =
8237 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8238 return LastInst;
8239 }
8240
8241 /// \brief Check if this slice can be merged with an expensive cross register
8242 /// bank copy. E.g.,
8243 /// i = load i32
8244 /// f = bitcast i32 i to float
8245 bool canMergeExpensiveCrossRegisterBankCopy() const {
8246 if (!Inst || !Inst->hasOneUse())
8247 return false;
8248 SDNode *Use = *Inst->use_begin();
8249 if (Use->getOpcode() != ISD::BITCAST)
8250 return false;
8251 assert(DAG && "Missing context");
8252 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8253 EVT ResVT = Use->getValueType(0);
8254 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8255 const TargetRegisterClass *ArgRC =
8256 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8257 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8258 return false;
8259
8260 // At this point, we know that we perform a cross-register-bank copy.
8261 // Check if it is expensive.
8262 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8263 // Assume bitcasts are cheap, unless both register classes do not
8264 // explicitly share a common sub class.
8265 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8266 return false;
8267
8268 // Check if it will be merged with the load.
8269 // 1. Check the alignment constraint.
8270 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8271 ResVT.getTypeForEVT(*DAG->getContext()));
8272
8273 if (RequiredAlignment > getAlignment())
8274 return false;
8275
8276 // 2. Check that the load is a legal operation for that type.
8277 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8278 return false;
8279
8280 // 3. Check that we do not have a zext in the way.
8281 if (Inst->getValueType(0) != getLoadedType())
8282 return false;
8283
8284 return true;
8285 }
8286};
8287}
8288
Quentin Colombetde0e0622013-10-11 18:29:42 +00008289/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8290/// \p UsedBits looks like 0..0 1..1 0..0.
8291static bool areUsedBitsDense(const APInt &UsedBits) {
8292 // If all the bits are one, this is dense!
8293 if (UsedBits.isAllOnesValue())
8294 return true;
8295
8296 // Get rid of the unused bits on the right.
8297 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8298 // Get rid of the unused bits on the left.
8299 if (NarrowedUsedBits.countLeadingZeros())
8300 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8301 // Check that the chunk of bits is completely used.
8302 return NarrowedUsedBits.isAllOnesValue();
8303}
8304
8305/// \brief Check whether or not \p First and \p Second are next to each other
8306/// in memory. This means that there is no hole between the bits loaded
8307/// by \p First and the bits loaded by \p Second.
8308static bool areSlicesNextToEachOther(const LoadedSlice &First,
8309 const LoadedSlice &Second) {
8310 assert(First.Origin == Second.Origin && First.Origin &&
8311 "Unable to match different memory origins.");
8312 APInt UsedBits = First.getUsedBits();
8313 assert((UsedBits & Second.getUsedBits()) == 0 &&
8314 "Slices are not supposed to overlap.");
8315 UsedBits |= Second.getUsedBits();
8316 return areUsedBitsDense(UsedBits);
8317}
8318
8319/// \brief Adjust the \p GlobalLSCost according to the target
8320/// paring capabilities and the layout of the slices.
8321/// \pre \p GlobalLSCost should account for at least as many loads as
8322/// there is in the slices in \p LoadedSlices.
8323static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8324 LoadedSlice::Cost &GlobalLSCost) {
8325 unsigned NumberOfSlices = LoadedSlices.size();
8326 // If there is less than 2 elements, no pairing is possible.
8327 if (NumberOfSlices < 2)
8328 return;
8329
8330 // Sort the slices so that elements that are likely to be next to each
8331 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008332 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8333 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8334 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8335 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8336 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008337 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8338 // First (resp. Second) is the first (resp. Second) potentially candidate
8339 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008340 const LoadedSlice *First = nullptr;
8341 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008342 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8343 // Set the beginning of the pair.
8344 First = Second) {
8345
8346 Second = &LoadedSlices[CurrSlice];
8347
8348 // If First is NULL, it means we start a new pair.
8349 // Get to the next slice.
8350 if (!First)
8351 continue;
8352
8353 EVT LoadedType = First->getLoadedType();
8354
8355 // If the types of the slices are different, we cannot pair them.
8356 if (LoadedType != Second->getLoadedType())
8357 continue;
8358
8359 // Check if the target supplies paired loads for this type.
8360 unsigned RequiredAlignment = 0;
8361 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8362 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008363 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008364 continue;
8365 }
8366 // Check if we meet the alignment requirement.
8367 if (RequiredAlignment > First->getAlignment())
8368 continue;
8369
8370 // Check that both loads are next to each other in memory.
8371 if (!areSlicesNextToEachOther(*First, *Second))
8372 continue;
8373
8374 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8375 --GlobalLSCost.Loads;
8376 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008377 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008378 }
8379}
8380
8381/// \brief Check the profitability of all involved LoadedSlice.
8382/// Currently, it is considered profitable if there is exactly two
8383/// involved slices (1) which are (2) next to each other in memory, and
8384/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8385///
8386/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8387/// the elements themselves.
8388///
8389/// FIXME: When the cost model will be mature enough, we can relax
8390/// constraints (1) and (2).
8391static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8392 const APInt &UsedBits, bool ForCodeSize) {
8393 unsigned NumberOfSlices = LoadedSlices.size();
8394 if (StressLoadSlicing)
8395 return NumberOfSlices > 1;
8396
8397 // Check (1).
8398 if (NumberOfSlices != 2)
8399 return false;
8400
8401 // Check (2).
8402 if (!areUsedBitsDense(UsedBits))
8403 return false;
8404
8405 // Check (3).
8406 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8407 // The original code has one big load.
8408 OrigCost.Loads = 1;
8409 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8410 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8411 // Accumulate the cost of all the slices.
8412 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8413 GlobalSlicingCost += SliceCost;
8414
8415 // Account as cost in the original configuration the gain obtained
8416 // with the current slices.
8417 OrigCost.addSliceGain(LS);
8418 }
8419
8420 // If the target supports paired load, adjust the cost accordingly.
8421 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8422 return OrigCost > GlobalSlicingCost;
8423}
8424
8425/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8426/// operations, split it in the various pieces being extracted.
8427///
8428/// This sort of thing is introduced by SROA.
8429/// This slicing takes care not to insert overlapping loads.
8430/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8431bool DAGCombiner::SliceUpLoad(SDNode *N) {
8432 if (Level < AfterLegalizeDAG)
8433 return false;
8434
8435 LoadSDNode *LD = cast<LoadSDNode>(N);
8436 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8437 !LD->getValueType(0).isInteger())
8438 return false;
8439
8440 // Keep track of already used bits to detect overlapping values.
8441 // In that case, we will just abort the transformation.
8442 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8443
8444 SmallVector<LoadedSlice, 4> LoadedSlices;
8445
8446 // Check if this load is used as several smaller chunks of bits.
8447 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8448 // of computation for each trunc.
8449 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8450 UI != UIEnd; ++UI) {
8451 // Skip the uses of the chain.
8452 if (UI.getUse().getResNo() != 0)
8453 continue;
8454
8455 SDNode *User = *UI;
8456 unsigned Shift = 0;
8457
8458 // Check if this is a trunc(lshr).
8459 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8460 isa<ConstantSDNode>(User->getOperand(1))) {
8461 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8462 User = *User->use_begin();
8463 }
8464
8465 // At this point, User is a Truncate, iff we encountered, trunc or
8466 // trunc(lshr).
8467 if (User->getOpcode() != ISD::TRUNCATE)
8468 return false;
8469
8470 // The width of the type must be a power of 2 and greater than 8-bits.
8471 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008472 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008473 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008474 unsigned Width = User->getValueSizeInBits(0);
8475 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8476 return 0;
8477
8478 // Build the slice for this chain of computations.
8479 LoadedSlice LS(User, LD, Shift, &DAG);
8480 APInt CurrentUsedBits = LS.getUsedBits();
8481
8482 // Check if this slice overlaps with another.
8483 if ((CurrentUsedBits & UsedBits) != 0)
8484 return false;
8485 // Update the bits used globally.
8486 UsedBits |= CurrentUsedBits;
8487
8488 // Check if the new slice would be legal.
8489 if (!LS.isLegal())
8490 return false;
8491
8492 // Record the slice.
8493 LoadedSlices.push_back(LS);
8494 }
8495
8496 // Abort slicing if it does not seem to be profitable.
8497 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8498 return false;
8499
8500 ++SlicedLoads;
8501
8502 // Rewrite each chain to use an independent load.
8503 // By construction, each chain can be represented by a unique load.
8504
8505 // Prepare the argument for the new token factor for all the slices.
8506 SmallVector<SDValue, 8> ArgChains;
8507 for (SmallVectorImpl<LoadedSlice>::const_iterator
8508 LSIt = LoadedSlices.begin(),
8509 LSItEnd = LoadedSlices.end();
8510 LSIt != LSItEnd; ++LSIt) {
8511 SDValue SliceInst = LSIt->loadSlice();
8512 CombineTo(LSIt->Inst, SliceInst, true);
8513 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8514 SliceInst = SliceInst.getOperand(0);
8515 assert(SliceInst->getOpcode() == ISD::LOAD &&
8516 "It takes more than a zext to get to the loaded slice!!");
8517 ArgChains.push_back(SliceInst.getValue(1));
8518 }
8519
8520 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008521 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8523 return true;
8524}
8525
Chris Lattner4041ab62010-04-15 04:48:01 +00008526/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8527/// load is having specific bytes cleared out. If so, return the byte size
8528/// being masked out and the shift amount.
8529static std::pair<unsigned, unsigned>
8530CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8531 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008532
Chris Lattner4041ab62010-04-15 04:48:01 +00008533 // Check for the structure we're looking for.
8534 if (V->getOpcode() != ISD::AND ||
8535 !isa<ConstantSDNode>(V->getOperand(1)) ||
8536 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8537 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008538
Chris Lattner3245afd2010-04-15 06:10:49 +00008539 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008540 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008541 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008542
Chris Lattner3245afd2010-04-15 06:10:49 +00008543 // The store should be chained directly to the load or be an operand of a
8544 // tokenfactor.
8545 if (LD == Chain.getNode())
8546 ; // ok.
8547 else if (Chain->getOpcode() != ISD::TokenFactor)
8548 return Result; // Fail.
8549 else {
8550 bool isOk = false;
8551 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8552 if (Chain->getOperand(i).getNode() == LD) {
8553 isOk = true;
8554 break;
8555 }
8556 if (!isOk) return Result;
8557 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008558
Chris Lattner4041ab62010-04-15 04:48:01 +00008559 // This only handles simple types.
8560 if (V.getValueType() != MVT::i16 &&
8561 V.getValueType() != MVT::i32 &&
8562 V.getValueType() != MVT::i64)
8563 return Result;
8564
8565 // Check the constant mask. Invert it so that the bits being masked out are
8566 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8567 // follow the sign bit for uniformity.
8568 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008569 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008570 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008571 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008572 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8573 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008574
Chris Lattner4041ab62010-04-15 04:48:01 +00008575 // See if we have a continuous run of bits. If so, we have 0*1+0*
8576 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8577 return Result;
8578
8579 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8580 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8581 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008582
Chris Lattner4041ab62010-04-15 04:48:01 +00008583 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8584 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008585 case 1:
8586 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008587 case 4: break;
8588 default: return Result; // All one mask, or 5-byte mask.
8589 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008590
Chris Lattner4041ab62010-04-15 04:48:01 +00008591 // Verify that the first bit starts at a multiple of mask so that the access
8592 // is aligned the same as the access width.
8593 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008594
Chris Lattner4041ab62010-04-15 04:48:01 +00008595 Result.first = MaskedBytes;
8596 Result.second = NotMaskTZ/8;
8597 return Result;
8598}
8599
8600
8601/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8602/// provides a value as specified by MaskInfo. If so, replace the specified
8603/// store with a narrower store of truncated IVal.
8604static SDNode *
8605ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8606 SDValue IVal, StoreSDNode *St,
8607 DAGCombiner *DC) {
8608 unsigned NumBytes = MaskInfo.first;
8609 unsigned ByteShift = MaskInfo.second;
8610 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008611
Chris Lattner4041ab62010-04-15 04:48:01 +00008612 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8613 // that uses this. If not, this is not a replacement.
8614 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8615 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008616 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008617
Chris Lattner4041ab62010-04-15 04:48:01 +00008618 // Check that it is legal on the target to do this. It is legal if the new
8619 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8620 // legalization.
8621 MVT VT = MVT::getIntegerVT(NumBytes*8);
8622 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008623 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008624
Chris Lattner4041ab62010-04-15 04:48:01 +00008625 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8626 // shifted by ByteShift and truncated down to NumBytes.
8627 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008628 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008629 DAG.getConstant(ByteShift*8,
8630 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008631
8632 // Figure out the offset for the store and the alignment of the access.
8633 unsigned StOffset;
8634 unsigned NewAlign = St->getAlignment();
8635
8636 if (DAG.getTargetLoweringInfo().isLittleEndian())
8637 StOffset = ByteShift;
8638 else
8639 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008640
Chris Lattner4041ab62010-04-15 04:48:01 +00008641 SDValue Ptr = St->getBasePtr();
8642 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008643 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008644 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8645 NewAlign = MinAlign(NewAlign, StOffset);
8646 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008647
Chris Lattner4041ab62010-04-15 04:48:01 +00008648 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008649 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008650
Chris Lattner4041ab62010-04-15 04:48:01 +00008651 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008652 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008653 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008654 false, false, NewAlign).getNode();
8655}
8656
Evan Chenga9cda8a2009-05-28 00:35:15 +00008657
8658/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8659/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8660/// of the loaded bits, try narrowing the load and store if it would end up
8661/// being a win for performance or code size.
8662SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8663 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008664 if (ST->isVolatile())
8665 return SDValue();
8666
Evan Chenga9cda8a2009-05-28 00:35:15 +00008667 SDValue Chain = ST->getChain();
8668 SDValue Value = ST->getValue();
8669 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008670 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008671
8672 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008673 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008674
8675 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008676
Chris Lattner4041ab62010-04-15 04:48:01 +00008677 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8678 // is a byte mask indicating a consecutive number of bytes, check to see if
8679 // Y is known to provide just those bytes. If so, we try to replace the
8680 // load + replace + store sequence with a single (narrower) store, which makes
8681 // the load dead.
8682 if (Opc == ISD::OR) {
8683 std::pair<unsigned, unsigned> MaskedLoad;
8684 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8685 if (MaskedLoad.first)
8686 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8687 Value.getOperand(1), ST,this))
8688 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008689
Chris Lattner4041ab62010-04-15 04:48:01 +00008690 // Or is commutative, so try swapping X and Y.
8691 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8692 if (MaskedLoad.first)
8693 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8694 Value.getOperand(0), ST,this))
8695 return SDValue(NewST, 0);
8696 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008697
Evan Chenga9cda8a2009-05-28 00:35:15 +00008698 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8699 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008700 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008701
8702 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008703 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8704 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008705 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008706 if (LD->getBasePtr() != Ptr ||
8707 LD->getPointerInfo().getAddrSpace() !=
8708 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008709 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008710
8711 // Find the type to narrow it the load / op / store to.
8712 SDValue N1 = Value.getOperand(1);
8713 unsigned BitWidth = N1.getValueSizeInBits();
8714 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8715 if (Opc == ISD::AND)
8716 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008717 if (Imm == 0 || Imm.isAllOnesValue())
8718 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008719 unsigned ShAmt = Imm.countTrailingZeros();
8720 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8721 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008722 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008723 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008724 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008725 TLI.isNarrowingProfitable(VT, NewVT))) {
8726 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008727 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008728 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008729 if (NewBW >= BitWidth)
8730 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008731
8732 // If the lsb changed does not start at the type bitwidth boundary,
8733 // start at the previous one.
8734 if (ShAmt % NewBW)
8735 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008736 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8737 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008738 if ((Imm & Mask) == Imm) {
8739 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8740 if (Opc == ISD::AND)
8741 NewImm ^= APInt::getAllOnesValue(NewBW);
8742 uint64_t PtrOff = ShAmt / 8;
8743 // For big endian targets, we need to adjust the offset to the pointer to
8744 // load the correct bytes.
8745 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008746 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008747
8748 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008749 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008750 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008751 return SDValue();
8752
Andrew Trickef9de2a2013-05-25 02:42:55 +00008753 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008754 Ptr.getValueType(), Ptr,
8755 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008756 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008757 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008758 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008759 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008760 LD->isInvariant(), NewAlign,
8761 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008762 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008763 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008764 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008765 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008766 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008767 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008768
8769 AddToWorkList(NewPtr.getNode());
8770 AddToWorkList(NewLD.getNode());
8771 AddToWorkList(NewVal.getNode());
8772 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008773 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008774 ++OpsNarrowed;
8775 return NewST;
8776 }
8777 }
8778
Evan Cheng6673ff02009-05-28 18:41:02 +00008779 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008780}
8781
Evan Chengd42641c2011-02-02 01:06:55 +00008782/// TransformFPLoadStorePair - For a given floating point load / store pair,
8783/// if the load value isn't used by any other operations, then consider
8784/// transforming the pair to integer load / store operations if the target
8785/// deems the transformation profitable.
8786SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8787 StoreSDNode *ST = cast<StoreSDNode>(N);
8788 SDValue Chain = ST->getChain();
8789 SDValue Value = ST->getValue();
8790 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8791 Value.hasOneUse() &&
8792 Chain == SDValue(Value.getNode(), 1)) {
8793 LoadSDNode *LD = cast<LoadSDNode>(Value);
8794 EVT VT = LD->getMemoryVT();
8795 if (!VT.isFloatingPoint() ||
8796 VT != ST->getMemoryVT() ||
8797 LD->isNonTemporal() ||
8798 ST->isNonTemporal() ||
8799 LD->getPointerInfo().getAddrSpace() != 0 ||
8800 ST->getPointerInfo().getAddrSpace() != 0)
8801 return SDValue();
8802
8803 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8804 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8805 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8806 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8807 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8808 return SDValue();
8809
8810 unsigned LDAlign = LD->getAlignment();
8811 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008812 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008813 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008814 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8815 return SDValue();
8816
Andrew Trickef9de2a2013-05-25 02:42:55 +00008817 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008818 LD->getChain(), LD->getBasePtr(),
8819 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008820 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008821
Andrew Trickef9de2a2013-05-25 02:42:55 +00008822 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008823 NewLD, ST->getBasePtr(),
8824 ST->getPointerInfo(),
8825 false, false, STAlign);
8826
8827 AddToWorkList(NewLD.getNode());
8828 AddToWorkList(NewST.getNode());
8829 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008830 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008831 ++LdStFP2Int;
8832 return NewST;
8833 }
8834
8835 return SDValue();
8836}
8837
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008838/// Helper struct to parse and store a memory address as base + index + offset.
8839/// We ignore sign extensions when it is safe to do so.
8840/// The following two expressions are not equivalent. To differentiate we need
8841/// to store whether there was a sign extension involved in the index
8842/// computation.
8843/// (load (i64 add (i64 copyfromreg %c)
8844/// (i64 signextend (add (i8 load %index)
8845/// (i8 1))))
8846/// vs
8847///
8848/// (load (i64 add (i64 copyfromreg %c)
8849/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8850/// (i32 1)))))
8851struct BaseIndexOffset {
8852 SDValue Base;
8853 SDValue Index;
8854 int64_t Offset;
8855 bool IsIndexSignExt;
8856
8857 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8858
8859 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8860 bool IsIndexSignExt) :
8861 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8862
8863 bool equalBaseIndex(const BaseIndexOffset &Other) {
8864 return Other.Base == Base && Other.Index == Index &&
8865 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008866 }
8867
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008868 /// Parses tree in Ptr for base, index, offset addresses.
8869 static BaseIndexOffset match(SDValue Ptr) {
8870 bool IsIndexSignExt = false;
8871
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008872 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8873 // instruction, then it could be just the BASE or everything else we don't
8874 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008875 if (Ptr->getOpcode() != ISD::ADD)
8876 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8877
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008878 // We know that we have at least an ADD instruction. Try to pattern match
8879 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008880 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8881 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8882 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8883 IsIndexSignExt);
8884 }
8885
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008886 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008887 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008888 // (i64 add (i64 %array_ptr)
8889 // (i64 mul (i64 %induction_var)
8890 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008891 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008892 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008893
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008894 // Look at Base + Index + Offset cases.
8895 SDValue Base = Ptr->getOperand(0);
8896 SDValue IndexOffset = Ptr->getOperand(1);
8897
8898 // Skip signextends.
8899 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8900 IndexOffset = IndexOffset->getOperand(0);
8901 IsIndexSignExt = true;
8902 }
8903
8904 // Either the case of Base + Index (no offset) or something else.
8905 if (IndexOffset->getOpcode() != ISD::ADD)
8906 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8907
8908 // Now we have the case of Base + Index + offset.
8909 SDValue Index = IndexOffset->getOperand(0);
8910 SDValue Offset = IndexOffset->getOperand(1);
8911
8912 if (!isa<ConstantSDNode>(Offset))
8913 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8914
8915 // Ignore signextends.
8916 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8917 Index = Index->getOperand(0);
8918 IsIndexSignExt = true;
8919 } else IsIndexSignExt = false;
8920
8921 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8922 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8923 }
8924};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008925
8926/// Holds a pointer to an LSBaseSDNode as well as information on where it
8927/// is located in a sequence of memory operations connected by a chain.
8928struct MemOpLink {
8929 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8930 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8931 // Ptr to the mem node.
8932 LSBaseSDNode *MemNode;
8933 // Offset from the base ptr.
8934 int64_t OffsetFromBase;
8935 // What is the sequence number of this mem node.
8936 // Lowest mem operand in the DAG starts at zero.
8937 unsigned SequenceNum;
8938};
8939
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008940bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8941 EVT MemVT = St->getMemoryVT();
8942 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008943 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8944 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008945
8946 // Don't merge vectors into wider inputs.
8947 if (MemVT.isVector() || !MemVT.isSimple())
8948 return false;
8949
8950 // Perform an early exit check. Do not bother looking at stored values that
8951 // are not constants or loads.
8952 SDValue StoredVal = St->getValue();
8953 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8954 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8955 !IsLoadSrc)
8956 return false;
8957
8958 // Only look at ends of store sequences.
8959 SDValue Chain = SDValue(St, 1);
8960 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8961 return false;
8962
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008963 // This holds the base pointer, index, and the offset in bytes from the base
8964 // pointer.
8965 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008966
8967 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008968 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008969 return false;
8970
8971 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008972 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008973 return false;
8974
Nadav Rotem307d7672012-11-29 00:00:08 +00008975 // Save the LoadSDNodes that we find in the chain.
8976 // We need to make sure that these nodes do not interfere with
8977 // any of the store nodes.
8978 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8979
8980 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008981 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00008982
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008983 // Walk up the chain and look for nodes with offsets from the same
8984 // base pointer. Stop when reaching an instruction with a different kind
8985 // or instruction which has a different base pointer.
8986 unsigned Seq = 0;
8987 StoreSDNode *Index = St;
8988 while (Index) {
8989 // If the chain has more than one use, then we can't reorder the mem ops.
8990 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8991 break;
8992
8993 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008994 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008995
8996 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008997 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008998 break;
8999
9000 // Check that the alignment is the same.
9001 if (Index->getAlignment() != St->getAlignment())
9002 break;
9003
9004 // The memory operands must not be volatile.
9005 if (Index->isVolatile() || Index->isIndexed())
9006 break;
9007
9008 // No truncation.
9009 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9010 if (St->isTruncatingStore())
9011 break;
9012
9013 // The stored memory type must be the same.
9014 if (Index->getMemoryVT() != MemVT)
9015 break;
9016
9017 // We do not allow unaligned stores because we want to prevent overriding
9018 // stores.
9019 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9020 break;
9021
9022 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009023 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009024
Nadav Rotem307d7672012-11-29 00:00:08 +00009025 // Find the next memory operand in the chain. If the next operand in the
9026 // chain is a store then move up and continue the scan with the next
9027 // memory operand. If the next operand is a load save it and use alias
9028 // information to check if it interferes with anything.
9029 SDNode *NextInChain = Index->getChain().getNode();
9030 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009031 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009032 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009033 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009034 break;
9035 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009036 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009037 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009038 break;
9039 }
9040
Nadav Rotem307d7672012-11-29 00:00:08 +00009041 // Save the load node for later. Continue the scan.
9042 AliasLoadNodes.push_back(Ldn);
9043 NextInChain = Ldn->getChain().getNode();
9044 continue;
9045 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009046 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009047 break;
9048 }
9049 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009050 }
9051
9052 // Check if there is anything to merge.
9053 if (StoreNodes.size() < 2)
9054 return false;
9055
9056 // Sort the memory operands according to their distance from the base pointer.
9057 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009058 [](MemOpLink LHS, MemOpLink RHS) {
9059 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9060 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9061 LHS.SequenceNum > RHS.SequenceNum);
9062 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009063
9064 // Scan the memory operations on the chain and find the first non-consecutive
9065 // store memory address.
9066 unsigned LastConsecutiveStore = 0;
9067 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009068 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9069
9070 // Check that the addresses are consecutive starting from the second
9071 // element in the list of stores.
9072 if (i > 0) {
9073 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9074 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9075 break;
9076 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009077
Nadav Rotem307d7672012-11-29 00:00:08 +00009078 bool Alias = false;
9079 // Check if this store interferes with any of the loads that we found.
9080 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9081 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9082 Alias = true;
9083 break;
9084 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009085 // We found a load that alias with this store. Stop the sequence.
9086 if (Alias)
9087 break;
9088
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009089 // Mark this node as useful.
9090 LastConsecutiveStore = i;
9091 }
9092
9093 // The node with the lowest store address.
9094 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9095
9096 // Store the constants into memory as one consecutive store.
9097 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009098 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009099 unsigned LastLegalVectorType = 0;
9100 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009101 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9102 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9103 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009104
9105 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009106 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009107 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009108 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009109 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009110 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009111 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009112 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009113
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009114 // Find a legal type for the constant store.
9115 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9116 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9117 if (TLI.isTypeLegal(StoreTy))
9118 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009119 // Or check whether a truncstore is legal.
9120 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9121 TargetLowering::TypePromoteInteger) {
9122 EVT LegalizedStoredValueTy =
9123 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9124 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9125 LastLegalType = i+1;
9126 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009127
9128 // Find a legal type for the vector store.
9129 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9130 if (TLI.isTypeLegal(Ty))
9131 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009132 }
9133
Bob Wilson3365b802012-12-20 01:36:20 +00009134 // We only use vectors if the constant is known to be zero and the
9135 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009136 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009137 LastLegalVectorType = 0;
9138
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009139 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009140 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009141 return false;
9142
Nadav Rotem495b1a42013-02-14 18:28:52 +00009143 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009144 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9145
9146 // Make sure we have something to merge.
9147 if (NumElem < 2)
9148 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009149
9150 unsigned EarliestNodeUsed = 0;
9151 for (unsigned i=0; i < NumElem; ++i) {
9152 // Find a chain for the new wide-store operand. Notice that some
9153 // of the store nodes that we found may not be selected for inclusion
9154 // in the wide store. The chain we use needs to be the chain of the
9155 // earliest store node which is *used* and replaced by the wide store.
9156 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9157 EarliestNodeUsed = i;
9158 }
9159
9160 // The earliest Node in the DAG.
9161 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009162 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009163
Nadav Rotemb27777f2012-10-04 22:35:15 +00009164 SDValue StoredVal;
9165 if (UseVector) {
9166 // Find a legal type for the vector store.
9167 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9168 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9169 StoredVal = DAG.getConstant(0, Ty);
9170 } else {
9171 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9172 APInt StoreInt(StoreBW, 0);
9173
9174 // Construct a single integer constant which is made of the smaller
9175 // constant inputs.
9176 bool IsLE = TLI.isLittleEndian();
9177 for (unsigned i = 0; i < NumElem ; ++i) {
9178 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9179 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9180 SDValue Val = St->getValue();
9181 StoreInt<<=ElementSizeBytes*8;
9182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9183 StoreInt|=C->getAPIntValue().zext(StoreBW);
9184 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9185 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9186 } else {
9187 assert(false && "Invalid constant element type");
9188 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009189 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009190
9191 // Create the new Load and Store operations.
9192 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9193 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009194 }
9195
Nadav Rotemb27777f2012-10-04 22:35:15 +00009196 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009197 FirstInChain->getBasePtr(),
9198 FirstInChain->getPointerInfo(),
9199 false, false,
9200 FirstInChain->getAlignment());
9201
9202 // Replace the first store with the new store
9203 CombineTo(EarliestOp, NewStore);
9204 // Erase all other stores.
9205 for (unsigned i = 0; i < NumElem ; ++i) {
9206 if (StoreNodes[i].MemNode == EarliestOp)
9207 continue;
9208 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009209 // ReplaceAllUsesWith will replace all uses that existed when it was
9210 // called, but graph optimizations may cause new ones to appear. For
9211 // example, the case in pr14333 looks like
9212 //
9213 // St's chain -> St -> another store -> X
9214 //
9215 // And the only difference from St to the other store is the chain.
9216 // When we change it's chain to be St's chain they become identical,
9217 // get CSEed and the net result is that X is now a use of St.
9218 // Since we know that St is redundant, just iterate.
9219 while (!St->use_empty())
9220 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009221 removeFromWorkList(St);
9222 DAG.DeleteNode(St);
9223 }
9224
9225 return true;
9226 }
9227
9228 // Below we handle the case of multiple consecutive stores that
9229 // come from multiple consecutive loads. We merge them into a single
9230 // wide load and a single wide store.
9231
9232 // Look for load nodes which are used by the stored values.
9233 SmallVector<MemOpLink, 8> LoadNodes;
9234
9235 // Find acceptable loads. Loads need to have the same chain (token factor),
9236 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009237 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009238 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9239 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9240 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9241 if (!Ld) break;
9242
9243 // Loads must only have one use.
9244 if (!Ld->hasNUsesOfValue(1, 0))
9245 break;
9246
9247 // Check that the alignment is the same as the stores.
9248 if (Ld->getAlignment() != St->getAlignment())
9249 break;
9250
9251 // The memory operands must not be volatile.
9252 if (Ld->isVolatile() || Ld->isIndexed())
9253 break;
9254
9255 // We do not accept ext loads.
9256 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9257 break;
9258
9259 // The stored memory type must be the same.
9260 if (Ld->getMemoryVT() != MemVT)
9261 break;
9262
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009263 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009264 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009265 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009266 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009267 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009268 break;
9269 } else {
9270 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009271 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009272 }
9273
9274 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009275 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009276 }
9277
9278 if (LoadNodes.size() < 2)
9279 return false;
9280
9281 // Scan the memory operations on the chain and find the first non-consecutive
9282 // load memory address. These variables hold the index in the store node
9283 // array.
9284 unsigned LastConsecutiveLoad = 0;
9285 // This variable refers to the size and not index in the array.
9286 unsigned LastLegalVectorType = 0;
9287 unsigned LastLegalIntegerType = 0;
9288 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009289 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9290 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9291 // All loads much share the same chain.
9292 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9293 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009294
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009295 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9296 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9297 break;
9298 LastConsecutiveLoad = i;
9299
9300 // Find a legal type for the vector store.
9301 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9302 if (TLI.isTypeLegal(StoreTy))
9303 LastLegalVectorType = i + 1;
9304
9305 // Find a legal type for the integer store.
9306 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9307 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9308 if (TLI.isTypeLegal(StoreTy))
9309 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009310 // Or check whether a truncstore and extload is legal.
9311 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9312 TargetLowering::TypePromoteInteger) {
9313 EVT LegalizedStoredValueTy =
9314 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9315 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9316 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9317 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9318 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9319 LastLegalIntegerType = i+1;
9320 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009321 }
9322
9323 // Only use vector types if the vector type is larger than the integer type.
9324 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009325 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009326 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9327
9328 // We add +1 here because the LastXXX variables refer to location while
9329 // the NumElem refers to array/index size.
9330 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9331 NumElem = std::min(LastLegalType, NumElem);
9332
9333 if (NumElem < 2)
9334 return false;
9335
9336 // The earliest Node in the DAG.
9337 unsigned EarliestNodeUsed = 0;
9338 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9339 for (unsigned i=1; i<NumElem; ++i) {
9340 // Find a chain for the new wide-store operand. Notice that some
9341 // of the store nodes that we found may not be selected for inclusion
9342 // in the wide store. The chain we use needs to be the chain of the
9343 // earliest store node which is *used* and replaced by the wide store.
9344 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9345 EarliestNodeUsed = i;
9346 }
9347
9348 // Find if it is better to use vectors or integers to load and store
9349 // to memory.
9350 EVT JointMemOpVT;
9351 if (UseVectorTy) {
9352 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9353 } else {
9354 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9355 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9356 }
9357
Andrew Trickef9de2a2013-05-25 02:42:55 +00009358 SDLoc LoadDL(LoadNodes[0].MemNode);
9359 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009360
9361 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9362 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9363 FirstLoad->getChain(),
9364 FirstLoad->getBasePtr(),
9365 FirstLoad->getPointerInfo(),
9366 false, false, false,
9367 FirstLoad->getAlignment());
9368
9369 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9370 FirstInChain->getBasePtr(),
9371 FirstInChain->getPointerInfo(), false, false,
9372 FirstInChain->getAlignment());
9373
Nadav Rotemac920662012-10-03 19:30:31 +00009374 // Replace one of the loads with the new load.
9375 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9376 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9377 SDValue(NewLoad.getNode(), 1));
9378
9379 // Remove the rest of the load chains.
9380 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009381 // Replace all chain users of the old load nodes with the chain of the new
9382 // load node.
9383 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009384 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9385 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009386
Nadav Rotemac920662012-10-03 19:30:31 +00009387 // Replace the first store with the new store.
9388 CombineTo(EarliestOp, NewStore);
9389 // Erase all other stores.
9390 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009391 // Remove all Store nodes.
9392 if (StoreNodes[i].MemNode == EarliestOp)
9393 continue;
9394 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9395 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9396 removeFromWorkList(St);
9397 DAG.DeleteNode(St);
9398 }
9399
9400 return true;
9401}
9402
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009403SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009404 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009405 SDValue Chain = ST->getChain();
9406 SDValue Value = ST->getValue();
9407 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009408
Evan Chenga4cf58a2007-05-07 21:27:48 +00009409 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009410 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009411 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009412 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009413 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009414 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009415 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009416 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009417 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009418 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009419 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009420 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009421 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009422 ST->isNonTemporal(), OrigAlign,
9423 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009424 }
Owen Andersona5192842011-04-14 17:30:49 +00009425
Chris Lattner41c80e82011-04-09 02:32:02 +00009426 // Turn 'store undef, Ptr' -> nothing.
9427 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9428 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009429
Nate Begeman8e20c762006-12-11 02:23:46 +00009430 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009431 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009432 // NOTE: If the original store is volatile, this transform must not increase
9433 // the number of stores. For example, on x86-32 an f64 can be stored in one
9434 // processor operation but an i64 (which is not legal) requires two. So the
9435 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009436 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009437 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009438 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009439 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009440 case MVT::f16: // We don't do this for these yet.
9441 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009442 case MVT::f128:
9443 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009444 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009445 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009446 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009447 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009448 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009449 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009450 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009451 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009452 }
9453 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009454 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009455 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009456 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009457 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009458 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009459 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009460 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009461 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009462 }
Owen Andersona5192842011-04-14 17:30:49 +00009463
Chris Lattner41c80e82011-04-09 02:32:02 +00009464 if (!ST->isVolatile() &&
9465 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009466 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009467 // argument passing. Since this is so common, custom legalize the
9468 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009469 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009470 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9471 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009472 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009473
Dan Gohman2af30632007-07-09 22:18:38 +00009474 unsigned Alignment = ST->getAlignment();
9475 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009476 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009477 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009478
Andrew Trickef9de2a2013-05-25 02:42:55 +00009479 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009480 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009481 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009482 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009483 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009484 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009485 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009486 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009487 Ptr, ST->getPointerInfo().getWithOffset(4),
9488 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009489 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009490 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009491 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009492 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009493
Chris Lattnerb7524b62006-12-12 04:16:14 +00009494 break;
Evan Cheng21836982006-12-11 17:25:19 +00009495 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009496 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009497 }
9498
Evan Cheng43cd9e32010-04-01 06:04:33 +00009499 // Try to infer better alignment information than the store already has.
9500 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009501 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9502 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009503 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009504 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009505 ST->isVolatile(), ST->isNonTemporal(), Align,
9506 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009507 }
9508 }
9509
Evan Chengd42641c2011-02-02 01:06:55 +00009510 // Try transforming a pair floating point load / store ops to integer
9511 // load / store ops.
9512 SDValue NewST = TransformFPLoadStorePair(N);
9513 if (NewST.getNode())
9514 return NewST;
9515
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009516 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9517 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009518#ifndef NDEBUG
9519 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9520 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9521 UseAA = false;
9522#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009523 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009524 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009525 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009526
Jim Laskey708d0db2006-10-04 16:53:27 +00009527 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009528 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009529 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009530
9531 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009532 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009533 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009534 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009535 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009536 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009537 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009538 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009539
Jim Laskeyd07be232006-09-25 16:29:54 +00009540 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009541 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009542 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009543
Nate Begeman879d8f12009-09-15 00:18:30 +00009544 // Make sure the new and old chains are cleaned up.
9545 AddToWorkList(Token.getNode());
9546
Jim Laskeydcf983c2006-10-13 23:32:28 +00009547 // Don't add users to work list.
9548 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009549 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009550 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009551
Evan Cheng33157702006-11-05 09:31:14 +00009552 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009553 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009554 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009555
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009556 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009557 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009558 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009559 // See if we can simplify the input to this truncstore with knowledge that
9560 // only the low bits are being used. For example:
9561 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009562 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009563 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009564 APInt::getLowBitsSet(
9565 Value.getValueType().getScalarType().getSizeInBits(),
9566 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009567 AddToWorkList(Value.getNode());
9568 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009569 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009570 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009571
Chris Lattnerf47e3062007-10-13 06:58:48 +00009572 // Otherwise, see if we can simplify the operation with
9573 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009574 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009575 APInt::getLowBitsSet(
9576 Value.getValueType().getScalarType().getSizeInBits(),
9577 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009578 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009579 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009580
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009581 // If this is a load followed by a store to the same location, then the store
9582 // is dead/noop.
9583 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009584 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009585 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009586 // There can't be any side effects between the load and store, such as
9587 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009588 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009589 // The store is dead, remove it.
9590 return Chain;
9591 }
9592 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009593
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009594 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9595 // truncating store. We can do this even if this is already a truncstore.
9596 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009597 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009598 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009599 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009600 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009601 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009602 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009603
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009604 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009605 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009606 if (!LegalTypes) {
9607 bool EverChanged = false;
9608
9609 do {
9610 // There can be multiple store sequences on the same chain.
9611 // Keep trying to merge store sequences until we are unable to do so
9612 // or until we merge the last store on the chain.
9613 bool Changed = MergeConsecutiveStores(ST);
9614 EverChanged |= Changed;
9615 if (!Changed) break;
9616 } while (ST->getOpcode() != ISD::DELETED_NODE);
9617
9618 if (EverChanged)
9619 return SDValue(N, 0);
9620 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009621
Evan Chenga9cda8a2009-05-28 00:35:15 +00009622 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009623}
9624
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009625SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9626 SDValue InVec = N->getOperand(0);
9627 SDValue InVal = N->getOperand(1);
9628 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009629 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009630
Bob Wilson42603952010-05-19 23:42:58 +00009631 // If the inserted element is an UNDEF, just use the input vector.
9632 if (InVal.getOpcode() == ISD::UNDEF)
9633 return InVec;
9634
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009635 EVT VT = InVec.getValueType();
9636
Owen Andersonb2c80da2011-02-25 21:41:48 +00009637 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009638 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9639 return SDValue();
9640
Eli Friedmanb7910b72011-09-09 21:04:06 +00009641 // Check that we know which element is being inserted
9642 if (!isa<ConstantSDNode>(EltNo))
9643 return SDValue();
9644 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009645
Eli Friedmanb7910b72011-09-09 21:04:06 +00009646 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9647 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9648 // vector elements.
9649 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009650 // Do not combine these two vectors if the output vector will not replace
9651 // the input vector.
9652 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009653 Ops.append(InVec.getNode()->op_begin(),
9654 InVec.getNode()->op_end());
9655 } else if (InVec.getOpcode() == ISD::UNDEF) {
9656 unsigned NElts = VT.getVectorNumElements();
9657 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9658 } else {
9659 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009660 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009661
9662 // Insert the element
9663 if (Elt < Ops.size()) {
9664 // All the operands of BUILD_VECTOR must have the same type;
9665 // we enforce that here.
9666 EVT OpVT = Ops[0].getValueType();
9667 if (InVal.getValueType() != OpVT)
9668 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9669 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9670 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9671 Ops[Elt] = InVal;
9672 }
9673
9674 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009675 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009676}
9677
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009678SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009679 // (vextract (scalar_to_vector val, 0) -> val
9680 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009681 EVT VT = InVec.getValueType();
9682 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009683
Duncan Sands6be291a2011-05-09 08:03:33 +00009684 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9685 // Check if the result type doesn't match the inserted element type. A
9686 // SCALAR_TO_VECTOR may truncate the inserted element and the
9687 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9688 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009689 if (InOp.getValueType() != NVT) {
9690 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009691 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009692 }
9693 return InOp;
9694 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009695
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009696 SDValue EltNo = N->getOperand(1);
9697 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9698
9699 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9700 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009701 // we may introduce new vector instructions which are not backed by TD
9702 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009703 // without using extract_subvector. However, if we can find an underlying
9704 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009705 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009706 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009707 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9708 int NumElem = VT.getVectorNumElements();
9709 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9710 // Find the new index to extract from.
9711 int OrigElt = SVOp->getMaskElt(Elt);
9712
9713 // Extracting an undef index is undef.
9714 if (OrigElt == -1)
9715 return DAG.getUNDEF(NVT);
9716
9717 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009718 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009719 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009720 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009721 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009722 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009723 OrigElt -= NumElem;
9724 }
9725
Hal Finkel02807592014-03-31 11:43:19 +00009726 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9727 SDValue InOp = SVInVec.getOperand(OrigElt);
9728 if (InOp.getValueType() != NVT) {
9729 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9730 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9731 }
9732
9733 return InOp;
9734 }
9735
9736 // FIXME: We should handle recursing on other vector shuffles and
9737 // scalar_to_vector here as well.
9738
9739 if (!LegalOperations) {
9740 EVT IndexTy = TLI.getVectorIdxTy();
9741 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9742 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9743 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009744 }
9745
Evan Cheng1120279a2008-05-13 08:35:03 +00009746 // Perform only after legalization to ensure build_vector / vector_shuffle
9747 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009748 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009749
Mon P Wangca6d6de2009-01-17 00:07:25 +00009750 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9751 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9752 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009753
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009754 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009755 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009756 bool NewLoad = false;
Mon P Wangb5eb7202008-12-11 00:26:16 +00009757 bool BCNumEltsChanged = false;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009758 EVT ExtVT = VT.getVectorElementType();
9759 EVT LVT = ExtVT;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009760
Evan Cheng7bf83092012-03-13 22:00:52 +00009761 // If the result of load has to be truncated, then it's not necessarily
9762 // profitable.
Evan Chengd5f8e572012-03-13 22:16:11 +00009763 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng7bf83092012-03-13 22:00:52 +00009764 return SDValue();
9765
Wesley Peck527da1b2010-11-23 03:31:01 +00009766 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009767 // Don't duplicate a load with other uses.
9768 if (!InVec.hasOneUse())
9769 return SDValue();
9770
Owen Anderson53aa7a92009-08-10 22:56:29 +00009771 EVT BCVT = InVec.getOperand(0).getValueType();
9772 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009773 return SDValue();
Mon P Wangb5eb7202008-12-11 00:26:16 +00009774 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9775 BCNumEltsChanged = true;
Evan Cheng1120279a2008-05-13 08:35:03 +00009776 InVec = InVec.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009777 ExtVT = BCVT.getVectorElementType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009778 NewLoad = true;
9779 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009780
Craig Topperc0196b12014-04-14 00:51:57 +00009781 LoadSDNode *LN0 = nullptr;
9782 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009783 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009784 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009785 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009786 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009787 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009788 // Don't duplicate a load with other uses.
9789 if (!InVec.hasOneUse())
9790 return SDValue();
9791
Evan Cheng1120279a2008-05-13 08:35:03 +00009792 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009793 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009794 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9795 // =>
9796 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009797
Eli Friedmane96286c2011-12-26 22:49:32 +00009798 // Don't duplicate a load with other uses.
9799 if (!InVec.hasOneUse())
9800 return SDValue();
9801
Mon P Wangb5eb7202008-12-11 00:26:16 +00009802 // If the bit convert changed the number of elements, it is unsafe
9803 // to examine the mask.
9804 if (BCNumEltsChanged)
9805 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009806
9807 // Select the input vector, guarding against out of range extract vector.
9808 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009809 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009810 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9811
Eli Friedmane96286c2011-12-26 22:49:32 +00009812 if (InVec.getOpcode() == ISD::BITCAST) {
9813 // Don't duplicate a load with other uses.
9814 if (!InVec.hasOneUse())
9815 return SDValue();
9816
Evan Cheng1120279a2008-05-13 08:35:03 +00009817 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009818 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009819 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009820 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009821 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009822 }
9823 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009824
Eli Friedmane96286c2011-12-26 22:49:32 +00009825 // Make sure we found a non-volatile load and the extractelement is
9826 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009827 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009828 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009829
Eric Christopherc6418b12010-11-03 20:44:42 +00009830 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9831 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009832 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009833
Evan Cheng1120279a2008-05-13 08:35:03 +00009834 unsigned Align = LN0->getAlignment();
9835 if (NewLoad) {
9836 // Check the resultant load doesn't need a higher alignment than the
9837 // original load.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009838 unsigned NewAlign =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009839 TLI.getDataLayout()
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009840 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendling27d9dd42009-01-30 23:36:47 +00009841
Dan Gohman4aa18462009-01-28 17:46:25 +00009842 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009843 return SDValue();
Bill Wendling27d9dd42009-01-30 23:36:47 +00009844
Evan Cheng1120279a2008-05-13 08:35:03 +00009845 Align = NewAlign;
9846 }
9847
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009848 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009849 unsigned PtrOff = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00009850
Eric Christopherc6418b12010-11-03 20:44:42 +00009851 if (Elt) {
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009852 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009853 EVT PtrType = NewPtr.getValueType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009854 if (TLI.isBigEndian())
Duncan Sands13237ac2008-06-06 12:08:01 +00009855 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009856 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng1120279a2008-05-13 08:35:03 +00009857 DAG.getConstant(PtrOff, PtrType));
9858 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009859
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009860 // The replacement we need to do here is a little tricky: we need to
9861 // replace an extractelement of a load with a load.
9862 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmane96286c2011-12-26 22:49:32 +00009863 // Note that this replacement assumes that the extractvalue is the only
9864 // use of the load; that's okay because we don't want to perform this
9865 // transformation in other cases anyway.
Evan Cheng7bf83092012-03-13 22:00:52 +00009866 SDValue Load;
Evan Chengd5f8e572012-03-13 22:16:11 +00009867 SDValue Chain;
Evan Cheng7bf83092012-03-13 22:00:52 +00009868 if (NVT.bitsGT(LVT)) {
9869 // If the result type of vextract is wider than the load, then issue an
9870 // extending load instead.
9871 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9872 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009873 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng7bf83092012-03-13 22:00:52 +00009874 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009875 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9876 Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009877 Chain = Load.getValue(1);
9878 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009879 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng7bf83092012-03-13 22:00:52 +00009880 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lincfe7f352013-07-08 00:37:03 +00009881 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009882 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009883 Chain = Load.getValue(1);
9884 if (NVT.bitsLT(LVT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009885 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009886 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009887 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009888 }
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009889 WorkListRemover DeadNodes(*this);
9890 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chengd5f8e572012-03-13 22:16:11 +00009891 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009892 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009893 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9894 // worklist explicitly as well.
9895 AddToWorkList(Load.getNode());
Craig Topperaaeae982012-03-20 05:28:39 +00009896 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009897 // Make sure to revisit this node to clean it up; it will usually be dead.
9898 AddToWorkList(N);
9899 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009900 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009901
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009902 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009903}
Evan Cheng0de312d2007-10-06 08:19:55 +00009904
Michael Liao6d106b72012-10-23 23:06:52 +00009905// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9906SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9907 // We perform this optimization post type-legalization because
9908 // the type-legalizer often scalarizes integer-promoted vectors.
9909 // Performing this optimization before may create bit-casts which
9910 // will be type-legalized to complex code sequences.
9911 // We perform this optimization only before the operation legalizer because we
9912 // may introduce illegal operations.
9913 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9914 return SDValue();
9915
Dan Gohmana8665142007-06-25 16:23:39 +00009916 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009917 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009918 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009919
Nadav Rotembf6568b2011-10-29 21:23:04 +00009920 // Check to see if this is a BUILD_VECTOR of a bunch of values
9921 // which come from any_extend or zero_extend nodes. If so, we can create
9922 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009923 // optimizations. We do not handle sign-extend because we can't fill the sign
9924 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009925 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009926 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009927
Craig Topper02cb0fb2012-01-17 09:09:48 +00009928 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009929 SDValue In = N->getOperand(i);
9930 // Ignore undef inputs.
9931 if (In.getOpcode() == ISD::UNDEF) continue;
9932
9933 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9934 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9935
Nadav Rotemf3103612011-10-31 20:08:25 +00009936 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009937 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009938 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009939 break;
9940 }
9941
9942 // The input is a ZeroExt or AnyExt. Check the original type.
9943 EVT InTy = In.getOperand(0).getValueType();
9944
9945 // Check that all of the widened source types are the same.
9946 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009947 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009948 SourceType = InTy;
9949 else if (InTy != SourceType) {
9950 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009951 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009952 break;
9953 }
9954
9955 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009956 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009957 }
9958
Nadav Rotemf3103612011-10-31 20:08:25 +00009959 // In order to have valid types, all of the inputs must be extended from the
9960 // same source type and all of the inputs must be any or zero extend.
9961 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009962 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009963 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +00009964 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9965 isPowerOf2_32(SourceType.getSizeInBits());
9966
Nadav Rotem6fd1d322012-03-15 08:49:06 +00009967 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9968 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +00009969 if (!ValidTypes)
9970 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +00009971
Michael Liao6d106b72012-10-23 23:06:52 +00009972 bool isLE = TLI.isLittleEndian();
9973 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9974 assert(ElemRatio > 1 && "Invalid element size ratio");
9975 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9976 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009977
Michael Liao6d106b72012-10-23 23:06:52 +00009978 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9979 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009980
Michael Liao6d106b72012-10-23 23:06:52 +00009981 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +00009982 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +00009983 SDValue Cast = N->getOperand(i);
9984 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9985 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9986 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9987 SDValue In;
9988 if (Cast.getOpcode() == ISD::UNDEF)
9989 In = DAG.getUNDEF(SourceType);
9990 else
9991 In = Cast->getOperand(0);
9992 unsigned Index = isLE ? (i * ElemRatio) :
9993 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +00009994
Michael Liao6d106b72012-10-23 23:06:52 +00009995 assert(Index < Ops.size() && "Invalid index");
9996 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009997 }
Chris Lattner5336a592006-03-19 01:27:56 +00009998
Michael Liao6d106b72012-10-23 23:06:52 +00009999 // The type of the new BUILD_VECTOR node.
10000 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10001 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10002 "Invalid vector size");
10003 // Check if the new vector type is legal.
10004 if (!isTypeLegal(VecVT)) return SDValue();
10005
10006 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010007 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010008
10009 // The new BUILD_VECTOR node has the potential to be further optimized.
10010 AddToWorkList(BV.getNode());
10011 // Bitcast to the desired type.
10012 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10013}
10014
Michael Liao59229792012-10-24 04:14:18 +000010015SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10016 EVT VT = N->getValueType(0);
10017
10018 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010019 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010020
10021 EVT SrcVT = MVT::Other;
10022 unsigned Opcode = ISD::DELETED_NODE;
10023 unsigned NumDefs = 0;
10024
10025 for (unsigned i = 0; i != NumInScalars; ++i) {
10026 SDValue In = N->getOperand(i);
10027 unsigned Opc = In.getOpcode();
10028
10029 if (Opc == ISD::UNDEF)
10030 continue;
10031
10032 // If all scalar values are floats and converted from integers.
10033 if (Opcode == ISD::DELETED_NODE &&
10034 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10035 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010036 }
Tom Stellard567f8862013-01-02 22:13:01 +000010037
Michael Liao59229792012-10-24 04:14:18 +000010038 if (Opc != Opcode)
10039 return SDValue();
10040
10041 EVT InVT = In.getOperand(0).getValueType();
10042
10043 // If all scalar values are typed differently, bail out. It's chosen to
10044 // simplify BUILD_VECTOR of integer types.
10045 if (SrcVT == MVT::Other)
10046 SrcVT = InVT;
10047 if (SrcVT != InVT)
10048 return SDValue();
10049 NumDefs++;
10050 }
10051
10052 // If the vector has just one element defined, it's not worth to fold it into
10053 // a vectorized one.
10054 if (NumDefs < 2)
10055 return SDValue();
10056
10057 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10058 && "Should only handle conversion from integer to float.");
10059 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10060
10061 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010062
10063 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10064 return SDValue();
10065
Michael Liao59229792012-10-24 04:14:18 +000010066 SmallVector<SDValue, 8> Opnds;
10067 for (unsigned i = 0; i != NumInScalars; ++i) {
10068 SDValue In = N->getOperand(i);
10069
10070 if (In.getOpcode() == ISD::UNDEF)
10071 Opnds.push_back(DAG.getUNDEF(SrcVT));
10072 else
10073 Opnds.push_back(In.getOperand(0));
10074 }
Craig Topper48d114b2014-04-26 18:35:24 +000010075 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Michael Liao59229792012-10-24 04:14:18 +000010076 AddToWorkList(BV.getNode());
10077
10078 return DAG.getNode(Opcode, dl, VT, BV);
10079}
10080
Michael Liao6d106b72012-10-23 23:06:52 +000010081SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10082 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010083 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010084 EVT VT = N->getValueType(0);
10085
10086 // A vector built entirely of undefs is undef.
10087 if (ISD::allOperandsUndef(N))
10088 return DAG.getUNDEF(VT);
10089
10090 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10091 if (V.getNode())
10092 return V;
10093
Michael Liao59229792012-10-24 04:14:18 +000010094 V = reduceBuildVecConvertToConvertBuildVec(N);
10095 if (V.getNode())
10096 return V;
10097
Dan Gohmana8665142007-06-25 16:23:39 +000010098 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10099 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10100 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010101
10102 // May only combine to shuffle after legalize if shuffle is legal.
10103 if (LegalOperations &&
10104 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10105 return SDValue();
10106
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010107 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010108 for (unsigned i = 0; i != NumInScalars; ++i) {
10109 // Ignore undef inputs.
10110 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010111
Dan Gohmana8665142007-06-25 16:23:39 +000010112 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010113 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010114 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010115 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010116 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010117 break;
10118 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010119
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010120 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010121 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010122 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10123 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010124
Craig Topperc0196b12014-04-14 00:51:57 +000010125 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010126 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010127 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010128 VecIn2 = ExtractedFromVec;
10129 } else {
10130 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010131 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010132 break;
10133 }
10134 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010135
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010136 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010137 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010138 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010139 for (unsigned i = 0; i != NumInScalars; ++i) {
10140 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010141 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010142 continue;
10143 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010144
Rafael Espindolab93db662009-04-24 12:40:33 +000010145 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010146 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010147 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010148 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010149 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10150 if (ExtIndex > VT.getVectorNumElements())
10151 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010152
Nate Begeman5f829d82009-04-29 05:20:52 +000010153 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010154 continue;
10155 }
10156
10157 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010158 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010159 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010160 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010161
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010162 // We can't generate a shuffle node with mismatched input and output types.
10163 // Attempt to transform a single input vector to the correct type.
10164 if ((VT != VecIn1.getValueType())) {
10165 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010166 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010167 return SDValue();
10168
10169 // We only support widening of vectors which are half the size of the
10170 // output registers. For example XMM->YMM widening on X86 with AVX.
10171 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10172 return SDValue();
10173
James Molloy1e5c6112012-09-10 14:01:21 +000010174 // If the input vector type has a different base type to the output
10175 // vector type, bail out.
10176 if (VecIn1.getValueType().getVectorElementType() !=
10177 VT.getVectorElementType())
10178 return SDValue();
10179
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010180 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010181 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010182 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010183 }
10184
10185 // If VecIn2 is unused then change it to undef.
10186 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10187
Nadav Rotem841c9a82012-09-20 08:53:31 +000010188 // Check that we were able to transform all incoming values to the same
10189 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010190 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10191 VecIn1.getValueType() != VT)
10192 return SDValue();
10193
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010194 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010195 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010196 return SDValue();
10197
Dan Gohmana8665142007-06-25 16:23:39 +000010198 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010199 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010200 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010201 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010202 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010203 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010204
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010205 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010206}
10207
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010208SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010209 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10210 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10211 // inputs come from at most two distinct vectors, turn this into a shuffle
10212 // node.
10213
10214 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010215 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010216 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010217
Nadav Rotem01892102012-07-14 21:30:27 +000010218 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010219 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010220 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010221 return DAG.getUNDEF(VT);
10222
10223 // Optimize concat_vectors where one of the vectors is undef.
10224 if (N->getNumOperands() == 2 &&
10225 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10226 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010227 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010228
10229 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10230 if (In->getOpcode() == ISD::BITCAST &&
10231 !In->getOperand(0)->getValueType(0).isVector()) {
10232 SDValue Scalar = In->getOperand(0);
10233 EVT SclTy = Scalar->getValueType(0);
10234
10235 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10236 return SDValue();
10237
10238 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10239 VT.getSizeInBits() / SclTy.getSizeInBits());
10240 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10241 return SDValue();
10242
10243 SDLoc dl = SDLoc(N);
10244 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10245 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10246 }
10247 }
Nadav Rotem01892102012-07-14 21:30:27 +000010248
Robert Lougher7d9084f2014-02-11 15:42:46 +000010249 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10250 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10251 if (N->getNumOperands() == 2 &&
10252 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10253 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10254 EVT VT = N->getValueType(0);
10255 SDValue N0 = N->getOperand(0);
10256 SDValue N1 = N->getOperand(1);
10257 SmallVector<SDValue, 8> Opnds;
10258 unsigned BuildVecNumElts = N0.getNumOperands();
10259
10260 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10261 Opnds.push_back(N0.getOperand(i));
10262 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10263 Opnds.push_back(N1.getOperand(i));
10264
Craig Topper48d114b2014-04-26 18:35:24 +000010265 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010266 }
10267
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010268 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10269 // nodes often generate nop CONCAT_VECTOR nodes.
10270 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10271 // place the incoming vectors at the exact same location.
10272 SDValue SingleSource = SDValue();
10273 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10274
10275 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10276 SDValue Op = N->getOperand(i);
10277
10278 if (Op.getOpcode() == ISD::UNDEF)
10279 continue;
10280
10281 // Check if this is the identity extract:
10282 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10283 return SDValue();
10284
10285 // Find the single incoming vector for the extract_subvector.
10286 if (SingleSource.getNode()) {
10287 if (Op.getOperand(0) != SingleSource)
10288 return SDValue();
10289 } else {
10290 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010291
10292 // Check the source type is the same as the type of the result.
10293 // If not, this concat may extend the vector, so we can not
10294 // optimize it away.
10295 if (SingleSource.getValueType() != N->getValueType(0))
10296 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010297 }
10298
10299 unsigned IdentityIndex = i * PartNumElem;
10300 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10301 // The extract index must be constant.
10302 if (!CS)
10303 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010304
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010305 // Check that we are reading from the identity index.
10306 if (CS->getZExtValue() != IdentityIndex)
10307 return SDValue();
10308 }
10309
10310 if (SingleSource.getNode())
10311 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010312
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010313 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010314}
10315
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010316SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10317 EVT NVT = N->getValueType(0);
10318 SDValue V = N->getOperand(0);
10319
Michael Liao7a442c802012-10-17 20:48:33 +000010320 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10321 // Combine:
10322 // (extract_subvec (concat V1, V2, ...), i)
10323 // Into:
10324 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010325 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10326 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010327 if (V->getOperand(0).getValueType() != NVT)
10328 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010329 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10330 unsigned NumElems = NVT.getVectorNumElements();
10331 assert((Idx % NumElems) == 0 &&
10332 "IDX in concat is not a multiple of the result vector length.");
10333 return V->getOperand(Idx / NumElems);
10334 }
10335
Michael Liaobb05a1d2013-03-25 23:47:35 +000010336 // Skip bitcasting
10337 if (V->getOpcode() == ISD::BITCAST)
10338 V = V.getOperand(0);
10339
10340 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010341 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010342 // Handle only simple case where vector being inserted and vector
10343 // being extracted are of same type, and are half size of larger vectors.
10344 EVT BigVT = V->getOperand(0).getValueType();
10345 EVT SmallVT = V->getOperand(1).getValueType();
10346 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10347 return SDValue();
10348
10349 // Only handle cases where both indexes are constants with the same type.
10350 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10351 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10352
10353 if (InsIdx && ExtIdx &&
10354 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10355 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10356 // Combine:
10357 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10358 // Into:
10359 // indices are equal or bit offsets are equal => V1
10360 // otherwise => (extract_subvec V1, ExtIdx)
10361 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10362 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10363 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10364 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10365 DAG.getNode(ISD::BITCAST, dl,
10366 N->getOperand(0).getValueType(),
10367 V->getOperand(0)), N->getOperand(1));
10368 }
10369 }
10370
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010371 return SDValue();
10372}
10373
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010374// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10375static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10376 EVT VT = N->getValueType(0);
10377 unsigned NumElts = VT.getVectorNumElements();
10378
10379 SDValue N0 = N->getOperand(0);
10380 SDValue N1 = N->getOperand(1);
10381 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10382
10383 SmallVector<SDValue, 4> Ops;
10384 EVT ConcatVT = N0.getOperand(0).getValueType();
10385 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10386 unsigned NumConcats = NumElts / NumElemsPerConcat;
10387
10388 // Look at every vector that's inserted. We're looking for exact
10389 // subvector-sized copies from a concatenated vector
10390 for (unsigned I = 0; I != NumConcats; ++I) {
10391 // Make sure we're dealing with a copy.
10392 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010393 bool AllUndef = true, NoUndef = true;
10394 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10395 if (SVN->getMaskElt(J) >= 0)
10396 AllUndef = false;
10397 else
10398 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010399 }
10400
Hao Liubc601962013-05-13 02:07:05 +000010401 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010402 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10403 return SDValue();
10404
10405 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10406 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10407 return SDValue();
10408
10409 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10410 if (FirstElt < N0.getNumOperands())
10411 Ops.push_back(N0.getOperand(FirstElt));
10412 else
10413 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10414
10415 } else if (AllUndef) {
10416 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10417 } else { // Mixed with general masks and undefs, can't do optimization.
10418 return SDValue();
10419 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010420 }
10421
Craig Topper48d114b2014-04-26 18:35:24 +000010422 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010423}
10424
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010425SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010426 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010427 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010428
Mon P Wang25f01062008-11-10 04:46:22 +000010429 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010430 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010431
Craig Topper5894fe42012-04-09 05:16:56 +000010432 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010433
Craig Topper279c77b2012-01-04 08:07:43 +000010434 // Canonicalize shuffle undef, undef -> undef
10435 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10436 return DAG.getUNDEF(VT);
10437
10438 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10439
10440 // Canonicalize shuffle v, v -> v, undef
10441 if (N0 == N1) {
10442 SmallVector<int, 8> NewMask;
10443 for (unsigned i = 0; i != NumElts; ++i) {
10444 int Idx = SVN->getMaskElt(i);
10445 if (Idx >= (int)NumElts) Idx -= NumElts;
10446 NewMask.push_back(Idx);
10447 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010448 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010449 &NewMask[0]);
10450 }
10451
10452 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10453 if (N0.getOpcode() == ISD::UNDEF) {
10454 SmallVector<int, 8> NewMask;
10455 for (unsigned i = 0; i != NumElts; ++i) {
10456 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010457 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010458 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010459 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010460 else
10461 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010462 }
10463 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010464 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010465 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010466 &NewMask[0]);
10467 }
10468
10469 // Remove references to rhs if it is undef
10470 if (N1.getOpcode() == ISD::UNDEF) {
10471 bool Changed = false;
10472 SmallVector<int, 8> NewMask;
10473 for (unsigned i = 0; i != NumElts; ++i) {
10474 int Idx = SVN->getMaskElt(i);
10475 if (Idx >= (int)NumElts) {
10476 Idx = -1;
10477 Changed = true;
10478 }
10479 NewMask.push_back(Idx);
10480 }
10481 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010482 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010483 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010484
Bob Wilsonf63da122010-10-28 17:06:14 +000010485 // If it is a splat, check if the argument vector is another splat or a
10486 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010487 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010488 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010489
Dan Gohmana8665142007-06-25 16:23:39 +000010490 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010491 // not the number of vector elements, look through it. Be careful not to
10492 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010493 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010494 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010495 if (ConvInput.getValueType().isVector() &&
10496 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010497 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010498 }
10499
Dan Gohmana8665142007-06-25 16:23:39 +000010500 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010501 assert(V->getNumOperands() == NumElts &&
10502 "BUILD_VECTOR has wrong number of operands");
10503 SDValue Base;
10504 bool AllSame = true;
10505 for (unsigned i = 0; i != NumElts; ++i) {
10506 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10507 Base = V->getOperand(i);
10508 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010509 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010510 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010511 // Splat of <u, u, u, u>, return <u, u, u, u>
10512 if (!Base.getNode())
10513 return N0;
10514 for (unsigned i = 0; i != NumElts; ++i) {
10515 if (V->getOperand(i) != Base) {
10516 AllSame = false;
10517 break;
10518 }
10519 }
10520 // Splat of <x, x, x, x>, return <x, x, x, x>
10521 if (AllSame)
10522 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010523 }
10524 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010525
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010526 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10527 Level < AfterLegalizeVectorOps &&
10528 (N1.getOpcode() == ISD::UNDEF ||
10529 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10530 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10531 SDValue V = partitionShuffleOfConcats(N, DAG);
10532
10533 if (V.getNode())
10534 return V;
10535 }
10536
Nadav Rotemb0783502012-04-01 19:31:22 +000010537 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010538 // and it reverses the swizzle of the previous shuffle then we can
10539 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010540 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10541 N1.getOpcode() == ISD::UNDEF) {
10542
Nadav Rotemb0783502012-04-01 19:31:22 +000010543 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10544
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010545 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10546 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10547 return SDValue();
10548
Craig Topper5894fe42012-04-09 05:16:56 +000010549 // The incoming shuffle must be of the same type as the result of the
10550 // current shuffle.
10551 assert(OtherSV->getOperand(0).getValueType() == VT &&
10552 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010553
10554 for (unsigned i = 0; i != NumElts; ++i) {
10555 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010556 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010557 // Next, this index comes from the first value, which is the incoming
10558 // shuffle. Adopt the incoming index.
10559 if (Idx >= 0)
10560 Idx = OtherSV->getMaskElt(Idx);
10561
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010562 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010563 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010564 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010565 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010566
10567 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010568 }
10569
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010570 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010571}
10572
Manman Ren413a6cb2014-01-31 01:10:35 +000010573SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10574 SDValue N0 = N->getOperand(0);
10575 SDValue N2 = N->getOperand(2);
10576
10577 // If the input vector is a concatenation, and the insert replaces
10578 // one of the halves, we can optimize into a single concat_vectors.
10579 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10580 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10581 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10582 EVT VT = N->getValueType(0);
10583
10584 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10585 // (concat_vectors Z, Y)
10586 if (InsIdx == 0)
10587 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10588 N->getOperand(1), N0.getOperand(1));
10589
10590 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10591 // (concat_vectors X, Z)
10592 if (InsIdx == VT.getVectorNumElements()/2)
10593 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10594 N0.getOperand(0), N->getOperand(1));
10595 }
10596
10597 return SDValue();
10598}
10599
Evan Chenga320abc2006-04-20 08:56:16 +000010600/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010601/// an AND to a vector_shuffle with the destination vector and a zero vector.
10602/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010603/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010604SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010605 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010606 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010607 SDValue LHS = N->getOperand(0);
10608 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010609 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010610 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010611 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010612 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010613 SmallVector<int, 8> Indices;
10614 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010615 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010616 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010617 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010618 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010619
10620 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010621 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010622 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010623 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010624 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010625 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010626 }
10627
10628 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010629 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010630 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010631 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010632
Dan Gohmana8665142007-06-25 16:23:39 +000010633 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010634 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010635 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010636 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000010637 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000010638 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010639 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010640 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010641 }
10642 }
Bill Wendling31b50992009-01-30 23:59:18 +000010643
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010644 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010645}
10646
Dan Gohmana8665142007-06-25 16:23:39 +000010647/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010648SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010649 assert(N->getValueType(0).isVector() &&
10650 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010651
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010652 SDValue LHS = N->getOperand(0);
10653 SDValue RHS = N->getOperand(1);
10654 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010655 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010656
Dan Gohmana8665142007-06-25 16:23:39 +000010657 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010658 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010659 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010660 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010661 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010662 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10663 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010664 return SDValue();
10665
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010666 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010667 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010668 SDValue LHSOp = LHS.getOperand(i);
10669 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010670
Evan Cheng64d28462006-05-31 06:08:35 +000010671 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010672 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10673 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010674 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010675 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010676 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010677 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010678 break;
10679 }
Bill Wendling31b50992009-01-30 23:59:18 +000010680
Bob Wilson54081442010-12-17 23:06:49 +000010681 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010682 EVT RVT = RHSOp.getValueType();
10683 if (RVT != VT) {
10684 // Integer BUILD_VECTOR operands may have types larger than the element
10685 // size (e.g., when the element type is not legal). Prior to type
10686 // legalization, the types may not match between the two BUILD_VECTORS.
10687 // Truncate one of the operands to make them match.
10688 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010689 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010690 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010691 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010692 VT = RVT;
10693 }
10694 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010695 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010696 LHSOp, RHSOp);
10697 if (FoldOp.getOpcode() != ISD::UNDEF &&
10698 FoldOp.getOpcode() != ISD::Constant &&
10699 FoldOp.getOpcode() != ISD::ConstantFP)
10700 break;
10701 Ops.push_back(FoldOp);
10702 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010703 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010704
Bob Wilson54081442010-12-17 23:06:49 +000010705 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000010706 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
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
Craig Topper48d114b2014-04-26 18:35:24 +000010741 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000010742}
10743
Andrew Trickef9de2a2013-05-25 02:42:55 +000010744SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010745 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010746 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010747
Bill Wendling31b50992009-01-30 23:59:18 +000010748 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010749 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010750
Nate Begeman2042aa52005-10-08 00:29:44 +000010751 // If we got a simplified select_cc node back from SimplifySelectCC, then
10752 // break it down into a new SETCC node, and a new SELECT node, and then return
10753 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010754 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010755 // Check to see if we got a select_cc back (to turn into setcc/select).
10756 // Otherwise, just return whatever node we got back, like fabs.
10757 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010758 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010759 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010760 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010761 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010762 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010763 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10764 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010765 }
Bill Wendling31b50992009-01-30 23:59:18 +000010766
Nate Begeman2042aa52005-10-08 00:29:44 +000010767 return SCC;
10768 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010769 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010770}
10771
Chris Lattner6c14c352005-10-18 06:04:22 +000010772/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10773/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010774/// select. Callers of this should assume that TheSelect is deleted if this
10775/// returns true. As such, they should return the appropriate thing (e.g. the
10776/// node) back to the top-level of the DAG combiner loop to avoid it being
10777/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010778bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010779 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010780
Nadav Rotema49a02a2011-02-11 19:57:47 +000010781 // Cannot simplify select with vector condition
10782 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10783
Chris Lattner6c14c352005-10-18 06:04:22 +000010784 // If this is a select from two identical things, try to pull the operation
10785 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010786 if (LHS.getOpcode() != RHS.getOpcode() ||
10787 !LHS.hasOneUse() || !RHS.hasOneUse())
10788 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010789
Chris Lattner254c4452010-09-21 15:46:59 +000010790 // If this is a load and the token chain is identical, replace the select
10791 // of two loads with a load through a select of the address to load from.
10792 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10793 // constants have been dropped into the constant pool.
10794 if (LHS.getOpcode() == ISD::LOAD) {
10795 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10796 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010797
Chris Lattner254c4452010-09-21 15:46:59 +000010798 // Token chains must be identical.
10799 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010800 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010801 LLD->isVolatile() || RLD->isVolatile() ||
10802 // If this is an EXTLOAD, the VT's must match.
10803 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010804 // If this is an EXTLOAD, the kind of extension must match.
10805 (LLD->getExtensionType() != RLD->getExtensionType() &&
10806 // The only exception is if one of the extensions is anyext.
10807 LLD->getExtensionType() != ISD::EXTLOAD &&
10808 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010809 // FIXME: this discards src value information. This is
10810 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010811 // both potential memory locations. Since we are discarding
10812 // src value info, don't do the transformation if the memory
10813 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010814 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010815 RLD->getPointerInfo().getAddrSpace() != 0 ||
10816 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10817 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010818 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010819
Chris Lattnere3267522010-09-21 15:58:55 +000010820 // Check that the select condition doesn't reach either load. If so,
10821 // folding this will induce a cycle into the DAG. If not, this is safe to
10822 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010823 SDValue Addr;
10824 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010825 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10826 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10827 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10828 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010829 // The loads must not depend on one another.
10830 if (LLD->isPredecessorOf(RLD) ||
10831 RLD->isPredecessorOf(LLD))
10832 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010833 Addr = DAG.getSelect(SDLoc(TheSelect),
10834 LLD->getBasePtr().getValueType(),
10835 TheSelect->getOperand(0), LLD->getBasePtr(),
10836 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010837 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010838 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10839 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10840
10841 if ((LLD->hasAnyUseOfValue(1) &&
10842 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010843 (RLD->hasAnyUseOfValue(1) &&
10844 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010845 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010846
Andrew Trickef9de2a2013-05-25 02:42:55 +000010847 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010848 LLD->getBasePtr().getValueType(),
10849 TheSelect->getOperand(0),
10850 TheSelect->getOperand(1),
10851 LLD->getBasePtr(), RLD->getBasePtr(),
10852 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010853 }
10854
Chris Lattnere3267522010-09-21 15:58:55 +000010855 SDValue Load;
10856 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10857 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010858 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010859 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010860 LLD->getChain(), Addr, MachinePointerInfo(),
10861 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010862 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010863 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010864 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10865 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010866 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010867 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010868 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010869 LLD->getChain(), Addr, MachinePointerInfo(),
10870 LLD->getMemoryVT(), LLD->isVolatile(),
10871 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010872 }
Chris Lattnere3267522010-09-21 15:58:55 +000010873
10874 // Users of the select now use the result of the load.
10875 CombineTo(TheSelect, Load);
10876
10877 // Users of the old loads now use the new load's chain. We know the
10878 // old-load value is dead now.
10879 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10880 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10881 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010882 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010883
Chris Lattner6c14c352005-10-18 06:04:22 +000010884 return false;
10885}
10886
Chris Lattner43d63772009-03-11 05:08:08 +000010887/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10888/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010889SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010890 SDValue N2, SDValue N3,
10891 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010892 // (x ? y : y) -> y.
10893 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010894
Owen Anderson53aa7a92009-08-10 22:56:29 +000010895 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010896 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10897 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10898 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010899
10900 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010901 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010902 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010903 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10904 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010905
10906 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010907 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010908 return N2;
10909 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010910 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010911 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010912
Nate Begeman2042aa52005-10-08 00:29:44 +000010913 // Check to see if we can simplify the select into an fabs node
10914 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10915 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010916 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010917 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10918 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10919 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10920 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010921 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010922
Nate Begeman2042aa52005-10-08 00:29:44 +000010923 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10924 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10925 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10926 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010927 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010928 }
10929 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010930
Chris Lattner43d63772009-03-11 05:08:08 +000010931 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10932 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10933 // in it. This is a win when the constant is not otherwise available because
10934 // it replaces two constant pool loads with one. We only do this if the FP
10935 // type is known to be legal, because if it isn't, then we are before legalize
10936 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010937 // messing with soft float) and if the ConstantFP is not legal, because if
10938 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010939 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10940 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10941 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010942 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000010943 TargetLowering::Legal &&
10944 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10945 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010946 // If both constants have multiple uses, then we won't need to do an
10947 // extra load, they are likely around in registers for other users.
10948 (TV->hasOneUse() || FV->hasOneUse())) {
10949 Constant *Elts[] = {
10950 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10951 const_cast<ConstantFP*>(TV->getConstantFPValue())
10952 };
Chris Lattner229907c2011-07-18 04:54:35 +000010953 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010954 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010955
Chris Lattner43d63772009-03-11 05:08:08 +000010956 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010957 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010958 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10959 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000010960 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000010961
10962 // Get the offsets to the 0 and 1 element of the array so that we can
10963 // select between them.
10964 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010965 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000010966 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000010967
Chris Lattner43d63772009-03-11 05:08:08 +000010968 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000010969 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000010970 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010971 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010972 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10973 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010974 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000010975 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000010976 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010977 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000010978 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000010979 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000010980 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000010981
10982 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010983 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010984
Nate Begeman2042aa52005-10-08 00:29:44 +000010985 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000010986 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000010987 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000010988 (N1C->isNullValue() || // (a < 0) ? b : 0
10989 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000010990 EVT XType = N0.getValueType();
10991 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000010992 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000010993 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000010994 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010995 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10996 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000010997 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000010998 SDValue ShCt = DAG.getConstant(ShCtV,
10999 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011000 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011001 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011002 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011003
Duncan Sands11dd4242008-06-08 20:54:56 +000011004 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011005 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011006 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011007 }
Bill Wendling31b50992009-01-30 23:59:18 +000011008
11009 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011010 }
Bill Wendling31b50992009-01-30 23:59:18 +000011011
Andrew Trickef9de2a2013-05-25 02:42:55 +000011012 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011013 XType, N0,
11014 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011015 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000011016 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011017
Duncan Sands11dd4242008-06-08 20:54:56 +000011018 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011019 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011020 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011021 }
Bill Wendling31b50992009-01-30 23:59:18 +000011022
11023 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011024 }
11025 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011026
Owen Anderson3231d132010-09-22 22:58:22 +000011027 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11028 // where y is has a single bit set.
11029 // A plaintext description would be, we can turn the SELECT_CC into an AND
11030 // when the condition can be materialized as an all-ones register. Any
11031 // single bit-test can be materialized as an all-ones register with
11032 // shift-left and shift-right-arith.
11033 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11034 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011035 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011036 N2C && N2C->isNullValue()) {
11037 SDValue AndLHS = N0->getOperand(0);
11038 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11039 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11040 // Shift the tested bit over the sign bit.
11041 APInt AndMask = ConstAndRHS->getAPIntValue();
11042 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011043 DAG.getConstant(AndMask.countLeadingZeros(),
11044 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011045 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011046
Owen Anderson3231d132010-09-22 22:58:22 +000011047 // Now arithmetic right shift it all the way over, so the result is either
11048 // all-ones, or zero.
11049 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011050 DAG.getConstant(AndMask.getBitWidth()-1,
11051 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011052 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011053
Owen Anderson3231d132010-09-22 22:58:22 +000011054 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11055 }
11056 }
11057
Nate Begeman6828ed92005-10-10 21:26:48 +000011058 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011059 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000011060 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11061 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011062
Chris Lattnera083ffc2007-04-11 06:50:51 +000011063 // If the caller doesn't want us to simplify this into a zext of a compare,
11064 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011065 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011066 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011067
Nate Begeman6828ed92005-10-10 21:26:48 +000011068 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011069 // NOTE: Don't create a SETCC if it's not legal on this target.
11070 if (!LegalOperations ||
11071 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011072 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011073 SDValue Temp, SCC;
11074 // cast from setcc result type to select result type
11075 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011076 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011077 N0, N1, CC);
11078 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011079 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011080 N2.getValueType());
11081 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011082 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011083 N2.getValueType(), SCC);
11084 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011085 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11086 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011087 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011088 }
11089
11090 AddToWorkList(SCC.getNode());
11091 AddToWorkList(Temp.getNode());
11092
11093 if (N2C->getAPIntValue() == 1)
11094 return Temp;
11095
11096 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011097 return DAG.getNode(
11098 ISD::SHL, DL, N2.getValueType(), Temp,
11099 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11100 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011101 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011102 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011103
Nate Begeman2042aa52005-10-08 00:29:44 +000011104 // Check to see if this is the equivalent of setcc
11105 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11106 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011107 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011108 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011109 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011110 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11111 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011112 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011113 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011114 return Res;
11115 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011116
Bill Wendling31b50992009-01-30 23:59:18 +000011117 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011118 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011119 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011120 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011121 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011122 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011123 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011124 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011125 }
Bill Wendling31b50992009-01-30 23:59:18 +000011126 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011127 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011128 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011129 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011130 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011131 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011132 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011133 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011134 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011135 }
Bill Wendling31b50992009-01-30 23:59:18 +000011136 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011137 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011138 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011139 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011140 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011141 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011142 }
11143 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011144
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011145 // Check to see if this is an integer abs.
11146 // select_cc setg[te] X, 0, X, -X ->
11147 // select_cc setgt X, -1, X, -X ->
11148 // select_cc setl[te] X, 0, -X, X ->
11149 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011150 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011151 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011152 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011153 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11154 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11155 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11156 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11157 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11158 (N1C->isOne() && CC == ISD::SETLT)) &&
11159 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11160 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11161
Owen Anderson53aa7a92009-08-10 22:56:29 +000011162 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011163 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011164 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011165 N0,
11166 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011167 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011168 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011169 XType, N0, Shift);
11170 AddToWorkList(Shift.getNode());
11171 AddToWorkList(Add.getNode());
11172 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011173 }
11174 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011175
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011176 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011177}
11178
Evan Cheng92658d52007-02-08 22:13:59 +000011179/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011180SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011181 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011182 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011183 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011184 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011185 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011186}
11187
Nate Begemanc6f067a2005-10-20 02:15:44 +000011188/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11189/// return a DAG expression to select that will generate the same value by
11190/// multiplying by a magic number. See:
11191/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011192SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011193 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11194 if (!C)
11195 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011196
11197 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011198 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011199 return SDValue();
11200
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011201 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011202 SDValue S =
11203 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011204
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011205 for (SDNode *N : Built)
11206 AddToWorkList(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011207 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011208}
11209
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011210/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begemanc6f067a2005-10-20 02:15:44 +000011211/// return a DAG expression to select that will generate the same value by
11212/// multiplying by a magic number. See:
11213/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011214SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011215 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11216 if (!C)
11217 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011218
11219 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011220 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011221 return SDValue();
11222
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011223 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011224 SDValue S =
11225 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011226
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011227 for (SDNode *N : Built)
11228 AddToWorkList(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011229 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011230}
11231
Nate Begeman18150d52009-09-25 06:05:26 +000011232/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011233// to alias with anything but itself. Provides base object and offset as
11234// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011235static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011236 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011237 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011238 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011239
Jim Laskey0463e082006-10-07 23:37:56 +000011240 // If it's an adding a simple constant then integrate the offset.
11241 if (Base.getOpcode() == ISD::ADD) {
11242 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11243 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011244 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011245 }
11246 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011247
Nate Begeman18150d52009-09-25 06:05:26 +000011248 // Return the underlying GlobalValue, and update the Offset. Return false
11249 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11250 // by multiple nodes with different offsets.
11251 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11252 GV = G->getGlobal();
11253 Offset += G->getOffset();
11254 return false;
11255 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011256
Nate Begeman18150d52009-09-25 06:05:26 +000011257 // Return the underlying Constant value, and update the Offset. Return false
11258 // for ConstantSDNodes since the same constant pool entry may be represented
11259 // by multiple nodes with different offsets.
11260 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011261 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11262 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011263 Offset += C->getOffset();
11264 return false;
11265 }
Jim Laskey0463e082006-10-07 23:37:56 +000011266 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011267 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011268}
11269
11270/// isAlias - Return true if there is any possibility that the two addresses
11271/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011272bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011273 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011274 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011275
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011276 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011277 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011278
Jim Laskey0463e082006-10-07 23:37:56 +000011279 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011280 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011281 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011282 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011283 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011284 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11285 Base1, Offset1, GV1, CV1);
11286 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11287 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011288
Nate Begeman18150d52009-09-25 06:05:26 +000011289 // If they have a same base address then check to see if they overlap.
11290 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011291 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11292 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011293
Owen Anderson272ff942010-09-20 20:39:59 +000011294 // It is possible for different frame indices to alias each other, mostly
11295 // when tail call optimization reuses return address slots for arguments.
11296 // To catch this case, look up the actual index of frame indices to compute
11297 // the real alias relationship.
11298 if (isFrameIndex1 && isFrameIndex2) {
11299 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11300 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11301 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011302 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11303 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011304 }
11305
Wesley Peck527da1b2010-11-23 03:31:01 +000011306 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011307 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011308 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11309 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011310
Nate Begeman879d8f12009-09-15 00:18:30 +000011311 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11312 // compared to the size and offset of the access, we may be able to prove they
11313 // do not alias. This check is conservative for now to catch cases created by
11314 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011315 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11316 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11317 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11318 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11319 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11320 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11321 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011322
Nate Begeman879d8f12009-09-15 00:18:30 +000011323 // There is no overlap between these relatively aligned accesses of similar
11324 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011325 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11326 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011327 return false;
11328 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011329
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011330 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11331 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011332#ifndef NDEBUG
11333 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11334 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11335 UseAA = false;
11336#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011337 if (UseAA &&
11338 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011339 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011340 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11341 Op1->getSrcValueOffset());
11342 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11343 Op0->getSrcValueOffset() - MinOffset;
11344 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11345 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011346 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011347 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11348 Overlap1,
11349 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11350 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11351 Overlap2,
11352 UseTBAA ? Op1->getTBAAInfo() : nullptr));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011353 if (AAResult == AliasAnalysis::NoAlias)
11354 return false;
11355 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011356
11357 // Otherwise we have to assume they alias.
11358 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011359}
11360
Jim Laskey708d0db2006-10-04 16:53:27 +000011361/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11362/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011363void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011364 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011365 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011366 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011367
Jim Laskeyd07be232006-09-25 16:29:54 +000011368 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011369 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011370
Jim Laskey708d0db2006-10-04 16:53:27 +000011371 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011372 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011373 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011374
Jim Laskey6549d222006-10-05 15:07:25 +000011375 // Look at each chain and determine if it is an alias. If so, add it to the
11376 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011377 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011378 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011379 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011380 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011381
11382 // For TokenFactor nodes, look at each operand and only continue up the
11383 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011384 // find more and revert to original chain since the xform is unlikely to be
11385 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011386 //
11387 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011388 // chain we found before we hit a tokenfactor rather than the original
11389 // chain.
11390 if (Depth > 6 || Aliases.size() == 2) {
11391 Aliases.clear();
11392 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011393 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011394 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011395
Nate Begeman879d8f12009-09-15 00:18:30 +000011396 // Don't bother if we've been before.
11397 if (!Visited.insert(Chain.getNode()))
11398 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011399
Jim Laskey6549d222006-10-05 15:07:25 +000011400 switch (Chain.getOpcode()) {
11401 case ISD::EntryToken:
11402 // Entry token is ideal chain operand, but handled in FindBetterChain.
11403 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011404
Jim Laskey6549d222006-10-05 15:07:25 +000011405 case ISD::LOAD:
11406 case ISD::STORE: {
11407 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011408 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11409 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011410
Jim Laskey6549d222006-10-05 15:07:25 +000011411 // If chain is alias then stop here.
11412 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011413 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011414 Aliases.push_back(Chain);
11415 } else {
11416 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011417 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011418 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011419 }
Jim Laskey6549d222006-10-05 15:07:25 +000011420 break;
11421 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011422
Jim Laskey6549d222006-10-05 15:07:25 +000011423 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011424 // We have to check each of the operands of the token factor for "small"
11425 // token factors, so we queue them up. Adding the operands to the queue
11426 // (stack) in reverse order maintains the original order and increases the
11427 // likelihood that getNode will find a matching token factor (CSE.)
11428 if (Chain.getNumOperands() > 16) {
11429 Aliases.push_back(Chain);
11430 break;
11431 }
Jim Laskey6549d222006-10-05 15:07:25 +000011432 for (unsigned n = Chain.getNumOperands(); n;)
11433 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011434 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011435 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011436
Jim Laskey6549d222006-10-05 15:07:25 +000011437 default:
11438 // For all other instructions we will just have to take what we can get.
11439 Aliases.push_back(Chain);
11440 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011441 }
11442 }
Hal Finkel51a98382014-01-24 20:12:02 +000011443
11444 // We need to be careful here to also search for aliases through the
11445 // value operand of a store, etc. Consider the following situation:
11446 // Token1 = ...
11447 // L1 = load Token1, %52
11448 // S1 = store Token1, L1, %51
11449 // L2 = load Token1, %52+8
11450 // S2 = store Token1, L2, %51+8
11451 // Token2 = Token(S1, S2)
11452 // L3 = load Token2, %53
11453 // S3 = store Token2, L3, %52
11454 // L4 = load Token2, %53+8
11455 // S4 = store Token2, L4, %52+8
11456 // If we search for aliases of S3 (which loads address %52), and we look
11457 // only through the chain, then we'll miss the trivial dependence on L1
11458 // (which also loads from %52). We then might change all loads and
11459 // stores to use Token1 as their chain operand, which could result in
11460 // copying %53 into %52 before copying %52 into %51 (which should
11461 // happen first).
11462 //
11463 // The problem is, however, that searching for such data dependencies
11464 // can become expensive, and the cost is not directly related to the
11465 // chain depth. Instead, we'll rule out such configurations here by
11466 // insisting that we've visited all chain users (except for users
11467 // of the original chain, which is not necessary). When doing this,
11468 // we need to look through nodes we don't care about (otherwise, things
11469 // like register copies will interfere with trivial cases).
11470
11471 SmallVector<const SDNode *, 16> Worklist;
11472 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11473 IE = Visited.end(); I != IE; ++I)
11474 if (*I != OriginalChain.getNode())
11475 Worklist.push_back(*I);
11476
11477 while (!Worklist.empty()) {
11478 const SDNode *M = Worklist.pop_back_val();
11479
11480 // We have already visited M, and want to make sure we've visited any uses
11481 // of M that we care about. For uses that we've not visisted, and don't
11482 // care about, queue them to the worklist.
11483
11484 for (SDNode::use_iterator UI = M->use_begin(),
11485 UIE = M->use_end(); UI != UIE; ++UI)
11486 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11487 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11488 // We've not visited this use, and we care about it (it could have an
11489 // ordering dependency with the original node).
11490 Aliases.clear();
11491 Aliases.push_back(OriginalChain);
11492 return;
11493 }
11494
11495 // We've not visited this use, but we don't care about it. Mark it as
11496 // visited and enqueue it to the worklist.
11497 Worklist.push_back(*UI);
11498 }
11499 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011500}
11501
11502/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11503/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011504SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11505 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011506
Jim Laskey708d0db2006-10-04 16:53:27 +000011507 // Accumulate all the aliases to this node.
11508 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011509
Dan Gohman4298df62011-05-17 22:20:36 +000011510 // If no operands then chain to entry token.
11511 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011512 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011513
11514 // If a single operand then chain to it. We don't need to revisit it.
11515 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011516 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011517
Jim Laskey708d0db2006-10-04 16:53:27 +000011518 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011519 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011520}
11521
Nate Begeman21158fc2005-09-01 00:19:25 +000011522// SelectionDAG::Combine - This is the entry point for the file.
11523//
Bill Wendling084669a2009-04-29 00:15:41 +000011524void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011525 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011526 /// run - This is the main entry point to this class.
11527 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011528 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011529}