blob: c45d6a1a79065a9ade6fc13dc70b88fc2f3aa555 [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
19#define DEBUG_TYPE "dagcombine"
Nate Begeman21158fc2005-09-01 00:19:25 +000020#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chris Lattneraee775a2006-12-19 22:41:21 +000043STATISTIC(NodesCombined , "Number of dag nodes combined");
44STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000046STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000047STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000048STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000049
Nate Begeman21158fc2005-09-01 00:19:25 +000050namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000051 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000052 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000053 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000054
Jim Laskey55e4dca2006-10-18 19:08:31 +000055 static cl::opt<bool>
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000057 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000058
Hal Finkeldbebb522014-01-25 19:24:54 +000059// FIXME: Enable the use of TBAA. There are two known issues preventing this:
60// 1. Stack coloring does not update TBAA when merging allocas
61// 2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62// Because BasicAA does not handle inttoptr, we'll often miss basic type
63// punning idioms that we need to catch so we don't miscompile real-world
64// code.
65 static cl::opt<bool>
66 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67 cl::desc("Enable DAG combiner's use of TBAA"));
68
Hal Finkel9b2617a2014-01-25 17:32:39 +000069#ifndef NDEBUG
70 static cl::opt<std::string>
71 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72 cl::desc("Only use DAG-combiner alias analysis in this"
73 " function"));
74#endif
75
Quentin Colombetde0e0622013-10-11 18:29:42 +000076 /// Hidden option to stress test load slicing, i.e., when this option
77 /// is enabled, load slicing bypasses most of its profitability guards.
78 static cl::opt<bool>
79 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80 cl::desc("Bypass the profitability model of load "
81 "slicing"),
82 cl::init(false));
83
Jim Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
95 // Worklist of all of the nodes that need to be simplified.
James Molloy67b6b112012-02-16 09:17:04 +000096 //
97 // This has the semantics that when adding to the worklist,
98 // the item added must be next to be processed. It should
99 // also only appear once. The naive approach to this takes
100 // linear time.
101 //
102 // To reduce the insert/remove time to logarithmic, we use
103 // a set and a vector to maintain our worklist.
104 //
105 // The set contains the items on the worklist, but does not
106 // maintain the order they should be visited.
107 //
108 // The vector maintains the order nodes should be visited, but may
109 // contain duplicate or removed nodes. When choosing a node to
110 // visit, we pop off the order stack until we find an item that is
111 // also in the contents set. All operations are O(log N).
112 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramere1e549d2012-03-10 00:23:58 +0000113 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman21158fc2005-09-01 00:19:25 +0000114
Jim Laskeydcb2b832006-10-16 20:52:31 +0000115 // AA - Used for DAG load/store alias analysis.
116 AliasAnalysis &AA;
117
Nate Begeman21158fc2005-09-01 00:19:25 +0000118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
120 /// now.
121 ///
122 void AddUsersToWorkList(SDNode *N) {
123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
Nate Begeman2504fe22005-09-01 23:24:04 +0000124 UI != UE; ++UI)
Dan Gohman91e5dcb2008-07-27 20:43:25 +0000125 AddToWorkList(*UI);
Nate Begeman21158fc2005-09-01 00:19:25 +0000126 }
127
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000128 /// visit - call the node-specific routine that knows how to fold each
129 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000130 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000131
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000132 public:
James Molloy920ae8c2012-02-16 09:48:07 +0000133 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000134 /// back (next to be processed.)
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000135 void AddToWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000136 WorkListContents.insert(N);
137 WorkListOrder.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000138 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000139
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000140 /// removeFromWorkList - remove all instances of N from the worklist.
141 ///
142 void removeFromWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000143 WorkListContents.erase(N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000145
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000147 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000148
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000150 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000151 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000152
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000154 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000155 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000156 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000157 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000158
159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000160
161 private:
162
Chris Lattner375e1a72006-02-17 21:58:01 +0000163 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000164 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000165 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000169 return SimplifyDemandedBits(Op, Demanded);
170 }
171
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000173
Chris Lattnerffad2162006-11-11 00:39:41 +0000174 bool CombineToPreIndexedLoadStore(SDNode *N);
175 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000176 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000177
Evan Cheng0abb54d2010-04-24 04:43:44 +0000178 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000182 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000183 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000184 SDValue PromoteExtend(SDValue Op);
185 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000186
Craig Toppere0b71182013-07-13 07:43:40 +0000187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000188 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000189 ISD::NodeType ExtType);
190
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000191 /// combine - call the node-specific routine that knows how to fold each
192 /// particular type of node. If that doesn't do anything, try the
193 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000194 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000195
196 // Visitation implementation - Implement dag node combining for different
197 // node types. The semantics are as follows:
198 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000199 // SDValue.getNode() == 0 - No change was made
200 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
201 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000202 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000203 SDValue visitTokenFactor(SDNode *N);
204 SDValue visitMERGE_VALUES(SDNode *N);
205 SDValue visitADD(SDNode *N);
206 SDValue visitSUB(SDNode *N);
207 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000208 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000209 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000210 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000211 SDValue visitMUL(SDNode *N);
212 SDValue visitSDIV(SDNode *N);
213 SDValue visitUDIV(SDNode *N);
214 SDValue visitSREM(SDNode *N);
215 SDValue visitUREM(SDNode *N);
216 SDValue visitMULHU(SDNode *N);
217 SDValue visitMULHS(SDNode *N);
218 SDValue visitSMUL_LOHI(SDNode *N);
219 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000220 SDValue visitSMULO(SDNode *N);
221 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000222 SDValue visitSDIVREM(SDNode *N);
223 SDValue visitUDIVREM(SDNode *N);
224 SDValue visitAND(SDNode *N);
225 SDValue visitOR(SDNode *N);
226 SDValue visitXOR(SDNode *N);
227 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000228 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000229 SDValue visitSHL(SDNode *N);
230 SDValue visitSRA(SDNode *N);
231 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000232 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000234 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000236 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000237 SDValue visitCTPOP(SDNode *N);
238 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000239 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000240 SDValue visitSELECT_CC(SDNode *N);
241 SDValue visitSETCC(SDNode *N);
242 SDValue visitSIGN_EXTEND(SDNode *N);
243 SDValue visitZERO_EXTEND(SDNode *N);
244 SDValue visitANY_EXTEND(SDNode *N);
245 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
246 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000247 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000248 SDValue visitBUILD_PAIR(SDNode *N);
249 SDValue visitFADD(SDNode *N);
250 SDValue visitFSUB(SDNode *N);
251 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000252 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000253 SDValue visitFDIV(SDNode *N);
254 SDValue visitFREM(SDNode *N);
255 SDValue visitFCOPYSIGN(SDNode *N);
256 SDValue visitSINT_TO_FP(SDNode *N);
257 SDValue visitUINT_TO_FP(SDNode *N);
258 SDValue visitFP_TO_SINT(SDNode *N);
259 SDValue visitFP_TO_UINT(SDNode *N);
260 SDValue visitFP_ROUND(SDNode *N);
261 SDValue visitFP_ROUND_INREG(SDNode *N);
262 SDValue visitFP_EXTEND(SDNode *N);
263 SDValue visitFNEG(SDNode *N);
264 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000265 SDValue visitFCEIL(SDNode *N);
266 SDValue visitFTRUNC(SDNode *N);
267 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000268 SDValue visitBRCOND(SDNode *N);
269 SDValue visitBR_CC(SDNode *N);
270 SDValue visitLOAD(SDNode *N);
271 SDValue visitSTORE(SDNode *N);
272 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
273 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
274 SDValue visitBUILD_VECTOR(SDNode *N);
275 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000276 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000277 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000278 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000279
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000280 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000281 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000282
Matt Arsenault985b9de2014-03-17 18:58:01 +0000283 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000284
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000285 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
286 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000287 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
288 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000289 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000290 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000291 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000292 SDLoc DL, bool foldBooleans = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000293 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000294 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000295 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000296 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000297 SDValue BuildSDIV(SDNode *N);
298 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000299 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
300 bool DemandHighBits = true);
301 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000302 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
303 SDValue InnerPos, SDValue InnerNeg,
304 unsigned PosOpcode, unsigned NegOpcode,
305 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000306 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000307 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000308 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000309 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000310 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000311 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000312
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000313 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000314
Jim Laskey708d0db2006-10-04 16:53:27 +0000315 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
316 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000317 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000318 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000319
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000320 /// isAlias - Return true if there is any possibility that the two addresses
321 /// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000322 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000323 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +0000324 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000325 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000326 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +0000327 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000328 unsigned SrcValueAlign2,
329 const MDNode *TBAAInfo2) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000330
Nadav Rotem307d7672012-11-29 00:00:08 +0000331 /// isAlias - Return true if there is any possibility that the two addresses
332 /// overlap.
333 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
334
Jim Laskey08edf332006-10-11 13:47:09 +0000335 /// FindAliasInfo - Extracts the relevant alias information from the memory
336 /// node. Returns true if the operand was a load.
337 bool FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000338 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Nate Begeman879d8f12009-09-15 00:18:30 +0000339 const Value *&SrcValue, int &SrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000340 unsigned &SrcValueAlignment,
341 const MDNode *&TBAAInfo) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000342
Jim Laskeyd07be232006-09-25 16:29:54 +0000343 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000344 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000345 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000346
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000347 /// Merge consecutive store operations into a wide store.
348 /// This optimization uses wide integers or vectors when possible.
349 /// \return True if some memory operations were changed.
350 bool MergeConsecutiveStores(StoreSDNode *N);
351
Adam Nemet67483892014-03-04 23:28:31 +0000352 /// \brief Try to transform a truncation where C is a constant:
353 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
354 ///
355 /// \p N needs to be a truncation and its first operand an AND. Other
356 /// requirements are checked by the function (e.g. that trunc is
357 /// single-use) and if missed an empty SDValue is returned.
358 SDValue distributeTruncateThroughAnd(SDNode *N);
359
Chris Lattner4041ab62010-04-15 04:48:01 +0000360 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000361 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000362 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
363 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
364 AttributeSet FnAttrs =
365 DAG.getMachineFunction().getFunction()->getAttributes();
366 ForCodeSize =
367 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
368 Attribute::OptimizeForSize) ||
369 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
370 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000371
Nate Begeman21158fc2005-09-01 00:19:25 +0000372 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000373 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000374
Chris Lattner4041ab62010-04-15 04:48:01 +0000375 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000376
Chris Lattner4041ab62010-04-15 04:48:01 +0000377 /// getShiftAmountTy - Returns a type large enough to hold any valid
378 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000379 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000380 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
381 if (LHSTy.isVector())
382 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000383 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
384 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000385 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000386
Chris Lattner4041ab62010-04-15 04:48:01 +0000387 /// isTypeLegal - This method returns true if we are running before type
388 /// legalization or if the specified VT is legal.
389 bool isTypeLegal(const EVT &VT) {
390 if (!LegalTypes) return true;
391 return TLI.isTypeLegal(VT);
392 }
Matt Arsenault758659232013-05-18 00:21:46 +0000393
394 /// getSetCCResultType - Convenience wrapper around
395 /// TargetLowering::getSetCCResultType
396 EVT getSetCCResultType(EVT VT) const {
397 return TLI.getSetCCResultType(*DAG.getContext(), VT);
398 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000399 };
400}
401
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000402
403namespace {
404/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
405/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000406class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000407 DAGCombiner &DC;
408public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000409 explicit WorkListRemover(DAGCombiner &dc)
410 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000411
Craig Topper7b883b32014-03-08 06:31:39 +0000412 void NodeDeleted(SDNode *N, SDNode *E) override {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000413 DC.removeFromWorkList(N);
414 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000415};
416}
417
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000418//===----------------------------------------------------------------------===//
419// TargetLowering::DAGCombinerInfo implementation
420//===----------------------------------------------------------------------===//
421
422void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
423 ((DAGCombiner*)DC)->AddToWorkList(N);
424}
425
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000426void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
427 ((DAGCombiner*)DC)->removeFromWorkList(N);
428}
429
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000430SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000431CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
432 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000433}
434
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000435SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000436CombineTo(SDNode *N, SDValue Res, bool AddTo) {
437 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000438}
439
440
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000441SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000442CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
443 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000444}
445
Dan Gohmane58ab792009-01-29 01:59:02 +0000446void TargetLowering::DAGCombinerInfo::
447CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
448 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
449}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000450
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000451//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000452// Helper Functions
453//===----------------------------------------------------------------------===//
454
455/// isNegatibleForFree - Return 1 if we can compute the negated form of the
456/// specified expression for the same cost as the expression itself, or 2 if we
457/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000458static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000459 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000460 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000461 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000462 // fneg is removable even if it has multiple uses.
463 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000464
Chris Lattnere49c9742007-05-14 22:04:50 +0000465 // Don't allow anything with multiple uses.
466 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000467
Chris Lattner46980832007-05-25 02:19:06 +0000468 // Don't recurse exponentially.
469 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000470
Chris Lattnere49c9742007-05-14 22:04:50 +0000471 switch (Op.getOpcode()) {
472 default: return false;
473 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000474 // Don't invert constant FP values after legalize. The negated constant
475 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000476 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000477 case ISD::FADD:
478 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000479 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000480
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000481 // After operation legalization, it might not be legal to create new FSUBs.
482 if (LegalOperations &&
483 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
484 return 0;
485
Craig Topper03f39772012-09-09 22:58:45 +0000486 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000487 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
488 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000489 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000490 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000491 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000492 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000493 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000494 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000495 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000496
Bill Wendling6fbf5492009-01-30 23:10:18 +0000497 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000498 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000499
Chris Lattnere49c9742007-05-14 22:04:50 +0000500 case ISD::FMUL:
501 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000502 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000503
Bill Wendling6fbf5492009-01-30 23:10:18 +0000504 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000505 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
506 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000507 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000508
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000509 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000510 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000511
Chris Lattnere49c9742007-05-14 22:04:50 +0000512 case ISD::FP_EXTEND:
513 case ISD::FP_ROUND:
514 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000515 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000516 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000517 }
518}
519
520/// GetNegatedExpression - If isNegatibleForFree returns true, this function
521/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000522static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000523 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000524 // fneg is removable even if it has multiple uses.
525 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000526
Chris Lattnere49c9742007-05-14 22:04:50 +0000527 // Don't allow anything with multiple uses.
528 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000529
Chris Lattner46980832007-05-25 02:19:06 +0000530 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000531 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000532 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000533 case ISD::ConstantFP: {
534 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
535 V.changeSign();
536 return DAG.getConstantFP(V, Op.getValueType());
537 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000538 case ISD::FADD:
539 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000540 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000541
Bill Wendling6fbf5492009-01-30 23:10:18 +0000542 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000543 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000544 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000545 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000546 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000547 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000548 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000549 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000550 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000551 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000552 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000553 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000554 Op.getOperand(0));
555 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000556 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000557 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000558
Bill Wendling6fbf5492009-01-30 23:10:18 +0000559 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000560 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000561 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000562 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000563
Bill Wendling6fbf5492009-01-30 23:10:18 +0000564 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000565 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000566 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000567
Chris Lattnere49c9742007-05-14 22:04:50 +0000568 case ISD::FMUL:
569 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000570 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000571
Bill Wendling6fbf5492009-01-30 23:10:18 +0000572 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000573 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000574 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000575 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000576 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000577 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000578 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000579 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000580
Bill Wendling6fbf5492009-01-30 23:10:18 +0000581 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000582 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000583 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000584 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000585 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000586
Chris Lattnere49c9742007-05-14 22:04:50 +0000587 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000588 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000589 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000590 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000591 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000592 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000593 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000594 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000595 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000596 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000597 }
598}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000599
600
Nate Begeman2504fe22005-09-01 23:24:04 +0000601// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
602// that selects between the values 1 and 0, making it equivalent to a setcc.
Scott Michelcf0da6c2009-02-17 22:15:04 +0000603// Also, set the incoming LHS, RHS, and CC references to the appropriate
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000604// nodes based on the type of node we are checking. This simplifies life a
605// bit for the callers.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000606static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
607 SDValue &CC) {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000608 if (N.getOpcode() == ISD::SETCC) {
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000612 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000613 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000614 if (N.getOpcode() == ISD::SELECT_CC &&
Nate Begeman21158fc2005-09-01 00:19:25 +0000615 N.getOperand(2).getOpcode() == ISD::Constant &&
616 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohmanb72127a2008-03-13 22:13:53 +0000617 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000618 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
619 LHS = N.getOperand(0);
620 RHS = N.getOperand(1);
621 CC = N.getOperand(4);
Nate Begeman21158fc2005-09-01 00:19:25 +0000622 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000623 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000624 return false;
625}
626
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000627// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
628// one use. If this is true, it allows the users to invert the operation for
629// free when it is profitable to do so.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000630static bool isOneUseSetCC(SDValue N) {
631 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000632 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000633 return true;
634 return false;
635}
636
Matt Arsenault985b9de2014-03-17 18:58:01 +0000637/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
638/// elements are all the same constant or undefined.
639static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
640 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
641 if (!C)
642 return false;
643
644 APInt SplatUndef;
645 unsigned SplatBitSize;
646 bool HasAnyUndefs;
647 EVT EltVT = N->getValueType(0).getVectorElementType();
648 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
649 HasAnyUndefs) &&
650 EltVT.getSizeInBits() >= SplatBitSize);
651}
652
653// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000654static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
655 if (isa<ConstantSDNode>(N))
656 return N.getNode();
657 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
658 if(BV && BV->isConstant())
659 return BV;
660 return NULL;
661}
662
Matt Arsenault985b9de2014-03-17 18:58:01 +0000663// \brief Returns the SDNode if it is a constant splat BuildVector or constant
664// int.
665static ConstantSDNode *isConstOrConstSplat(SDValue N) {
666 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
667 return CN;
668
669 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
670 return BV->isConstantSplat();
671
672 return nullptr;
673}
674
Andrew Trickef9de2a2013-05-25 02:42:55 +0000675SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000676 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000677 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000678 if (N0.getOpcode() == Opc) {
679 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
680 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
681 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
682 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
683 if (!OpNode.getNode())
684 return SDValue();
685 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000686 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000687 if (N0.hasOneUse()) {
688 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
689 // use
690 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
691 if (!OpNode.getNode())
692 return SDValue();
693 AddToWorkList(OpNode.getNode());
694 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000695 }
696 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000697 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000698
Juergen Ributzka68402822014-01-13 21:49:25 +0000699 if (N1.getOpcode() == Opc) {
700 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
701 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
702 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
703 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
704 if (!OpNode.getNode())
705 return SDValue();
706 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
707 }
708 if (N1.hasOneUse()) {
709 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
710 // use
711 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
712 if (!OpNode.getNode())
713 return SDValue();
714 AddToWorkList(OpNode.getNode());
715 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
716 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000717 }
718 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000719
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000720 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000721}
722
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000723SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
724 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000725 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
726 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000727 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000728 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000729 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000730 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000731 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000732 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000733 assert((!To[i].getNode() ||
734 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000735 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000736 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000737 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000738 if (AddTo) {
739 // Push the new nodes and any users onto the worklist
740 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000741 if (To[i].getNode()) {
742 AddToWorkList(To[i].getNode());
743 AddUsersToWorkList(To[i].getNode());
744 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000745 }
746 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000747
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000748 // Finally, if the node is now dead, remove it from the graph. The node
749 // may not be dead if the replacement process recursively simplified to
750 // something else needing this node.
751 if (N->use_empty()) {
752 // Nodes can be reintroduced into the worklist. Make sure we do not
753 // process a node that has been replaced.
754 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000755
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000756 // Finally, since the node is now dead, remove it from the graph.
757 DAG.DeleteNode(N);
758 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000759 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000760}
761
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000762void DAGCombiner::
763CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000764 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000765 // are deleted, make sure to remove them from our worklist.
766 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000767 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000768
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000769 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000770 AddToWorkList(TLO.New.getNode());
771 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000772
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000773 // Finally, if the node is now dead, remove it from the graph. The node
774 // may not be dead if the replacement process recursively simplified to
775 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000776 if (TLO.Old.getNode()->use_empty()) {
777 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000778
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000779 // If the operands of this node are only used by the node, they will now
780 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000781 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
782 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
783 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000784
Gabor Greiff304a7a2008-08-28 21:40:38 +0000785 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000786 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000787}
788
789/// SimplifyDemandedBits - Check the specified integer node value to see if
790/// it can be simplified or if things it uses can be simplified by bit
791/// propagation. If so, return true.
792bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000793 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000794 APInt KnownZero, KnownOne;
795 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
796 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000797
Dan Gohmane58ab792009-01-29 01:59:02 +0000798 // Revisit the node.
799 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000800
Dan Gohmane58ab792009-01-29 01:59:02 +0000801 // Replace the old value with the new one.
802 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000803 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000804 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000805 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000806 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000807 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000808
Dan Gohmane58ab792009-01-29 01:59:02 +0000809 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000810 return true;
811}
812
Evan Cheng0abb54d2010-04-24 04:43:44 +0000813void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000814 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000815 EVT VT = Load->getValueType(0);
816 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000817
Evan Cheng0abb54d2010-04-24 04:43:44 +0000818 DEBUG(dbgs() << "\nReplacing.9 ";
819 Load->dump(&DAG);
820 dbgs() << "\nWith: ";
821 Trunc.getNode()->dump(&DAG);
822 dbgs() << '\n');
823 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000824 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
825 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000826 removeFromWorkList(Load);
827 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000828 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000829}
830
831SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
832 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000833 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000834 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000835 EVT MemVT = LD->getMemoryVT();
836 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000837 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000838 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000839 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000840 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000841 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000842 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000843 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000844 }
845
Evan Chenge19aa5c2010-04-19 19:29:22 +0000846 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000847 switch (Opc) {
848 default: break;
849 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000850 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000851 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000852 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000853 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000854 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000855 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000856 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000857 case ISD::Constant: {
858 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000859 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000860 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000861 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000862 }
863
864 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000865 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000866 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000867}
868
Evan Cheng0abb54d2010-04-24 04:43:44 +0000869SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000870 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
871 return SDValue();
872 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000873 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000874 bool Replace = false;
875 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
876 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000877 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000878 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000879
880 if (Replace)
881 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
882 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000883 DAG.getValueType(OldVT));
884}
885
Evan Cheng0abb54d2010-04-24 04:43:44 +0000886SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000887 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000888 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000889 bool Replace = false;
890 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
891 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000892 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000893 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000894
895 if (Replace)
896 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
897 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000898}
899
Evan Chengaf56fac2010-04-16 06:14:10 +0000900/// PromoteIntBinOp - Promote the specified integer binary operation if the
901/// target indicates it is beneficial. e.g. On x86, it's usually better to
902/// promote i16 operations to i32 since i16 instructions are longer.
903SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
904 if (!LegalOperations)
905 return SDValue();
906
907 EVT VT = Op.getValueType();
908 if (VT.isVector() || !VT.isInteger())
909 return SDValue();
910
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000911 // If operation type is 'undesirable', e.g. i16 on x86, consider
912 // promoting it.
913 unsigned Opc = Op.getOpcode();
914 if (TLI.isTypeDesirableForOp(Opc, VT))
915 return SDValue();
916
Evan Chengaf56fac2010-04-16 06:14:10 +0000917 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000918 // Consult target whether it is a good idea to promote this operation and
919 // what's the right type to promote it to.
920 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000921 assert(PVT != VT && "Don't know what type to promote to!");
922
Evan Cheng0abb54d2010-04-24 04:43:44 +0000923 bool Replace0 = false;
924 SDValue N0 = Op.getOperand(0);
925 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
926 if (NN0.getNode() == 0)
Evan Chengf1223bd2010-04-22 20:19:46 +0000927 return SDValue();
928
Evan Cheng0abb54d2010-04-24 04:43:44 +0000929 bool Replace1 = false;
930 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000931 SDValue NN1;
932 if (N0 == N1)
933 NN1 = NN0;
934 else {
935 NN1 = PromoteOperand(N1, PVT, Replace1);
936 if (NN1.getNode() == 0)
937 return SDValue();
938 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000939
Evan Cheng0abb54d2010-04-24 04:43:44 +0000940 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000941 if (NN1.getNode())
942 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000943
944 if (Replace0)
945 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
946 if (Replace1)
947 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000948
Evan Chenge8136902010-04-27 19:48:13 +0000949 DEBUG(dbgs() << "\nPromoting ";
950 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000951 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000952 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000953 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000954 }
955 return SDValue();
956}
957
958/// PromoteIntShiftOp - Promote the specified integer shift operation if the
959/// target indicates it is beneficial. e.g. On x86, it's usually better to
960/// promote i16 operations to i32 since i16 instructions are longer.
961SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
962 if (!LegalOperations)
963 return SDValue();
964
965 EVT VT = Op.getValueType();
966 if (VT.isVector() || !VT.isInteger())
967 return SDValue();
968
969 // If operation type is 'undesirable', e.g. i16 on x86, consider
970 // promoting it.
971 unsigned Opc = Op.getOpcode();
972 if (TLI.isTypeDesirableForOp(Opc, VT))
973 return SDValue();
974
975 EVT PVT = VT;
976 // Consult target whether it is a good idea to promote this operation and
977 // what's the right type to promote it to.
978 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
979 assert(PVT != VT && "Don't know what type to promote to!");
980
Evan Cheng0abb54d2010-04-24 04:43:44 +0000981 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000982 SDValue N0 = Op.getOperand(0);
983 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000984 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000985 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000986 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000987 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000988 N0 = PromoteOperand(N0, PVT, Replace);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000989 if (N0.getNode() == 0)
990 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000991
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000992 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000993 if (Replace)
994 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000995
Evan Chenge8136902010-04-27 19:48:13 +0000996 DEBUG(dbgs() << "\nPromoting ";
997 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000998 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000999 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001000 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001001 }
1002 return SDValue();
1003}
1004
Evan Chenge19aa5c2010-04-19 19:29:22 +00001005SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1006 if (!LegalOperations)
1007 return SDValue();
1008
1009 EVT VT = Op.getValueType();
1010 if (VT.isVector() || !VT.isInteger())
1011 return SDValue();
1012
1013 // If operation type is 'undesirable', e.g. i16 on x86, consider
1014 // promoting it.
1015 unsigned Opc = Op.getOpcode();
1016 if (TLI.isTypeDesirableForOp(Opc, VT))
1017 return SDValue();
1018
1019 EVT PVT = VT;
1020 // Consult target whether it is a good idea to promote this operation and
1021 // what's the right type to promote it to.
1022 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023 assert(PVT != VT && "Don't know what type to promote to!");
1024 // fold (aext (aext x)) -> (aext x)
1025 // fold (aext (zext x)) -> (zext x)
1026 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001027 DEBUG(dbgs() << "\nPromoting ";
1028 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001029 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001030 }
1031 return SDValue();
1032}
1033
1034bool DAGCombiner::PromoteLoad(SDValue Op) {
1035 if (!LegalOperations)
1036 return false;
1037
1038 EVT VT = Op.getValueType();
1039 if (VT.isVector() || !VT.isInteger())
1040 return false;
1041
1042 // If operation type is 'undesirable', e.g. i16 on x86, consider
1043 // promoting it.
1044 unsigned Opc = Op.getOpcode();
1045 if (TLI.isTypeDesirableForOp(Opc, VT))
1046 return false;
1047
1048 EVT PVT = VT;
1049 // Consult target whether it is a good idea to promote this operation and
1050 // what's the right type to promote it to.
1051 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052 assert(PVT != VT && "Don't know what type to promote to!");
1053
Andrew Trickef9de2a2013-05-25 02:42:55 +00001054 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001055 SDNode *N = Op.getNode();
1056 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001057 EVT MemVT = LD->getMemoryVT();
1058 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001059 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001060 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001061 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001062 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001063 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001064 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001065 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1066
Evan Cheng0abb54d2010-04-24 04:43:44 +00001067 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001068 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001069 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001070 Result.getNode()->dump(&DAG);
1071 dbgs() << '\n');
1072 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001073 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1074 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001075 removeFromWorkList(N);
1076 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001077 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001078 return true;
1079 }
1080 return false;
1081}
1082
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001083
Chris Lattnere49c9742007-05-14 22:04:50 +00001084//===----------------------------------------------------------------------===//
1085// Main DAG Combiner implementation
1086//===----------------------------------------------------------------------===//
1087
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001088void DAGCombiner::Run(CombineLevel AtLevel) {
1089 // set the instance variables, so that the various visit routines may use it.
1090 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001091 LegalOperations = Level >= AfterLegalizeVectorOps;
1092 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001093
Evan Cheng5e7658c2008-08-29 22:21:44 +00001094 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001095 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1096 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001097 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001098
Evan Cheng5e7658c2008-08-29 22:21:44 +00001099 // Create a dummy node (which is not added to allnodes), that adds a reference
1100 // to the root node, preventing it from being deleted, and tracking any
1101 // changes of the root.
1102 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001103
Jim Laskeye7d2c242006-10-17 19:33:52 +00001104 // The root of the dag may dangle to deleted nodes until the dag combiner is
1105 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001106 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001107
James Molloy67b6b112012-02-16 09:17:04 +00001108 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001109 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001110 while (!WorkListContents.empty()) {
1111 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001112 // The WorkListOrder holds the SDNodes in order, but it may contain
1113 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001114 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1115 // worklist *should* contain, and check the node we want to visit is should
1116 // actually be visited.
1117 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001118 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001119 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001120
Evan Cheng5e7658c2008-08-29 22:21:44 +00001121 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1122 // N is deleted from the DAG, since they too may now be dead or may have a
1123 // reduced number of uses, allowing other xforms.
1124 if (N->use_empty() && N != &Dummy) {
1125 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1126 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001127
Evan Cheng5e7658c2008-08-29 22:21:44 +00001128 DAG.DeleteNode(N);
1129 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001130 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001131
Evan Cheng5e7658c2008-08-29 22:21:44 +00001132 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001133
Evan Cheng5e7658c2008-08-29 22:21:44 +00001134 if (RV.getNode() == 0)
1135 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001136
Evan Cheng5e7658c2008-08-29 22:21:44 +00001137 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001138
Evan Cheng5e7658c2008-08-29 22:21:44 +00001139 // If we get back the same node we passed in, rather than a new node or
1140 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001141 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001142 // mechanics for us, we have no work to do in this case.
1143 if (RV.getNode() == N)
1144 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001145
Evan Cheng5e7658c2008-08-29 22:21:44 +00001146 assert(N->getOpcode() != ISD::DELETED_NODE &&
1147 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1148 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001149
Wesley Peck527da1b2010-11-23 03:31:01 +00001150 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001151 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001152 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001153 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001154 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001155
Devang Patelefec7712011-05-23 22:04:42 +00001156 // Transfer debug value.
1157 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001158 WorkListRemover DeadNodes(*this);
1159 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001160 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001161 else {
1162 assert(N->getValueType(0) == RV.getValueType() &&
1163 N->getNumValues() == 1 && "Type mismatch");
1164 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001165 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001166 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001167
Evan Cheng5e7658c2008-08-29 22:21:44 +00001168 // Push the new node and any users onto the worklist
1169 AddToWorkList(RV.getNode());
1170 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001171
Evan Cheng5e7658c2008-08-29 22:21:44 +00001172 // Add any uses of the old node to the worklist in case this node is the
1173 // last one that uses them. They may become dead after this node is
1174 // deleted.
1175 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1176 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001177
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001178 // Finally, if the node is now dead, remove it from the graph. The node
1179 // may not be dead if the replacement process recursively simplified to
1180 // something else needing this node.
1181 if (N->use_empty()) {
1182 // Nodes can be reintroduced into the worklist. Make sure we do not
1183 // process a node that has been replaced.
1184 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001185
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001186 // Finally, since the node is now dead, remove it from the graph.
1187 DAG.DeleteNode(N);
1188 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001189 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001190
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001191 // If the root changed (e.g. it was a dead load, update the root).
1192 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001193 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001194}
1195
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001196SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001197 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001198 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001199 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001200 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001201 case ISD::ADD: return visitADD(N);
1202 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001203 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001204 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001205 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001206 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001207 case ISD::MUL: return visitMUL(N);
1208 case ISD::SDIV: return visitSDIV(N);
1209 case ISD::UDIV: return visitUDIV(N);
1210 case ISD::SREM: return visitSREM(N);
1211 case ISD::UREM: return visitUREM(N);
1212 case ISD::MULHU: return visitMULHU(N);
1213 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001214 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1215 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001216 case ISD::SMULO: return visitSMULO(N);
1217 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001218 case ISD::SDIVREM: return visitSDIVREM(N);
1219 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001220 case ISD::AND: return visitAND(N);
1221 case ISD::OR: return visitOR(N);
1222 case ISD::XOR: return visitXOR(N);
1223 case ISD::SHL: return visitSHL(N);
1224 case ISD::SRA: return visitSRA(N);
1225 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001226 case ISD::ROTR:
1227 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001228 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001229 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001230 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001231 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001232 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001233 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001234 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001235 case ISD::SELECT_CC: return visitSELECT_CC(N);
1236 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001237 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1238 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001239 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001240 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1241 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001242 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001243 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001244 case ISD::FADD: return visitFADD(N);
1245 case ISD::FSUB: return visitFSUB(N);
1246 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001247 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001248 case ISD::FDIV: return visitFDIV(N);
1249 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001250 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001251 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1252 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1253 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1254 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1255 case ISD::FP_ROUND: return visitFP_ROUND(N);
1256 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1257 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1258 case ISD::FNEG: return visitFNEG(N);
1259 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001260 case ISD::FFLOOR: return visitFFLOOR(N);
1261 case ISD::FCEIL: return visitFCEIL(N);
1262 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001263 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001264 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001265 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001266 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001267 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001268 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001269 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1270 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001271 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001272 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001273 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001274 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001275 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001276}
1277
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001278SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001279 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001280
1281 // If nothing happened, try a target-specific DAG combine.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001282 if (RV.getNode() == 0) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001283 assert(N->getOpcode() != ISD::DELETED_NODE &&
1284 "Node was deleted but visit returned NULL!");
1285
1286 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1287 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1288
1289 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001290 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001291 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001292
1293 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1294 }
1295 }
1296
Evan Chengf1005572010-04-28 07:10:39 +00001297 // If nothing happened still, try promoting the operation.
1298 if (RV.getNode() == 0) {
1299 switch (N->getOpcode()) {
1300 default: break;
1301 case ISD::ADD:
1302 case ISD::SUB:
1303 case ISD::MUL:
1304 case ISD::AND:
1305 case ISD::OR:
1306 case ISD::XOR:
1307 RV = PromoteIntBinOp(SDValue(N, 0));
1308 break;
1309 case ISD::SHL:
1310 case ISD::SRA:
1311 case ISD::SRL:
1312 RV = PromoteIntShiftOp(SDValue(N, 0));
1313 break;
1314 case ISD::SIGN_EXTEND:
1315 case ISD::ZERO_EXTEND:
1316 case ISD::ANY_EXTEND:
1317 RV = PromoteExtend(SDValue(N, 0));
1318 break;
1319 case ISD::LOAD:
1320 if (PromoteLoad(SDValue(N, 0)))
1321 RV = SDValue(N, 0);
1322 break;
1323 }
1324 }
1325
Scott Michelcf0da6c2009-02-17 22:15:04 +00001326 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001327 // sdisel CSE.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001328 if (RV.getNode() == 0 &&
Evan Cheng31604a62008-03-22 01:55:50 +00001329 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1330 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001331 SDValue N0 = N->getOperand(0);
1332 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001333
Evan Cheng31604a62008-03-22 01:55:50 +00001334 // Constant operands are canonicalized to RHS.
1335 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001336 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001337 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1338 Ops, 2);
Evan Chengfe7610f2008-03-24 23:55:16 +00001339 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001340 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001341 }
1342 }
1343
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001344 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001345}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001346
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001347/// getInputChainForNode - Given a node, return its input chain if it has one,
1348/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001349static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001350 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001351 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001352 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001353 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001354 return N->getOperand(NumOps-1);
1355 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001356 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001357 return N->getOperand(i);
1358 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001359 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001360}
1361
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001362SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001363 // If N has two operands, where one has an input chain equal to the other,
1364 // the 'other' chain is redundant.
1365 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001366 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001367 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001368 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001369 return N->getOperand(1);
1370 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001371
Chris Lattner48fb92f2007-05-16 06:37:59 +00001372 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001373 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001374 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001375 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001376
Jim Laskey708d0db2006-10-04 16:53:27 +00001377 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001378 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001379
Jim Laskey0463e082006-10-07 23:37:56 +00001380 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001381 // encountered.
1382 for (unsigned i = 0; i < TFs.size(); ++i) {
1383 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001384
Jim Laskey708d0db2006-10-04 16:53:27 +00001385 // Check each of the operands.
1386 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001387 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001388
Jim Laskey708d0db2006-10-04 16:53:27 +00001389 switch (Op.getOpcode()) {
1390 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001391 // Entry tokens don't need to be added to the list. They are
1392 // rededundant.
1393 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001394 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001395
Jim Laskey708d0db2006-10-04 16:53:27 +00001396 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001397 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001398 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001399 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001400 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001401 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001402 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001403 Changed = true;
1404 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001405 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001406 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001407
Jim Laskey708d0db2006-10-04 16:53:27 +00001408 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001409 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001410 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001411 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001412 else
1413 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001414 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001415 }
1416 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001417 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001418
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001419 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001420
1421 // If we've change things around then replace token factor.
1422 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001423 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001424 // The entry token is the only possible outcome.
1425 Result = DAG.getEntryNode();
1426 } else {
1427 // New and improved token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001428 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00001429 MVT::Other, &Ops[0], Ops.size());
Nate Begeman02b23c62005-10-13 03:11:28 +00001430 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001431
Jim Laskeydcf983c2006-10-13 23:32:28 +00001432 // Don't add users to work list.
1433 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001434 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001435
Jim Laskey708d0db2006-10-04 16:53:27 +00001436 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001437}
1438
Chris Lattneree322b42008-02-13 07:25:05 +00001439/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001440SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001441 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001442 // Replacing results may cause a different MERGE_VALUES to suddenly
1443 // be CSE'd with N, and carry its uses with it. Iterate until no
1444 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001445 // First add the users of this node to the work list so that they
1446 // can be tried again once they have new operands.
1447 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001448 do {
1449 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001450 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001451 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001452 removeFromWorkList(N);
1453 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001454 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001455}
1456
Evan Cheng92011002007-01-19 17:51:44 +00001457static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001458SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001459 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001460 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001461 SDValue N00 = N0.getOperand(0);
1462 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001463 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001464
Gabor Greiff304a7a2008-08-28 21:40:38 +00001465 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001466 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001467 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001468 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1469 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001470 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001471 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001472 N00.getOperand(1), N01));
1473 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001474 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001475
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001476 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001477}
1478
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001479SDValue DAGCombiner::visitADD(SDNode *N) {
1480 SDValue N0 = N->getOperand(0);
1481 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001482 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1483 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001484 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001485
1486 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001487 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001488 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001489 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001490
1491 // fold (add x, 0) -> x, vector edition
1492 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1493 return N0;
1494 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1495 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001496 }
Bill Wendling0864a752008-12-10 22:36:00 +00001497
Dan Gohman06563a82007-07-03 14:03:57 +00001498 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001499 if (N0.getOpcode() == ISD::UNDEF)
1500 return N0;
1501 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001502 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001503 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001504 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001505 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001506 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001507 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001508 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001509 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001510 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001511 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001512 // fold (add Sym, c) -> Sym+c
1513 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001514 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001515 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001516 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001517 GA->getOffset() +
1518 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001519 // fold ((c1-A)+c2) -> (c1+c2)-A
1520 if (N1C && N0.getOpcode() == ISD::SUB)
1521 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001522 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001523 DAG.getConstant(N1C->getAPIntValue()+
1524 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001525 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001526 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001527 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001528 if (RADD.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001529 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001530 // fold ((0-A) + B) -> B-A
1531 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1532 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001533 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001534 // fold (A + (0-B)) -> A-B
1535 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1536 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001537 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001538 // fold (A+(B-A)) -> B
1539 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001540 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001541 // fold ((B-A)+A) -> B
1542 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1543 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001544 // fold (A+(B-(A+C))) to (B-C)
1545 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001546 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001547 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001548 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001549 // fold (A+(B-(C+A))) to (B-C)
1550 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001551 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001552 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001553 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001554 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001555 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1556 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001557 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001558 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001559 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001560
Dale Johannesen8c766702008-12-02 01:30:54 +00001561 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1562 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1563 SDValue N00 = N0.getOperand(0);
1564 SDValue N01 = N0.getOperand(1);
1565 SDValue N10 = N1.getOperand(0);
1566 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001567
1568 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001569 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1570 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1571 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001572 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001573
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001574 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1575 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001576
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001577 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001578 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001579 APInt LHSZero, LHSOne;
1580 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001581 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001582
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001583 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001584 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001585
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001586 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1587 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001588 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1589 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1590 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1591 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001592 }
1593 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001594
Evan Cheng92011002007-01-19 17:51:44 +00001595 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001596 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001597 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001598 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001599 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001600 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001601 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001602 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001603 }
1604
Dan Gohman954f4902010-01-19 23:30:49 +00001605 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1606 if (N1.getOpcode() == ISD::SHL &&
1607 N1.getOperand(0).getOpcode() == ISD::SUB)
1608 if (ConstantSDNode *C =
1609 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1610 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001611 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1612 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001613 N1.getOperand(0).getOperand(1),
1614 N1.getOperand(1)));
1615 if (N0.getOpcode() == ISD::SHL &&
1616 N0.getOperand(0).getOpcode() == ISD::SUB)
1617 if (ConstantSDNode *C =
1618 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1619 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001620 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1621 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001622 N0.getOperand(0).getOperand(1),
1623 N0.getOperand(1)));
1624
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001625 if (N1.getOpcode() == ISD::AND) {
1626 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001627 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001628 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1629 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001630
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001631 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1632 // and similar xforms where the inner op is either ~0 or 0.
1633 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001634 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001635 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1636 }
1637 }
1638
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001639 // add (sext i1), X -> sub X, (zext i1)
1640 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1641 N0.getOperand(0).getValueType() == MVT::i1 &&
1642 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001643 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001644 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1645 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1646 }
1647
Evan Chengf1005572010-04-28 07:10:39 +00001648 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001649}
1650
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001651SDValue DAGCombiner::visitADDC(SDNode *N) {
1652 SDValue N0 = N->getOperand(0);
1653 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001654 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1655 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001656 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001657
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001658 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001659 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001660 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001661 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001662 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001663
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001664 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001665 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001666 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001667
Chris Lattner47206662007-03-04 20:40:38 +00001668 // fold (addc x, 0) -> x + no carry out
1669 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001670 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001671 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001672
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001673 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001674 APInt LHSZero, LHSOne;
1675 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001676 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001677
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001678 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001679 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001680
Chris Lattner47206662007-03-04 20:40:38 +00001681 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1682 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001683 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001684 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001685 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001686 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001687 }
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
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001692SDValue DAGCombiner::visitADDE(SDNode *N) {
1693 SDValue N0 = N->getOperand(0);
1694 SDValue N1 = N->getOperand(1);
1695 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001696 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1697 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001698
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001699 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001700 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001701 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001702 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001703
Chris Lattner47206662007-03-04 20:40:38 +00001704 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001705 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001706 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001707
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001708 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001709}
1710
Eric Christophere5ca1e02011-02-16 04:50:12 +00001711// Since it may not be valid to emit a fold to zero for vector initializers
1712// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001713static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001714 SelectionDAG &DAG,
1715 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001716 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001717 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001718 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1719 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001720 return SDValue();
1721}
1722
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001723SDValue DAGCombiner::visitSUB(SDNode *N) {
1724 SDValue N0 = N->getOperand(0);
1725 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001726 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1727 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001728 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1729 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001730 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001731
Dan Gohmana8665142007-06-25 16:23:39 +00001732 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001733 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001734 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001735 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001736
1737 // fold (sub x, 0) -> x, vector edition
1738 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1739 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001740 }
Bill Wendling0864a752008-12-10 22:36:00 +00001741
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001742 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001743 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001744 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001745 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001746 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001747 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001748 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001749 // fold (sub x, c) -> (add x, -c)
1750 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001751 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001752 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001753 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1754 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001755 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001756 // fold A-(A-B) -> B
1757 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1758 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001759 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001760 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001761 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001762 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001763 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001764 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001765 // fold C2-(A+C1) -> (C2-C1)-A
1766 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001767 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1768 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001769 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001770 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001771 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001772 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001773 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001774 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1775 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001776 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001777 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001778 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001779 // fold ((A+(C+B))-B) -> A+C
1780 if (N0.getOpcode() == ISD::ADD &&
1781 N0.getOperand(1).getOpcode() == ISD::ADD &&
1782 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001783 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001784 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001785 // fold ((A-(B-C))-C) -> A-B
1786 if (N0.getOpcode() == ISD::SUB &&
1787 N0.getOperand(1).getOpcode() == ISD::SUB &&
1788 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001789 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001790 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001791
Dan Gohman06563a82007-07-03 14:03:57 +00001792 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001793 if (N0.getOpcode() == ISD::UNDEF)
1794 return N0;
1795 if (N1.getOpcode() == ISD::UNDEF)
1796 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001797
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001798 // If the relocation model supports it, consider symbol offsets.
1799 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001800 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001801 // fold (sub Sym, c) -> Sym-c
1802 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001803 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001804 GA->getOffset() -
1805 (uint64_t)N1C->getSExtValue());
1806 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1807 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1808 if (GA->getGlobal() == GB->getGlobal())
1809 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1810 VT);
1811 }
1812
Evan Chengf1005572010-04-28 07:10:39 +00001813 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001814}
1815
Craig Topper43a1bd62012-01-07 09:06:39 +00001816SDValue DAGCombiner::visitSUBC(SDNode *N) {
1817 SDValue N0 = N->getOperand(0);
1818 SDValue N1 = N->getOperand(1);
1819 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1820 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1821 EVT VT = N0.getValueType();
1822
1823 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001824 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001825 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1826 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001827 MVT::Glue));
1828
1829 // fold (subc x, x) -> 0 + no borrow
1830 if (N0 == N1)
1831 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001832 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001833 MVT::Glue));
1834
1835 // fold (subc x, 0) -> x + no borrow
1836 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001837 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001838 MVT::Glue));
1839
1840 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1841 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001842 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1843 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001844 MVT::Glue));
1845
1846 return SDValue();
1847}
1848
1849SDValue DAGCombiner::visitSUBE(SDNode *N) {
1850 SDValue N0 = N->getOperand(0);
1851 SDValue N1 = N->getOperand(1);
1852 SDValue CarryIn = N->getOperand(2);
1853
1854 // fold (sube x, y, false) -> (subc x, y)
1855 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001856 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001857
1858 return SDValue();
1859}
1860
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001861SDValue DAGCombiner::visitMUL(SDNode *N) {
1862 SDValue N0 = N->getOperand(0);
1863 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001864 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001865
Dan Gohman06563a82007-07-03 14:03:57 +00001866 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001867 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001868 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001869
1870 bool N0IsConst = false;
1871 bool N1IsConst = false;
1872 APInt ConstValue0, ConstValue1;
1873 // fold vector ops
1874 if (VT.isVector()) {
1875 SDValue FoldedVOp = SimplifyVBinOp(N);
1876 if (FoldedVOp.getNode()) return FoldedVOp;
1877
1878 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1879 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1880 } else {
1881 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001882 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1883 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001884 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001885 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1886 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001887 }
1888
Nate Begeman21158fc2005-09-01 00:19:25 +00001889 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001890 if (N0IsConst && N1IsConst)
1891 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1892
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001893 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001894 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001895 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001896 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001897 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001898 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001899 // We require a splat of the entire scalar bit width for non-contiguous
1900 // bit patterns.
1901 bool IsFullSplat =
1902 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001903 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001904 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001905 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001906 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001907 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001908 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001909 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001910 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001911 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001912 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001913 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001914 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001915 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001916 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001917 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001918 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001919 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001920 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001921 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001922 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001923 DAG.getConstant(Log2Val,
1924 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001925 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001926
1927 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001928 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001929 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001930 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001932 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001933 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001934 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001935 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001936 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001937 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001938
Chris Lattner324871e2006-03-01 03:44:24 +00001939 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1940 // use.
1941 {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001942 SDValue Sh(0,0), Y(0,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001943 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001944 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001945 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1946 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001947 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001948 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001949 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001950 isa<ConstantSDNode>(N1.getOperand(1)) &&
1951 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001952 Sh = N1; Y = N0;
1953 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001954
Gabor Greiff304a7a2008-08-28 21:40:38 +00001955 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001956 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001957 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001958 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001959 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001960 }
1961 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001962
Chris Lattnerf29f5202006-03-04 23:33:26 +00001963 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001964 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1965 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1966 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001967 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1968 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001969 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001970 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001971 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001972
Nate Begeman22e251a2006-02-03 06:46:56 +00001973 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001974 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001975 if (RMUL.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001976 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001977
Evan Chengf1005572010-04-28 07:10:39 +00001978 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001979}
1980
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001981SDValue DAGCombiner::visitSDIV(SDNode *N) {
1982 SDValue N0 = N->getOperand(0);
1983 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001984 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1985 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001986 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001987
Dan Gohmana8665142007-06-25 16:23:39 +00001988 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001989 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001990 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001991 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001992 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001993
Nate Begeman21158fc2005-09-01 00:19:25 +00001994 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001995 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001996 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001997 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001998 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001999 return N0;
2000 // fold (sdiv X, -1) -> 0-X
2001 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002002 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002003 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002004 // If we know the sign bits of both operands are zero, strength reduce to a
2005 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002006 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002007 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002008 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002009 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002010 }
Nate Begeman57b35672006-02-17 07:26:20 +00002011 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedmanf9081a82011-12-07 03:55:52 +00002012 if (N1C && !N1C->isNullValue() &&
Eli Friedmane9e356a2011-10-27 02:06:39 +00002013 (N1C->getAPIntValue().isPowerOf2() ||
2014 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002015 // If dividing by powers of two is cheap, then don't perform the following
2016 // fold.
2017 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002018 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002019
Eli Friedmane9e356a2011-10-27 02:06:39 +00002020 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002021
Chris Lattner471627c2006-02-16 08:02:36 +00002022 // Splat the sign bit into the register
Andrew Trickef9de2a2013-05-25 02:42:55 +00002023 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling5b663e72009-01-30 02:52:17 +00002024 DAG.getConstant(VT.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002025 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002026 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002027
Chris Lattner471627c2006-02-16 08:02:36 +00002028 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002029 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling5b663e72009-01-30 02:52:17 +00002030 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002031 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002032 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002033 AddToWorkList(SRL.getNode());
2034 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002035 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002036 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002037
Nate Begeman4dd38312005-10-21 00:02:42 +00002038 // If we're dividing by a positive value, we're done. Otherwise, we must
2039 // negate the result.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002040 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002041 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002042
Gabor Greiff304a7a2008-08-28 21:40:38 +00002043 AddToWorkList(SRA.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002044 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002045 DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002046 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002047
Nate Begemanc6f067a2005-10-20 02:15:44 +00002048 // if integer divide is expensive and we satisfy the requirements, emit an
2049 // alternate sequence.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002050 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002051 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002052 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002053 }
Dan Gohmana8665142007-06-25 16:23:39 +00002054
Dan Gohman06563a82007-07-03 14:03:57 +00002055 // undef / X -> 0
2056 if (N0.getOpcode() == ISD::UNDEF)
2057 return DAG.getConstant(0, VT);
2058 // X / undef -> undef
2059 if (N1.getOpcode() == ISD::UNDEF)
2060 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002061
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002062 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002063}
2064
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002065SDValue DAGCombiner::visitUDIV(SDNode *N) {
2066 SDValue N0 = N->getOperand(0);
2067 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002068 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00002070 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002071
Dan Gohmana8665142007-06-25 16:23:39 +00002072 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002073 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002074 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002075 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002076 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002077
Nate Begeman21158fc2005-09-01 00:19:25 +00002078 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002079 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002080 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002081 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002082 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002083 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002084 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002085 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002086 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002087 if (N1.getOpcode() == ISD::SHL) {
2088 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002089 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002090 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002091 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002092 N1.getOperand(1),
2093 DAG.getConstant(SHC->getAPIntValue()
2094 .logBase2(),
2095 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002096 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002097 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002098 }
2099 }
2100 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002101 // fold (udiv x, c) -> alternate
Dan Gohmanb72127a2008-03-13 22:13:53 +00002102 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002103 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002104 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002105 }
Dan Gohmana8665142007-06-25 16:23:39 +00002106
Dan Gohman06563a82007-07-03 14:03:57 +00002107 // undef / X -> 0
2108 if (N0.getOpcode() == ISD::UNDEF)
2109 return DAG.getConstant(0, VT);
2110 // X / undef -> undef
2111 if (N1.getOpcode() == ISD::UNDEF)
2112 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002113
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002114 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002115}
2116
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002117SDValue DAGCombiner::visitSREM(SDNode *N) {
2118 SDValue N0 = N->getOperand(0);
2119 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002120 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2121 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002122 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002123
Nate Begeman21158fc2005-09-01 00:19:25 +00002124 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002125 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002126 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002127 // If we know the sign bits of both operands are zero, strength reduce to a
2128 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002129 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002130 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002131 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002132 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002133
Dan Gohman9a693412007-11-26 23:46:11 +00002134 // If X/C can be simplified by the division-by-constant logic, lower
2135 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002136 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002137 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002138 AddToWorkList(Div.getNode());
2139 SDValue OptimizedDiv = combine(Div.getNode());
2140 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002141 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002142 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002143 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002144 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002145 return Sub;
2146 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002147 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002148
Dan Gohman06563a82007-07-03 14:03:57 +00002149 // undef % X -> 0
2150 if (N0.getOpcode() == ISD::UNDEF)
2151 return DAG.getConstant(0, VT);
2152 // X % undef -> undef
2153 if (N1.getOpcode() == ISD::UNDEF)
2154 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002155
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002156 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002157}
2158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002159SDValue DAGCombiner::visitUREM(SDNode *N) {
2160 SDValue N0 = N->getOperand(0);
2161 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002162 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2163 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002164 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002165
Nate Begeman21158fc2005-09-01 00:19:25 +00002166 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002167 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002168 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002169 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002170 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002171 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002172 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002173 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2174 if (N1.getOpcode() == ISD::SHL) {
2175 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002176 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002177 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002178 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002179 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002180 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002181 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002182 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002183 }
2184 }
2185 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002186
Dan Gohman9a693412007-11-26 23:46:11 +00002187 // If X/C can be simplified by the division-by-constant logic, lower
2188 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002189 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002190 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002191 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002192 SDValue OptimizedDiv = combine(Div.getNode());
2193 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002194 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002195 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002196 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002197 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002198 return Sub;
2199 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002200 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002201
Dan Gohman06563a82007-07-03 14:03:57 +00002202 // undef % X -> 0
2203 if (N0.getOpcode() == ISD::UNDEF)
2204 return DAG.getConstant(0, VT);
2205 // X % undef -> undef
2206 if (N1.getOpcode() == ISD::UNDEF)
2207 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002208
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002209 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002210}
2211
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002212SDValue DAGCombiner::visitMULHS(SDNode *N) {
2213 SDValue N0 = N->getOperand(0);
2214 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002215 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002216 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002217 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002218
Nate Begeman21158fc2005-09-01 00:19:25 +00002219 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002220 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002221 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002222 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002223 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002224 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002225 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002226 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002227 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002228 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002229 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002230
Chris Lattner10bd29f2010-12-13 08:39:01 +00002231 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2232 // plus a shift.
2233 if (VT.isSimple() && !VT.isVector()) {
2234 MVT Simple = VT.getSimpleVT();
2235 unsigned SimpleSize = Simple.getSizeInBits();
2236 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2237 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2238 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2239 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2240 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002241 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002242 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002243 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2244 }
2245 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002246
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002247 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002248}
2249
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002250SDValue DAGCombiner::visitMULHU(SDNode *N) {
2251 SDValue N0 = N->getOperand(0);
2252 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002253 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002254 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002255 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002256
Nate Begeman21158fc2005-09-01 00:19:25 +00002257 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002258 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002259 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002260 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002261 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002262 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002263 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002264 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002265 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002266
Chris Lattner10bd29f2010-12-13 08:39:01 +00002267 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2268 // plus a shift.
2269 if (VT.isSimple() && !VT.isVector()) {
2270 MVT Simple = VT.getSimpleVT();
2271 unsigned SimpleSize = Simple.getSizeInBits();
2272 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2273 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2274 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2275 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2276 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2277 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002278 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002279 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2280 }
2281 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002282
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002283 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002284}
2285
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002286/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2287/// compute two values. LoOp and HiOp give the opcodes for the two computations
2288/// that are being performed. Return true if a simplification was made.
2289///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002290SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002291 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002292 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002293 bool HiExists = N->hasAnyUseOfValue(1);
2294 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002295 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002296 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002297 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002298 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002299 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002300 }
2301
2302 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002303 bool LoExists = N->hasAnyUseOfValue(0);
2304 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002305 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002306 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002307 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002308 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002309 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002310 }
2311
Evan Chengece4c682007-11-08 09:25:29 +00002312 // If both halves are used, return as it is.
2313 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002314 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002315
2316 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002317 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002318 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002319 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002320 AddToWorkList(Lo.getNode());
2321 SDValue LoOpt = combine(Lo.getNode());
2322 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002323 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002324 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002325 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002326 }
2327
Evan Chengece4c682007-11-08 09:25:29 +00002328 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002329 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002330 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002331 AddToWorkList(Hi.getNode());
2332 SDValue HiOpt = combine(Hi.getNode());
2333 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002334 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002335 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002336 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002337 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002338
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002339 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002340}
2341
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002342SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2343 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002344 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002345
Chris Lattner15090e12010-12-15 06:04:19 +00002346 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002347 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002348
2349 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2350 // plus a shift.
2351 if (VT.isSimple() && !VT.isVector()) {
2352 MVT Simple = VT.getSimpleVT();
2353 unsigned SimpleSize = Simple.getSizeInBits();
2354 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2355 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2356 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2357 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2358 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2359 // Compute the high part as N1.
2360 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002361 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002362 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2363 // Compute the low part as N0.
2364 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2365 return CombineTo(N, Lo, Hi);
2366 }
2367 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002368
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002369 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002370}
2371
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002372SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2373 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002374 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002375
Chris Lattner15090e12010-12-15 06:04:19 +00002376 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002377 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002378
Chris Lattner15090e12010-12-15 06:04:19 +00002379 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2380 // plus a shift.
2381 if (VT.isSimple() && !VT.isVector()) {
2382 MVT Simple = VT.getSimpleVT();
2383 unsigned SimpleSize = Simple.getSizeInBits();
2384 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2385 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2386 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2387 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2388 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2389 // Compute the high part as N1.
2390 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002391 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002392 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2393 // Compute the low part as N0.
2394 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2395 return CombineTo(N, Lo, Hi);
2396 }
2397 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002398
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002399 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002400}
2401
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002402SDValue DAGCombiner::visitSMULO(SDNode *N) {
2403 // (smulo x, 2) -> (saddo x, x)
2404 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2405 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002406 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002407 N->getOperand(0), N->getOperand(0));
2408
2409 return SDValue();
2410}
2411
2412SDValue DAGCombiner::visitUMULO(SDNode *N) {
2413 // (umulo x, 2) -> (uaddo x, x)
2414 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2415 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002416 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002417 N->getOperand(0), N->getOperand(0));
2418
2419 return SDValue();
2420}
2421
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002422SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2423 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002424 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002425
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002426 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002427}
2428
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002429SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2430 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002431 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002432
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002433 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002434}
2435
Chris Lattner8d6fc202006-05-05 05:51:50 +00002436/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2437/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002438SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2439 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002440 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002441 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002442
Dan Gohmandd5286d2010-01-14 03:08:49 +00002443 // Bail early if none of these transforms apply.
2444 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2445
Chris Lattner002ee912006-05-05 06:31:05 +00002446 // For each of OP in AND/OR/XOR:
2447 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2448 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2449 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002450 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002451 //
2452 // do not sink logical op inside of a vector extend, since it may combine
2453 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002454 EVT Op0VT = N0.getOperand(0).getValueType();
2455 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002456 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002457 // Avoid infinite looping with PromoteIntBinOp.
2458 (N0.getOpcode() == ISD::ANY_EXTEND &&
2459 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002460 (N0.getOpcode() == ISD::TRUNCATE &&
2461 (!TLI.isZExtFree(VT, Op0VT) ||
2462 !TLI.isTruncateFree(Op0VT, VT)) &&
2463 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002464 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002465 Op0VT == N1.getOperand(0).getValueType() &&
2466 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002467 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002468 N0.getOperand(0).getValueType(),
2469 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002470 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002471 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002473
Chris Lattner5ac42932006-05-05 06:10:43 +00002474 // For each of OP in SHL/SRL/SRA/AND...
2475 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2476 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2477 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002478 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002479 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002480 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002481 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002482 N0.getOperand(0).getValueType(),
2483 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002484 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002485 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002486 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002487 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002488
Nadav Rotemb0783502012-04-01 19:31:22 +00002489 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2490 // Only perform this optimization after type legalization and before
2491 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2492 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2493 // we don't want to undo this promotion.
2494 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2495 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002496 if ((N0.getOpcode() == ISD::BITCAST ||
2497 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2498 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002499 SDValue In0 = N0.getOperand(0);
2500 SDValue In1 = N1.getOperand(0);
2501 EVT In0Ty = In0.getValueType();
2502 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002503 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002504 // If both incoming values are integers, and the original types are the
2505 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002506 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002507 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2508 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002509 AddToWorkList(Op.getNode());
2510 return BC;
2511 }
2512 }
2513
2514 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2515 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2516 // If both shuffles use the same mask, and both shuffle within a single
2517 // vector, then it is worthwhile to move the swizzle after the operation.
2518 // The type-legalizer generates this pattern when loading illegal
2519 // vector types from memory. In many cases this allows additional shuffle
2520 // optimizations.
Craig Topper9c3da312012-04-09 07:19:09 +00002521 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2522 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2523 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002524 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2525 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002526
2527 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2528 "Inputs to shuffles are not the same type");
Nadav Rotemb0783502012-04-01 19:31:22 +00002529
2530 unsigned NumElts = VT.getVectorNumElements();
Nadav Rotemb0783502012-04-01 19:31:22 +00002531
2532 // Check that both shuffles use the same mask. The masks are known to be of
2533 // the same length because the result vector type is the same.
2534 bool SameMask = true;
2535 for (unsigned i = 0; i != NumElts; ++i) {
2536 int Idx0 = SVN0->getMaskElt(i);
2537 int Idx1 = SVN1->getMaskElt(i);
2538 if (Idx0 != Idx1) {
2539 SameMask = false;
2540 break;
2541 }
2542 }
2543
Craig Topper9c3da312012-04-09 07:19:09 +00002544 if (SameMask) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002545 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
Craig Topper9c3da312012-04-09 07:19:09 +00002546 N0.getOperand(0), N1.getOperand(0));
Nadav Rotemb0783502012-04-01 19:31:22 +00002547 AddToWorkList(Op.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002548 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
Craig Topper9c3da312012-04-09 07:19:09 +00002549 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
Nadav Rotemb0783502012-04-01 19:31:22 +00002550 }
2551 }
Craig Topper9c3da312012-04-09 07:19:09 +00002552
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002553 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002554}
2555
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002556SDValue DAGCombiner::visitAND(SDNode *N) {
2557 SDValue N0 = N->getOperand(0);
2558 SDValue N1 = N->getOperand(1);
2559 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002560 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2561 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002562 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002563 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002564
Dan Gohmana8665142007-06-25 16:23:39 +00002565 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002566 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002567 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002568 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002569
2570 // fold (and x, 0) -> 0, vector edition
2571 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2572 return N0;
2573 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2574 return N1;
2575
2576 // fold (and x, -1) -> x, vector edition
2577 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2578 return N1;
2579 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2580 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002581 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002582
Dan Gohman06563a82007-07-03 14:03:57 +00002583 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002584 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002585 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002586 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002587 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002588 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002589 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002590 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002591 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002592 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002593 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002594 return N0;
2595 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002596 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002597 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002598 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002599 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002600 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002601 if (RAND.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00002602 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002603 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002604 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002605 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002606 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002607 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002608 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2609 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002610 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002611 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002612 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002613 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002614 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002615 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002616
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002617 // Replace uses of the AND with uses of the Zero extend node.
2618 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002619
Chris Lattner49beaf42006-02-02 07:17:31 +00002620 // We actually want to replace all uses of the any_extend with the
2621 // zero_extend, to avoid duplicating things. This will later cause this
2622 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002623 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002624 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002625 }
2626 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002627 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002628 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2629 // already be zero by virtue of the width of the base type of the load.
2630 //
2631 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2632 // more cases.
2633 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2634 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2635 N0.getOpcode() == ISD::LOAD) {
2636 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2637 N0 : N0.getOperand(0) );
2638
2639 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2640 // This can be a pure constant or a vector splat, in which case we treat the
2641 // vector as a scalar and use the splat value.
2642 APInt Constant = APInt::getNullValue(1);
2643 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2644 Constant = C->getAPIntValue();
2645 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2646 APInt SplatValue, SplatUndef;
2647 unsigned SplatBitSize;
2648 bool HasAnyUndefs;
2649 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2650 SplatBitSize, HasAnyUndefs);
2651 if (IsSplat) {
2652 // Undef bits can contribute to a possible optimisation if set, so
2653 // set them.
2654 SplatValue |= SplatUndef;
2655
2656 // The splat value may be something like "0x00FFFFFF", which means 0 for
2657 // the first vector value and FF for the rest, repeating. We need a mask
2658 // that will apply equally to all members of the vector, so AND all the
2659 // lanes of the constant together.
2660 EVT VT = Vector->getValueType(0);
2661 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002662
2663 // If the splat value has been compressed to a bitlength lower
2664 // than the size of the vector lane, we need to re-expand it to
2665 // the lane size.
2666 if (BitWidth > SplatBitSize)
2667 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2668 SplatBitSize < BitWidth;
2669 SplatBitSize = SplatBitSize * 2)
2670 SplatValue |= SplatValue.shl(SplatBitSize);
2671
James Molloy862fe492012-02-20 12:02:38 +00002672 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002673 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002674 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2675 }
2676 }
2677
2678 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2679 // actually legal and isn't going to get expanded, else this is a false
2680 // optimisation.
2681 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2682 Load->getMemoryVT());
2683
2684 // Resize the constant to the same size as the original memory access before
2685 // extension. If it is still the AllOnesValue then this AND is completely
2686 // unneeded.
2687 Constant =
2688 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2689
2690 bool B;
2691 switch (Load->getExtensionType()) {
2692 default: B = false; break;
2693 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2694 case ISD::ZEXTLOAD:
2695 case ISD::NON_EXTLOAD: B = true; break;
2696 }
2697
2698 if (B && Constant.isAllOnesValue()) {
2699 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2700 // preserve semantics once we get rid of the AND.
2701 SDValue NewLoad(Load, 0);
2702 if (Load->getExtensionType() == ISD::EXTLOAD) {
2703 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002704 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002705 Load->getChain(), Load->getBasePtr(),
2706 Load->getOffset(), Load->getMemoryVT(),
2707 Load->getMemOperand());
2708 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002709 if (Load->getNumValues() == 3) {
2710 // PRE/POST_INC loads have 3 values.
2711 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2712 NewLoad.getValue(2) };
2713 CombineTo(Load, To, 3, true);
2714 } else {
2715 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2716 }
James Molloy862fe492012-02-20 12:02:38 +00002717 }
2718
2719 // Fold the AND away, taking care not to fold to the old load node if we
2720 // replaced it.
2721 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2722
2723 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2724 }
2725 }
Nate Begeman049b7482005-09-09 19:49:52 +00002726 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2727 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2728 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2729 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002730
Nate Begeman049b7482005-09-09 19:49:52 +00002731 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002732 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002733 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002734 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002735 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002736 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002737 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002738 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002739 }
Bill Wendling86171912009-01-30 20:43:18 +00002740 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002741 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002742 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002743 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002744 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002745 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002746 }
Bill Wendling86171912009-01-30 20:43:18 +00002747 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002748 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002749 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002750 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002751 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002752 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002753 }
2754 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002755 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2756 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2757 Op0 == Op1 && LL.getValueType().isInteger() &&
2758 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2759 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2760 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2761 cast<ConstantSDNode>(RR)->isNullValue()))) {
2762 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2763 LL, DAG.getConstant(1, LL.getValueType()));
2764 AddToWorkList(ADDNode.getNode());
2765 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2766 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2767 }
Nate Begeman049b7482005-09-09 19:49:52 +00002768 // canonicalize equivalent to ll == rl
2769 if (LL == RR && LR == RL) {
2770 Op1 = ISD::getSetCCSwappedOperands(Op1);
2771 std::swap(RL, RR);
2772 }
2773 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002774 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002775 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002776 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002777 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002778 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2779 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002780 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002781 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002782 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002783 }
2784 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002785
Bill Wendling86171912009-01-30 20:43:18 +00002786 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002787 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002788 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002789 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002790 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002791
Nate Begemandc7bba92006-02-03 22:24:05 +00002792 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2793 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002794 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002795 SimplifyDemandedBits(SDValue(N, 0)))
2796 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002797
Nate Begeman02b23c62005-10-13 03:11:28 +00002798 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002799 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002800 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002801 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002802 // If we zero all the possible extended bits, then we can turn this into
2803 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002804 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002805 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002806 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002807 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002808 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002809 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002810 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002811 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002812 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002813 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002814 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002815 }
2816 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002817 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002818 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002819 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002820 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002821 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002822 // If we zero all the possible extended bits, then we can turn this into
2823 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002824 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002825 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002826 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002827 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002828 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002829 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002830 LN0->getChain(), LN0->getBasePtr(),
2831 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002832 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002833 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002834 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002835 }
2836 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002837
Chris Lattnerf0032b32006-02-28 06:49:37 +00002838 // fold (and (load x), 255) -> (zextload x, i8)
2839 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002840 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2841 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2842 (N0.getOpcode() == ISD::ANY_EXTEND &&
2843 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2844 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2845 LoadSDNode *LN0 = HasAnyExt
2846 ? cast<LoadSDNode>(N0.getOperand(0))
2847 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002848 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002849 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002850 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002851 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2852 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2853 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002854
Evan Cheng166a4e62010-01-06 19:38:29 +00002855 if (ExtVT == LoadedVT &&
2856 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002857 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002858
2859 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002860 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002861 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2862 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002863 AddToWorkList(N);
2864 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2865 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2866 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002867
Chris Lattner88de3842010-01-07 21:53:27 +00002868 // Do not change the width of a volatile load.
2869 // Do not generate loads of non-round integer types since these can
2870 // be expensive (and would be wrong if the type is not byte sized).
2871 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2872 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2873 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002874
Chris Lattner88de3842010-01-07 21:53:27 +00002875 unsigned Alignment = LN0->getAlignment();
2876 SDValue NewPtr = LN0->getBasePtr();
2877
2878 // For big endian targets, we need to add an offset to the pointer
2879 // to load the correct bytes. For little endian systems, we merely
2880 // need to read fewer bytes from the same pointer.
2881 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002882 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2883 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2884 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002885 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002886 NewPtr, DAG.getConstant(PtrOff, PtrType));
2887 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002888 }
Chris Lattner88de3842010-01-07 21:53:27 +00002889
2890 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002891
Chris Lattner88de3842010-01-07 21:53:27 +00002892 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2893 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002894 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002895 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002896 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002897 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002898 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002899 AddToWorkList(N);
2900 CombineTo(LN0, Load, Load.getValue(1));
2901 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002902 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002903 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002904 }
2905 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002906
Evan Chenge6a3b032012-07-17 18:54:11 +00002907 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2908 VT.getSizeInBits() <= 64) {
2909 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2910 APInt ADDC = ADDI->getAPIntValue();
2911 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2912 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2913 // immediate for an add, but it is legal if its top c2 bits are set,
2914 // transform the ADD so the immediate doesn't need to be materialized
2915 // in a register.
2916 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2917 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2918 SRLI->getZExtValue());
2919 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2920 ADDC |= Mask;
2921 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2922 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002923 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002924 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2925 CombineTo(N0.getNode(), NewAdd);
2926 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2927 }
2928 }
2929 }
2930 }
2931 }
2932 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002933
Tim Northover819bfb52013-08-27 13:46:45 +00002934 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2935 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2936 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2937 N0.getOperand(1), false);
2938 if (BSwap.getNode())
2939 return BSwap;
2940 }
2941
Evan Chengf1005572010-04-28 07:10:39 +00002942 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002943}
2944
Evan Cheng4c0bd962011-06-21 06:01:08 +00002945/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2946///
2947SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2948 bool DemandHighBits) {
2949 if (!LegalOperations)
2950 return SDValue();
2951
2952 EVT VT = N->getValueType(0);
2953 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2954 return SDValue();
2955 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2956 return SDValue();
2957
2958 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2959 bool LookPassAnd0 = false;
2960 bool LookPassAnd1 = false;
2961 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2962 std::swap(N0, N1);
2963 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2964 std::swap(N0, N1);
2965 if (N0.getOpcode() == ISD::AND) {
2966 if (!N0.getNode()->hasOneUse())
2967 return SDValue();
2968 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2969 if (!N01C || N01C->getZExtValue() != 0xFF00)
2970 return SDValue();
2971 N0 = N0.getOperand(0);
2972 LookPassAnd0 = true;
2973 }
2974
2975 if (N1.getOpcode() == ISD::AND) {
2976 if (!N1.getNode()->hasOneUse())
2977 return SDValue();
2978 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2979 if (!N11C || N11C->getZExtValue() != 0xFF)
2980 return SDValue();
2981 N1 = N1.getOperand(0);
2982 LookPassAnd1 = true;
2983 }
2984
2985 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2986 std::swap(N0, N1);
2987 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2988 return SDValue();
2989 if (!N0.getNode()->hasOneUse() ||
2990 !N1.getNode()->hasOneUse())
2991 return SDValue();
2992
2993 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2994 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2995 if (!N01C || !N11C)
2996 return SDValue();
2997 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2998 return SDValue();
2999
3000 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3001 SDValue N00 = N0->getOperand(0);
3002 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3003 if (!N00.getNode()->hasOneUse())
3004 return SDValue();
3005 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3006 if (!N001C || N001C->getZExtValue() != 0xFF)
3007 return SDValue();
3008 N00 = N00.getOperand(0);
3009 LookPassAnd0 = true;
3010 }
3011
3012 SDValue N10 = N1->getOperand(0);
3013 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3014 if (!N10.getNode()->hasOneUse())
3015 return SDValue();
3016 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3017 if (!N101C || N101C->getZExtValue() != 0xFF00)
3018 return SDValue();
3019 N10 = N10.getOperand(0);
3020 LookPassAnd1 = true;
3021 }
3022
3023 if (N00 != N10)
3024 return SDValue();
3025
Tim Northover819bfb52013-08-27 13:46:45 +00003026 // Make sure everything beyond the low halfword gets set to zero since the SRL
3027 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003028 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003029 if (DemandHighBits && OpSizeInBits > 16) {
3030 // If the left-shift isn't masked out then the only way this is a bswap is
3031 // if all bits beyond the low 8 are 0. In that case the entire pattern
3032 // reduces to a left shift anyway: leave it for other parts of the combiner.
3033 if (!LookPassAnd0)
3034 return SDValue();
3035
3036 // However, if the right shift isn't masked out then it might be because
3037 // it's not needed. See if we can spot that too.
3038 if (!LookPassAnd1 &&
3039 !DAG.MaskedValueIsZero(
3040 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3041 return SDValue();
3042 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003043
Andrew Trickef9de2a2013-05-25 02:42:55 +00003044 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003045 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003046 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003047 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3048 return Res;
3049}
3050
3051/// isBSwapHWordElement - Return true if the specified node is an element
3052/// that makes up a 32-bit packed halfword byteswap. i.e.
3053/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003054static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003055 if (!N.getNode()->hasOneUse())
3056 return false;
3057
3058 unsigned Opc = N.getOpcode();
3059 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3060 return false;
3061
3062 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3063 if (!N1C)
3064 return false;
3065
3066 unsigned Num;
3067 switch (N1C->getZExtValue()) {
3068 default:
3069 return false;
3070 case 0xFF: Num = 0; break;
3071 case 0xFF00: Num = 1; break;
3072 case 0xFF0000: Num = 2; break;
3073 case 0xFF000000: Num = 3; break;
3074 }
3075
3076 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3077 SDValue N0 = N.getOperand(0);
3078 if (Opc == ISD::AND) {
3079 if (Num == 0 || Num == 2) {
3080 // (x >> 8) & 0xff
3081 // (x >> 8) & 0xff0000
3082 if (N0.getOpcode() != ISD::SRL)
3083 return false;
3084 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3085 if (!C || C->getZExtValue() != 8)
3086 return false;
3087 } else {
3088 // (x << 8) & 0xff00
3089 // (x << 8) & 0xff000000
3090 if (N0.getOpcode() != ISD::SHL)
3091 return false;
3092 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3093 if (!C || C->getZExtValue() != 8)
3094 return false;
3095 }
3096 } else if (Opc == ISD::SHL) {
3097 // (x & 0xff) << 8
3098 // (x & 0xff0000) << 8
3099 if (Num != 0 && Num != 2)
3100 return false;
3101 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3102 if (!C || C->getZExtValue() != 8)
3103 return false;
3104 } else { // Opc == ISD::SRL
3105 // (x & 0xff00) >> 8
3106 // (x & 0xff000000) >> 8
3107 if (Num != 1 && Num != 3)
3108 return false;
3109 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3110 if (!C || C->getZExtValue() != 8)
3111 return false;
3112 }
3113
3114 if (Parts[Num])
3115 return false;
3116
3117 Parts[Num] = N0.getOperand(0).getNode();
3118 return true;
3119}
3120
3121/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3122/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3123/// => (rotl (bswap x), 16)
3124SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3125 if (!LegalOperations)
3126 return SDValue();
3127
3128 EVT VT = N->getValueType(0);
3129 if (VT != MVT::i32)
3130 return SDValue();
3131 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3132 return SDValue();
3133
3134 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3135 // Look for either
3136 // (or (or (and), (and)), (or (and), (and)))
3137 // (or (or (or (and), (and)), (and)), (and))
3138 if (N0.getOpcode() != ISD::OR)
3139 return SDValue();
3140 SDValue N00 = N0.getOperand(0);
3141 SDValue N01 = N0.getOperand(1);
3142
Evan Chengbf0baa92012-12-13 01:34:32 +00003143 if (N1.getOpcode() == ISD::OR &&
3144 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003145 // (or (or (and), (and)), (or (and), (and)))
3146 SDValue N000 = N00.getOperand(0);
3147 if (!isBSwapHWordElement(N000, Parts))
3148 return SDValue();
3149
3150 SDValue N001 = N00.getOperand(1);
3151 if (!isBSwapHWordElement(N001, Parts))
3152 return SDValue();
3153 SDValue N010 = N01.getOperand(0);
3154 if (!isBSwapHWordElement(N010, Parts))
3155 return SDValue();
3156 SDValue N011 = N01.getOperand(1);
3157 if (!isBSwapHWordElement(N011, Parts))
3158 return SDValue();
3159 } else {
3160 // (or (or (or (and), (and)), (and)), (and))
3161 if (!isBSwapHWordElement(N1, Parts))
3162 return SDValue();
3163 if (!isBSwapHWordElement(N01, Parts))
3164 return SDValue();
3165 if (N00.getOpcode() != ISD::OR)
3166 return SDValue();
3167 SDValue N000 = N00.getOperand(0);
3168 if (!isBSwapHWordElement(N000, Parts))
3169 return SDValue();
3170 SDValue N001 = N00.getOperand(1);
3171 if (!isBSwapHWordElement(N001, Parts))
3172 return SDValue();
3173 }
3174
3175 // Make sure the parts are all coming from the same node.
3176 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3177 return SDValue();
3178
Andrew Trickef9de2a2013-05-25 02:42:55 +00003179 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003180 SDValue(Parts[0],0));
3181
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003182 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003183 // do (x << 16) | (x >> 16).
3184 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3185 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003186 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003187 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003188 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3189 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3190 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3191 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003192}
3193
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003194SDValue DAGCombiner::visitOR(SDNode *N) {
3195 SDValue N0 = N->getOperand(0);
3196 SDValue N1 = N->getOperand(1);
3197 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003198 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3199 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003200 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003201
Dan Gohmana8665142007-06-25 16:23:39 +00003202 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003203 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003204 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003205 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003206
3207 // fold (or x, 0) -> x, vector edition
3208 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3209 return N1;
3210 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3211 return N0;
3212
3213 // fold (or x, -1) -> -1, vector edition
3214 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3215 return N0;
3216 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3217 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003218
3219 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3220 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3221 // Do this only if the resulting shuffle is legal.
3222 if (isa<ShuffleVectorSDNode>(N0) &&
3223 isa<ShuffleVectorSDNode>(N1) &&
3224 N0->getOperand(1) == N1->getOperand(1) &&
3225 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3226 bool CanFold = true;
3227 unsigned NumElts = VT.getVectorNumElements();
3228 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3229 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3230 // We construct two shuffle masks:
3231 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3232 // and N1 as the second operand.
3233 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3234 // and N0 as the second operand.
3235 // We do this because OR is commutable and therefore there might be
3236 // two ways to fold this node into a shuffle.
3237 SmallVector<int,4> Mask1;
3238 SmallVector<int,4> Mask2;
3239
3240 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3241 int M0 = SV0->getMaskElt(i);
3242 int M1 = SV1->getMaskElt(i);
3243
3244 // Both shuffle indexes are undef. Propagate Undef.
3245 if (M0 < 0 && M1 < 0) {
3246 Mask1.push_back(M0);
3247 Mask2.push_back(M0);
3248 continue;
3249 }
3250
3251 if (M0 < 0 || M1 < 0 ||
3252 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3253 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3254 CanFold = false;
3255 break;
3256 }
3257
3258 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3259 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3260 }
3261
3262 if (CanFold) {
3263 // Fold this sequence only if the resulting shuffle is 'legal'.
3264 if (TLI.isShuffleMaskLegal(Mask1, VT))
3265 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3266 N1->getOperand(0), &Mask1[0]);
3267 if (TLI.isShuffleMaskLegal(Mask2, VT))
3268 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3269 N0->getOperand(0), &Mask2[0]);
3270 }
3271 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003272 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003273
Dan Gohman06563a82007-07-03 14:03:57 +00003274 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003275 if (!LegalOperations &&
3276 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003277 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3278 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3279 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003280 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003281 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003282 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003283 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003284 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003285 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003286 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003287 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003288 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003289 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003290 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003291 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003292 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003293 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003294 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003295
3296 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3297 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3298 if (BSwap.getNode() != 0)
3299 return BSwap;
3300 BSwap = MatchBSwapHWordLow(N, N0, N1);
3301 if (BSwap.getNode() != 0)
3302 return BSwap;
3303
Nate Begeman22e251a2006-02-03 06:46:56 +00003304 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003305 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003306 if (ROR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003307 return ROR;
3308 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003309 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003310 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003311 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003312 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003313 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3314 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3315 if (!COR.getNode())
3316 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003317 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3318 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003319 N0.getOperand(0), N1), COR);
3320 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003321 }
Nate Begeman049b7482005-09-09 19:49:52 +00003322 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3323 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3324 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3325 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003326
Nate Begeman049b7482005-09-09 19:49:52 +00003327 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003328 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003329 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3330 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003331 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003332 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003333 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003334 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003335 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003336 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003337 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003338 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3339 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003340 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003341 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003342 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003343 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003344 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003345 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003346 }
3347 }
3348 // canonicalize equivalent to ll == rl
3349 if (LL == RR && LR == RL) {
3350 Op1 = ISD::getSetCCSwappedOperands(Op1);
3351 std::swap(RL, RR);
3352 }
3353 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003354 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003355 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003356 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003357 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003358 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3359 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003360 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003361 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003362 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003363 }
3364 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003365
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003366 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003367 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003368 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003369 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003370 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003371
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003372 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003373 if (N0.getOpcode() == ISD::AND &&
3374 N1.getOpcode() == ISD::AND &&
3375 N0.getOperand(1).getOpcode() == ISD::Constant &&
3376 N1.getOperand(1).getOpcode() == ISD::Constant &&
3377 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003378 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003379 // We can only do this xform if we know that bits from X that are set in C2
3380 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003381 const APInt &LHSMask =
3382 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3383 const APInt &RHSMask =
3384 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003385
Dan Gohman309d3d52007-06-22 14:59:07 +00003386 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3387 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003388 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003389 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003390 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003391 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003392 }
3393 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003394
Chris Lattner97614c82006-09-14 20:50:57 +00003395 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003396 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003397 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003398
Dan Gohman600f62b2010-06-24 14:30:44 +00003399 // Simplify the operands using demanded-bits information.
3400 if (!VT.isVector() &&
3401 SimplifyDemandedBits(SDValue(N, 0)))
3402 return SDValue(N, 0);
3403
Evan Chengf1005572010-04-28 07:10:39 +00003404 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003405}
3406
Chris Lattner97614c82006-09-14 20:50:57 +00003407/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003408static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003409 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003410 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003411 Mask = Op.getOperand(1);
3412 Op = Op.getOperand(0);
3413 } else {
3414 return false;
3415 }
3416 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003417
Chris Lattner97614c82006-09-14 20:50:57 +00003418 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3419 Shift = Op;
3420 return true;
3421 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003422
Scott Michelcf0da6c2009-02-17 22:15:04 +00003423 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003424}
3425
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003426// Return true if we can prove that, whenever Neg and Pos are both in the
3427// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003428// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3429//
3430// (or (shift1 X, Neg), (shift2 X, Pos))
3431//
Adam Nemetc6553a82014-03-07 23:56:24 +00003432// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3433// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3434// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003435static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003436 // If OpSize is a power of 2 then:
3437 //
3438 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3439 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3440 //
3441 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3442 // for the stronger condition:
3443 //
3444 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3445 //
3446 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3447 // we can just replace Neg with Neg' for the rest of the function.
3448 //
3449 // In other cases we check for the even stronger condition:
3450 //
3451 // Neg == OpSize - Pos [B]
3452 //
3453 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3454 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003455 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003456 // We could actually use [A] whenever OpSize is a power of 2, but the
3457 // only extra cases that it would match are those uninteresting ones
3458 // where Neg and Pos are never in range at the same time. E.g. for
3459 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3460 // as well as (sub 32, Pos), but:
3461 //
3462 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3463 //
3464 // always invokes undefined behavior for 32-bit X.
3465 //
3466 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003467 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003468 if (Neg.getOpcode() == ISD::AND &&
3469 isPowerOf2_64(OpSize) &&
3470 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3471 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3472 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003473 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003474 }
3475
Richard Sandiford0f264db2014-01-09 10:49:40 +00003476 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3477 if (Neg.getOpcode() != ISD::SUB)
3478 return 0;
3479 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3480 if (!NegC)
3481 return 0;
3482 SDValue NegOp1 = Neg.getOperand(1);
3483
Adam Nemet5117f5d2014-03-07 23:56:28 +00003484 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3485 // Pos'. The truncation is redundant for the purpose of the equality.
3486 if (MaskLoBits &&
3487 Pos.getOpcode() == ISD::AND &&
3488 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3489 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3490 Pos = Pos.getOperand(0);
3491
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003492 // The condition we need is now:
3493 //
3494 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3495 //
3496 // If NegOp1 == Pos then we need:
3497 //
3498 // OpSize & Mask == NegC & Mask
3499 //
3500 // (because "x & Mask" is a truncation and distributes through subtraction).
3501 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003502 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003503 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003504 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3505 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003506 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003507 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3508 //
3509 // which, again because "x & Mask" is a truncation, becomes:
3510 //
3511 // NegC & Mask == (OpSize - PosC) & Mask
3512 // OpSize & Mask == (NegC + PosC) & Mask
3513 else if (Pos.getOpcode() == ISD::ADD &&
3514 Pos.getOperand(0) == NegOp1 &&
3515 Pos.getOperand(1).getOpcode() == ISD::Constant)
3516 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3517 NegC->getAPIntValue());
3518 else
3519 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003520
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003521 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003522 if (MaskLoBits)
3523 // Opsize & Mask is 0 since Mask is Opsize - 1.
3524 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003525 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003526}
3527
Richard Sandiford95c864d2014-01-08 15:40:47 +00003528// A subroutine of MatchRotate used once we have found an OR of two opposite
3529// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3530// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3531// former being preferred if supported. InnerPos and InnerNeg are Pos and
3532// Neg with outer conversions stripped away.
3533SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3534 SDValue Neg, SDValue InnerPos,
3535 SDValue InnerNeg, unsigned PosOpcode,
3536 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003537 // fold (or (shl x, (*ext y)),
3538 // (srl x, (*ext (sub 32, y)))) ->
3539 // (rotl x, y) or (rotr x, (sub 32, y))
3540 //
3541 // fold (or (shl x, (*ext (sub 32, y))),
3542 // (srl x, (*ext y))) ->
3543 // (rotr x, y) or (rotl x, (sub 32, y))
3544 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003545 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003546 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3547 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3548 HasPos ? Pos : Neg).getNode();
3549 }
3550
3551 // fold (or (shl (*ext x), (*ext y)),
3552 // (srl (*ext x), (*ext (sub 32, y)))) ->
3553 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3554 //
3555 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3556 // (srl (*ext x), (*ext y))) ->
3557 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3558 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3559 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3560 SDValue InnerShifted = Shifted.getOperand(0);
3561 EVT InnerVT = InnerShifted.getValueType();
3562 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3563 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
Richard Sandiford0f264db2014-01-09 10:49:40 +00003564 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003565 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3566 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3567 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3568 }
3569 }
3570 }
3571
3572 return 0;
3573}
3574
Chris Lattner97614c82006-09-14 20:50:57 +00003575// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3576// idioms for rotate, and if the target supports rotation instructions, generate
3577// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003578SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003579 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003580 EVT VT = LHS.getValueType();
Chris Lattner97614c82006-09-14 20:50:57 +00003581 if (!TLI.isTypeLegal(VT)) return 0;
3582
3583 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003584 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3585 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Chris Lattner97614c82006-09-14 20:50:57 +00003586 if (!HasROTL && !HasROTR) return 0;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003587
Chris Lattner97614c82006-09-14 20:50:57 +00003588 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003589 SDValue LHSShift; // The shift.
3590 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003591 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3592 return 0; // Not part of a rotate.
3593
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003594 SDValue RHSShift; // The shift.
3595 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003596 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3597 return 0; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003598
Chris Lattner97614c82006-09-14 20:50:57 +00003599 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3600 return 0; // Not shifting the same value.
3601
3602 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3603 return 0; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003604
Chris Lattner97614c82006-09-14 20:50:57 +00003605 // Canonicalize shl to left side in a shl/srl pair.
3606 if (RHSShift.getOpcode() == ISD::SHL) {
3607 std::swap(LHS, RHS);
3608 std::swap(LHSShift, RHSShift);
3609 std::swap(LHSMask , RHSMask );
3610 }
3611
Duncan Sands13237ac2008-06-06 12:08:01 +00003612 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003613 SDValue LHSShiftArg = LHSShift.getOperand(0);
3614 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003615 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003616 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003617
3618 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3619 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003620 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3621 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003622 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3623 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003624 if ((LShVal + RShVal) != OpSizeInBits)
3625 return 0;
3626
Craig Topper65161fa2012-09-29 06:54:22 +00003627 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3628 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003629
Chris Lattner97614c82006-09-14 20:50:57 +00003630 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003631 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003632 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003633
Gabor Greiff304a7a2008-08-28 21:40:38 +00003634 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003635 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3636 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003637 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003638 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003639 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3640 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003641 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003642
Bill Wendling35972a92009-01-30 21:14:50 +00003643 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003644 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003645
Gabor Greiff304a7a2008-08-28 21:40:38 +00003646 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003647 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003648
Chris Lattner97614c82006-09-14 20:50:57 +00003649 // If there is a mask here, and we have a variable shift, we can't be sure
3650 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003651 if (LHSMask.getNode() || RHSMask.getNode())
Chris Lattner97614c82006-09-14 20:50:57 +00003652 return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003653
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003654 // If the shift amount is sign/zext/any-extended just peel it off.
3655 SDValue LExtOp0 = LHSShiftAmt;
3656 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003657 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3658 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3659 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3660 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3661 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3662 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3663 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3664 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003665 LExtOp0 = LHSShiftAmt.getOperand(0);
3666 RExtOp0 = RHSShiftAmt.getOperand(0);
3667 }
3668
Richard Sandiford95c864d2014-01-08 15:40:47 +00003669 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3670 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3671 if (TryL)
3672 return TryL;
3673
3674 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3675 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3676 if (TryR)
3677 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003678
Chris Lattner97614c82006-09-14 20:50:57 +00003679 return 0;
3680}
3681
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003682SDValue DAGCombiner::visitXOR(SDNode *N) {
3683 SDValue N0 = N->getOperand(0);
3684 SDValue N1 = N->getOperand(1);
3685 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003686 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3687 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003688 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003689
Dan Gohmana8665142007-06-25 16:23:39 +00003690 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003691 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003692 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003693 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003694
3695 // fold (xor x, 0) -> x, vector edition
3696 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3697 return N1;
3698 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3699 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003700 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003701
Evan Chengdf1690d2008-03-25 20:08:07 +00003702 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3703 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3704 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003705 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003706 if (N0.getOpcode() == ISD::UNDEF)
3707 return N0;
3708 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003709 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003710 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003711 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003712 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003713 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003714 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003715 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003716 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003717 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003718 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003719 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003720 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003721 if (RXOR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003722 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003723
Nate Begeman21158fc2005-09-01 00:19:25 +00003724 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003725 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003726 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003727 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3728 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003729
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003730 if (!LegalOperations ||
3731 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003732 switch (N0.getOpcode()) {
3733 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003734 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003735 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003736 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003737 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003738 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003739 N0.getOperand(3), NotCC);
3740 }
3741 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003742 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003743
Chris Lattner58c227b2007-09-10 21:39:07 +00003744 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003745 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003746 N0.getNode()->hasOneUse() &&
3747 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003748 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003749 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003750 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003751 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003752 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003753 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003754
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003755 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003756 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003757 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003758 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003759 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3760 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003761 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3762 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003763 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003764 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003765 }
3766 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003767 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003768 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003769 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003770 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003771 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3772 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003773 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3774 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003775 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003776 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003777 }
3778 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003779 // fold (xor (and x, y), y) -> (and (not x), y)
3780 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003781 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003782 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003783 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003784 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003785 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003786 }
Bill Wendling35972a92009-01-30 21:14:50 +00003787 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003788 if (N1C && N0.getOpcode() == ISD::XOR) {
3789 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3790 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3791 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003792 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003793 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003794 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003795 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003796 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003797 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003798 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003799 }
3800 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003801 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003802 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003803
Chris Lattner8d6fc202006-05-05 05:51:50 +00003804 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3805 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003806 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003807 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003808 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003809
Chris Lattner098c01e2006-04-08 04:15:24 +00003810 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003811 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003812 SimplifyDemandedBits(SDValue(N, 0)))
3813 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003814
Evan Chengf1005572010-04-28 07:10:39 +00003815 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003816}
3817
Chris Lattner7c709a52007-12-06 07:33:36 +00003818/// visitShiftByConstant - Handle transforms common to the three shifts, when
3819/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003820SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003821 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003822 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003823 return SDValue();
3824
Gabor Greiff304a7a2008-08-28 21:40:38 +00003825 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003826 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003827
Chris Lattner7c709a52007-12-06 07:33:36 +00003828 // We want to pull some binops through shifts, so that we have (and (shift))
3829 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3830 // thing happens with address calculations, so it's important to canonicalize
3831 // it.
3832 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003833
Chris Lattner7c709a52007-12-06 07:33:36 +00003834 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003835 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003836 case ISD::OR:
3837 case ISD::XOR:
3838 HighBitSet = false; // We can only transform sra if the high bit is clear.
3839 break;
3840 case ISD::AND:
3841 HighBitSet = true; // We can only transform sra if the high bit is set.
3842 break;
3843 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003844 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003845 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003846 HighBitSet = false; // We can only transform sra if the high bit is clear.
3847 break;
3848 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003849
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003850 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003851 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003852 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003853
3854 // FIXME: disable this unless the input to the binop is a shift by a constant.
3855 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003856 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003857 // void foo(int *X, int i) { X[i & 1235] = 1; }
3858 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003859 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003860 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003861 BinOpLHSVal->getOpcode() != ISD::SRA &&
3862 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3863 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003864 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003865
Owen Anderson53aa7a92009-08-10 22:56:29 +00003866 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003867
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003868 // If this is a signed shift right, and the high bit is modified by the
3869 // logical operation, do not perform the transformation. The highBitSet
3870 // boolean indicates the value of the high bit of the constant which would
3871 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003872 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003873 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3874 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003875 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003876 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003877
Chris Lattner7c709a52007-12-06 07:33:36 +00003878 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003879 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003880 N->getValueType(0),
3881 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003882 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003883
3884 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003885 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003886 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003887 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003888
3889 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003890 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003891}
3892
Adam Nemet67483892014-03-04 23:28:31 +00003893SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3894 assert(N->getOpcode() == ISD::TRUNCATE);
3895 assert(N->getOperand(0).getOpcode() == ISD::AND);
3896
3897 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3898 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3899 SDValue N01 = N->getOperand(0).getOperand(1);
3900
Matt Arsenault985b9de2014-03-17 18:58:01 +00003901 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003902 EVT TruncVT = N->getValueType(0);
3903 SDValue N00 = N->getOperand(0).getOperand(0);
3904 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003905 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003906
3907 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3908 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3909 DAG.getConstant(TruncC, TruncVT));
3910 }
3911 }
3912
3913 return SDValue();
3914}
Adam Nemet7f928f12014-03-07 23:56:30 +00003915
3916SDValue DAGCombiner::visitRotate(SDNode *N) {
3917 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3918 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3919 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3920 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3921 if (NewOp1.getNode())
3922 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3923 N->getOperand(0), NewOp1);
3924 }
3925 return SDValue();
3926}
3927
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003928SDValue DAGCombiner::visitSHL(SDNode *N) {
3929 SDValue N0 = N->getOperand(0);
3930 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003931 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3932 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003933 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003934 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003935
Daniel Sandersa1840d22013-11-11 17:23:41 +00003936 // fold vector ops
3937 if (VT.isVector()) {
3938 SDValue FoldedVOp = SimplifyVBinOp(N);
3939 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003940
3941 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3942 // If setcc produces all-one true value then:
3943 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003944 if (N1CV && N1CV->isConstant()) {
3945 if (N0.getOpcode() == ISD::AND &&
3946 TLI.getBooleanContents(true) ==
3947 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3948 SDValue N00 = N0->getOperand(0);
3949 SDValue N01 = N0->getOperand(1);
3950 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003951
Matt Arsenault985b9de2014-03-17 18:58:01 +00003952 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3953 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3954 if (C.getNode())
3955 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3956 }
3957 } else {
3958 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003959 }
3960 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003961 }
3962
Nate Begeman21158fc2005-09-01 00:19:25 +00003963 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003964 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003965 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003966 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003967 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003968 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003969 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003970 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003971 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003972 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003973 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003974 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003975 // fold (shl undef, x) -> 0
3976 if (N0.getOpcode() == ISD::UNDEF)
3977 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003978 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003979 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003980 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003981 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003982 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003983 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00003984 N1.getOperand(0).getOpcode() == ISD::AND) {
3985 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3986 if (NewOp1.getNode())
3987 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003988 }
3989
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003990 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3991 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003992
3993 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00003994 if (N1C && N0.getOpcode() == ISD::SHL) {
3995 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3996 uint64_t c1 = N0C1->getZExtValue();
3997 uint64_t c2 = N1C->getZExtValue();
3998 if (c1 + c2 >= OpSizeInBits)
3999 return DAG.getConstant(0, VT);
4000 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4001 DAG.getConstant(c1 + c2, N1.getValueType()));
4002 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004003 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004004
4005 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4006 // For this to be valid, the second form must not preserve any of the bits
4007 // that are shifted out by the inner shift in the first form. This means
4008 // the outer shift size must be >= the number of bits added by the ext.
4009 // As a corollary, we don't care what kind of ext it is.
4010 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4011 N0.getOpcode() == ISD::ANY_EXTEND ||
4012 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004013 N0.getOperand(0).getOpcode() == ISD::SHL) {
4014 SDValue N0Op0 = N0.getOperand(0);
4015 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4016 uint64_t c1 = N0Op0C1->getZExtValue();
4017 uint64_t c2 = N1C->getZExtValue();
4018 EVT InnerShiftVT = N0Op0.getValueType();
4019 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4020 if (c2 >= OpSizeInBits - InnerShiftSize) {
4021 if (c1 + c2 >= OpSizeInBits)
4022 return DAG.getConstant(0, VT);
4023 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4024 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4025 N0Op0->getOperand(0)),
4026 DAG.getConstant(c1 + c2, N1.getValueType()));
4027 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004028 }
4029 }
4030
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004031 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4032 // Only fold this if the inner zext has no other uses to avoid increasing
4033 // the total number of instructions.
4034 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004035 N0.getOperand(0).getOpcode() == ISD::SRL) {
4036 SDValue N0Op0 = N0.getOperand(0);
4037 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4038 uint64_t c1 = N0Op0C1->getZExtValue();
4039 if (c1 < VT.getScalarSizeInBits()) {
4040 uint64_t c2 = N1C->getZExtValue();
4041 if (c1 == c2) {
4042 SDValue NewOp0 = N0.getOperand(0);
4043 EVT CountVT = NewOp0.getOperand(1).getValueType();
4044 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4045 NewOp0, DAG.getConstant(c2, CountVT));
4046 AddToWorkList(NewSHL.getNode());
4047 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4048 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004049 }
4050 }
4051 }
4052
Eli Friedman1877ac92011-06-09 22:14:44 +00004053 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4054 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004055 // Only fold this if the inner shift has no other uses -- if it does, folding
4056 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004057 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4058 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4059 uint64_t c1 = N0C1->getZExtValue();
4060 if (c1 < OpSizeInBits) {
4061 uint64_t c2 = N1C->getZExtValue();
4062 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4063 SDValue Shift;
4064 if (c2 > c1) {
4065 Mask = Mask.shl(c2 - c1);
4066 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4067 DAG.getConstant(c2 - c1, N1.getValueType()));
4068 } else {
4069 Mask = Mask.lshr(c1 - c2);
4070 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4071 DAG.getConstant(c1 - c2, N1.getValueType()));
4072 }
4073 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4074 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004075 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004076 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004077 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004078 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004079 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004080 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004081 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004082 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4083 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004084 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004085 HiBitsMask);
4086 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004087
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004088 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004089 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004090 if (NewSHL.getNode())
4091 return NewSHL;
4092 }
4093
Evan Chengf1005572010-04-28 07:10:39 +00004094 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004095}
4096
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004097SDValue DAGCombiner::visitSRA(SDNode *N) {
4098 SDValue N0 = N->getOperand(0);
4099 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004100 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4101 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004102 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004103 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004104
Daniel Sandersa1840d22013-11-11 17:23:41 +00004105 // fold vector ops
4106 if (VT.isVector()) {
4107 SDValue FoldedVOp = SimplifyVBinOp(N);
4108 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004109
4110 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004111 }
4112
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004113 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004114 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004115 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004116 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004117 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004118 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004119 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004120 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004121 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004122 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004123 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004124 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004125 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004126 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004127 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004128 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4129 // sext_inreg.
4130 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004131 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004132 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4133 if (VT.isVector())
4134 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4135 ExtVT, VT.getVectorNumElements());
4136 if ((!LegalOperations ||
4137 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004138 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004139 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004140 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004141
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004142 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004143 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004144 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004145 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004146 if (Sum >= OpSizeInBits)
4147 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004148 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004149 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004150 }
4151 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004152
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004153 // fold (sra (shl X, m), (sub result_size, n))
4154 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004155 // result_size - n != m.
4156 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004157 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004158 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004159 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004160 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4161 if (N01C) {
4162 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004163 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004164 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4165
4166 if (VT.isVector())
4167 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4168
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004169 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004170 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004171
Scott Michelcf0da6c2009-02-17 22:15:04 +00004172 // If the shift is not a no-op (in which case this should be just a sign
4173 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004174 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004175 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004176 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004177 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4178 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004179 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004180
Owen Andersonb2c80da2011-02-25 21:41:48 +00004181 SDValue Amt = DAG.getConstant(ShiftAmt,
4182 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004183 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004184 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004185 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004186 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004187 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004188 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004189 }
4190 }
4191 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004192
Duncan Sands3ed76882009-02-01 18:06:53 +00004193 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004194 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004195 N1.getOperand(0).getOpcode() == ISD::AND) {
4196 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4197 if (NewOp1.getNode())
4198 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004199 }
4200
Matt Arsenault985b9de2014-03-17 18:58:01 +00004201 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004202 // if c1 is equal to the number of bits the trunc removes
4203 if (N0.getOpcode() == ISD::TRUNCATE &&
4204 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4205 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4206 N0.getOperand(0).hasOneUse() &&
4207 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004208 N1C) {
4209 SDValue N0Op0 = N0.getOperand(0);
4210 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4211 unsigned LargeShiftVal = LargeShift->getZExtValue();
4212 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004213
Matt Arsenault985b9de2014-03-17 18:58:01 +00004214 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4215 SDValue Amt =
4216 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4217 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4218 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4219 N0Op0.getOperand(0), Amt);
4220 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4221 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004222 }
4223 }
4224
Scott Michelcf0da6c2009-02-17 22:15:04 +00004225 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004226 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4227 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004228
4229
Nate Begeman21158fc2005-09-01 00:19:25 +00004230 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004231 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004232 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004233
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004234 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004235 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004236 if (NewSRA.getNode())
4237 return NewSRA;
4238 }
4239
Evan Chengf1005572010-04-28 07:10:39 +00004240 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004241}
4242
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004243SDValue DAGCombiner::visitSRL(SDNode *N) {
4244 SDValue N0 = N->getOperand(0);
4245 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004246 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4247 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004248 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004249 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004250
Daniel Sandersa1840d22013-11-11 17:23:41 +00004251 // fold vector ops
4252 if (VT.isVector()) {
4253 SDValue FoldedVOp = SimplifyVBinOp(N);
4254 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004255
4256 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004257 }
4258
Nate Begeman21158fc2005-09-01 00:19:25 +00004259 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004260 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004261 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004262 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004263 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004264 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004265 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004266 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004267 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004268 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004269 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004270 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004271 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004272 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004273 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004274 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004275
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004276 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004277 if (N1C && N0.getOpcode() == ISD::SRL) {
4278 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4279 uint64_t c1 = N01C->getZExtValue();
4280 uint64_t c2 = N1C->getZExtValue();
4281 if (c1 + c2 >= OpSizeInBits)
4282 return DAG.getConstant(0, VT);
4283 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4284 DAG.getConstant(c1 + c2, N1.getValueType()));
4285 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004286 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004287
Dale Johannesencd538af2010-12-17 21:45:49 +00004288 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004289 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4290 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004291 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004292 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004293 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4294 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004295 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4296 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004297 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004298 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004299 if (c1 + OpSizeInBits == InnerShiftSize) {
4300 if (c1 + c2 >= InnerShiftSize)
4301 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004302 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4303 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004304 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004305 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004306 }
4307 }
4308
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004309 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004310 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4311 unsigned BitSize = N0.getScalarValueSizeInBits();
4312 if (BitSize <= 64) {
4313 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4314 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4315 DAG.getConstant(~0ULL >> ShAmt, VT));
4316 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004317 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004318
Michael Liao62ebfd82013-06-21 18:45:27 +00004319 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004320 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4321 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004322 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004323 unsigned BitSize = SmallVT.getScalarSizeInBits();
4324 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004325 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004326
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004327 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004328 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004329 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004330 N0.getOperand(0),
4331 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004332 AddToWorkList(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004333 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004334 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4335 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4336 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004337 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004338 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004339
Chris Lattner2e33fb42006-10-12 20:23:19 +00004340 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4341 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004342 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004343 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004344 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004345 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004346
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004347 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004348 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004349 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004350 APInt KnownZero, KnownOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004351 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004352
Chris Lattner49932492006-04-02 06:11:11 +00004353 // If any of the input bits are KnownOne, then the input couldn't be all
4354 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004355 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004356
Chris Lattner49932492006-04-02 06:11:11 +00004357 // If all of the bits input the to ctlz node are known to be zero, then
4358 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004359 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004360 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004361
Chris Lattner49932492006-04-02 06:11:11 +00004362 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004363 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004364 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004365 // could be set on input to the CTLZ node. If this bit is set, the SRL
4366 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4367 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004368 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004369 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004370
Chris Lattner49932492006-04-02 06:11:11 +00004371 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004372 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004373 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004374 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004375 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004376
Andrew Trickef9de2a2013-05-25 02:42:55 +00004377 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004378 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004379 }
4380 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004381
Duncan Sands3ed76882009-02-01 18:06:53 +00004382 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004383 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004384 N1.getOperand(0).getOpcode() == ISD::AND) {
4385 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4386 if (NewOp1.getNode())
4387 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004388 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004389
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004390 // fold operands of srl based on knowledge that the low bits are not
4391 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004392 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4393 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004394
Evan Chengb175de62009-12-18 21:31:31 +00004395 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004396 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004397 if (NewSRL.getNode())
4398 return NewSRL;
4399 }
4400
Dan Gohman600f62b2010-06-24 14:30:44 +00004401 // Attempt to convert a srl of a load into a narrower zero-extending load.
4402 SDValue NarrowLoad = ReduceLoadWidth(N);
4403 if (NarrowLoad.getNode())
4404 return NarrowLoad;
4405
Evan Chengb175de62009-12-18 21:31:31 +00004406 // Here is a common situation. We want to optimize:
4407 //
4408 // %a = ...
4409 // %b = and i32 %a, 2
4410 // %c = srl i32 %b, 1
4411 // brcond i32 %c ...
4412 //
4413 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004414 //
Evan Chengb175de62009-12-18 21:31:31 +00004415 // %a = ...
4416 // %b = and %a, 2
4417 // %c = setcc eq %b, 0
4418 // brcond %c ...
4419 //
4420 // However when after the source operand of SRL is optimized into AND, the SRL
4421 // itself may not be optimized further. Look for it and add the BRCOND into
4422 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004423 if (N->hasOneUse()) {
4424 SDNode *Use = *N->use_begin();
4425 if (Use->getOpcode() == ISD::BRCOND)
4426 AddToWorkList(Use);
4427 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4428 // Also look pass the truncate.
4429 Use = *Use->use_begin();
4430 if (Use->getOpcode() == ISD::BRCOND)
4431 AddToWorkList(Use);
4432 }
4433 }
Evan Chengb175de62009-12-18 21:31:31 +00004434
Evan Chengf1005572010-04-28 07:10:39 +00004435 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004436}
4437
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004438SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4439 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004440 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004441
4442 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004443 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004444 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004445 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004446}
4447
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004448SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4449 SDValue N0 = N->getOperand(0);
4450 EVT VT = N->getValueType(0);
4451
4452 // fold (ctlz_zero_undef c1) -> c2
4453 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004454 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004455 return SDValue();
4456}
4457
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004458SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4459 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004460 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004461
Nate Begeman21158fc2005-09-01 00:19:25 +00004462 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004463 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004464 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004465 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004466}
4467
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004468SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4469 SDValue N0 = N->getOperand(0);
4470 EVT VT = N->getValueType(0);
4471
4472 // fold (cttz_zero_undef c1) -> c2
4473 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004474 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004475 return SDValue();
4476}
4477
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004478SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4479 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004480 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004481
Nate Begeman21158fc2005-09-01 00:19:25 +00004482 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004483 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004484 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004485 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004486}
4487
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004488SDValue DAGCombiner::visitSELECT(SDNode *N) {
4489 SDValue N0 = N->getOperand(0);
4490 SDValue N1 = N->getOperand(1);
4491 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004492 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4494 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004495 EVT VT = N->getValueType(0);
4496 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004497
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004498 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004499 if (N1 == N2)
4500 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004501 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004502 if (N0C && !N0C->isNullValue())
4503 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004504 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004505 if (N0C && N0C->isNullValue())
4506 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004507 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004508 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004509 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004510 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004511 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004512 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004513 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004514 TLI.getBooleanContents(false) ==
4515 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004516 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004517 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004518 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004519 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004520 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004521 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004522 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004523 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004524 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004525 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4526 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004527 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004528 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004529 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004530 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004531 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004532 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004533 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004534 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004535 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004536 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004537 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004538 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004539 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004540 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004541 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004542 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004543 // fold (select X, X, Y) -> (or X, Y)
4544 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004545 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004546 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004547 // fold (select X, Y, X) -> (and X, Y)
4548 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004549 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004550 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004551
Chris Lattner6c14c352005-10-18 06:04:22 +00004552 // If we can fold this based on the true/false value, do so.
4553 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004554 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004555
Nate Begemanc760f802005-09-19 22:34:01 +00004556 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004557 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004558 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004559 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004560 // having to say they don't support SELECT_CC on every type the DAG knows
4561 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004562 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004563 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004564 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004565 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004566 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004567 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004568 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004569
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004570 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004571}
4572
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004573static
4574std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4575 SDLoc DL(N);
4576 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004577 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004578
4579 // Split the inputs.
4580 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004581 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4582 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004583
4584 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4585 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4586
4587 return std::make_pair(Lo, Hi);
4588}
4589
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004590SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4591 SDValue N0 = N->getOperand(0);
4592 SDValue N1 = N->getOperand(1);
4593 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004594 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004595
4596 // Canonicalize integer abs.
4597 // vselect (setg[te] X, 0), X, -X ->
4598 // vselect (setgt X, -1), X, -X ->
4599 // vselect (setl[te] X, 0), -X, X ->
4600 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4601 if (N0.getOpcode() == ISD::SETCC) {
4602 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4603 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4604 bool isAbs = false;
4605 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4606
4607 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4608 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4609 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4610 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4611 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4612 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4613 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4614
4615 if (isAbs) {
4616 EVT VT = LHS.getValueType();
4617 SDValue Shift = DAG.getNode(
4618 ISD::SRA, DL, VT, LHS,
4619 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4620 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4621 AddToWorkList(Shift.getNode());
4622 AddToWorkList(Add.getNode());
4623 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4624 }
4625 }
4626
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004627 // If the VSELECT result requires splitting and the mask is provided by a
4628 // SETCC, then split both nodes and its operands before legalization. This
4629 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4630 // and enables future optimizations (e.g. min/max pattern matching on X86).
4631 if (N0.getOpcode() == ISD::SETCC) {
4632 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004633
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004634 // Check if any splitting is required.
4635 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4636 TargetLowering::TypeSplitVector)
4637 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004638
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004639 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004640 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4641 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4642 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004643
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004644 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4645 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004646
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004647 // Add the new VSELECT nodes to the work list in case they need to be split
4648 // again.
4649 AddToWorkList(Lo.getNode());
4650 AddToWorkList(Hi.getNode());
4651
4652 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004653 }
4654
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004655 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4656 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4657 return N1;
4658 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4659 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4660 return N2;
4661
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004662 return SDValue();
4663}
4664
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004665SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4666 SDValue N0 = N->getOperand(0);
4667 SDValue N1 = N->getOperand(1);
4668 SDValue N2 = N->getOperand(2);
4669 SDValue N3 = N->getOperand(3);
4670 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004671 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004672
Nate Begemanc760f802005-09-19 22:34:01 +00004673 // fold select_cc lhs, rhs, x, x, cc -> x
4674 if (N2 == N3)
4675 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004676
Chris Lattner8b68dec2006-09-20 06:19:26 +00004677 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004678 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004679 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004680 if (SCC.getNode()) {
4681 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004682
Stephen Lin605207f2013-06-15 04:03:33 +00004683 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4684 if (!SCCC->isNullValue())
4685 return N2; // cond always true -> true val
4686 else
4687 return N3; // cond always false -> false val
4688 }
4689
4690 // Fold to a simpler select_cc
4691 if (SCC.getOpcode() == ISD::SETCC)
4692 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4693 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4694 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004695 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004696
Chris Lattner6c14c352005-10-18 06:04:22 +00004697 // If we can fold this based on the true/false value, do so.
4698 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004699 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004700
Nate Begemanc760f802005-09-19 22:34:01 +00004701 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004702 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004703}
4704
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004705SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004706 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004707 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004708 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004709}
4710
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004711// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4712// dag node into a ConstantSDNode or a build_vector of constants.
4713// This function is called by the DAGCombiner when visiting sext/zext/aext
4714// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4715// Vector extends are not folded if operations are legal; this is to
4716// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004717static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4718 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004719 bool LegalOperations) {
4720 unsigned Opcode = N->getOpcode();
4721 SDValue N0 = N->getOperand(0);
4722 EVT VT = N->getValueType(0);
4723
4724 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4725 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4726
4727 // fold (sext c1) -> c1
4728 // fold (zext c1) -> c1
4729 // fold (aext c1) -> c1
4730 if (isa<ConstantSDNode>(N0))
4731 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4732
4733 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4734 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4735 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004736 EVT SVT = VT.getScalarType();
4737 if (!(VT.isVector() &&
4738 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004739 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4740 return 0;
4741
4742 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004743 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004744 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4745 unsigned ShAmt = VTBits - EVTBits;
4746 SmallVector<SDValue, 8> Elts;
4747 unsigned NumElts = N0->getNumOperands();
4748 SDLoc DL(N);
4749
4750 for (unsigned i=0; i != NumElts; ++i) {
4751 SDValue Op = N0->getOperand(i);
4752 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004753 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004754 continue;
4755 }
4756
4757 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4758 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4759 if (Opcode == ISD::SIGN_EXTEND)
4760 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004761 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004762 else
4763 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004764 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004765 }
4766
4767 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4768}
4769
Evan Chenge106e2f2007-10-29 19:58:20 +00004770// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004771// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004772// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004773// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004774static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004775 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004776 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004777 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004778 bool HasCopyToRegUses = false;
4779 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004780 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4781 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004782 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004783 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004784 if (User == N)
4785 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004786 if (UI.getUse().getResNo() != N0.getResNo())
4787 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004788 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004789 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004790 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4791 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4792 // Sign bits will be lost after a zext.
4793 return false;
4794 bool Add = false;
4795 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004796 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004797 if (UseOp == N0)
4798 continue;
4799 if (!isa<ConstantSDNode>(UseOp))
4800 return false;
4801 Add = true;
4802 }
4803 if (Add)
4804 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004805 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004806 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004807 // If truncates aren't free and there are users we can't
4808 // extend, it isn't worthwhile.
4809 if (!isTruncFree)
4810 return false;
4811 // Remember if this value is live-out.
4812 if (User->getOpcode() == ISD::CopyToReg)
4813 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004814 }
4815
4816 if (HasCopyToRegUses) {
4817 bool BothLiveOut = false;
4818 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4819 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004820 SDUse &Use = UI.getUse();
4821 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4822 BothLiveOut = true;
4823 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004824 }
4825 }
4826 if (BothLiveOut)
4827 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004828 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004829 return ExtendNodes.size();
4830 }
4831 return true;
4832}
4833
Craig Toppere0b71182013-07-13 07:43:40 +00004834void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004835 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004836 ISD::NodeType ExtType) {
4837 // Extend SetCC uses if necessary.
4838 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4839 SDNode *SetCC = SetCCs[i];
4840 SmallVector<SDValue, 4> Ops;
4841
4842 for (unsigned j = 0; j != 2; ++j) {
4843 SDValue SOp = SetCC->getOperand(j);
4844 if (SOp == Trunc)
4845 Ops.push_back(ExtLoad);
4846 else
4847 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4848 }
4849
4850 Ops.push_back(SetCC->getOperand(2));
4851 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4852 &Ops[0], Ops.size()));
4853 }
4854}
4855
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004856SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4857 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004858 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004859
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004860 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4861 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004862 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004863
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004864 // fold (sext (sext x)) -> (sext x)
4865 // fold (sext (aext x)) -> (sext x)
4866 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004867 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004868 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004869
Chris Lattnerfce448f2007-02-26 03:13:59 +00004870 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004871 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4872 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004873 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4874 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004875 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4876 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004877 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004878 // CombineTo deleted the truncate, if needed, but not what's under it.
4879 AddToWorkList(oye);
4880 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004881 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004882 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004883
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004884 // See if the value being truncated is already sign extended. If so, just
4885 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004886 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004887 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4888 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4889 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004890 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004891
Chris Lattnerfce448f2007-02-26 03:13:59 +00004892 if (OpBits == DestBits) {
4893 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4894 // bits, it is already ready.
4895 if (NumSignBits > DestBits-MidBits)
4896 return Op;
4897 } else if (OpBits < DestBits) {
4898 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4899 // bits, just sext from i32.
4900 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004901 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004902 } else {
4903 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4904 // bits, just truncate to i32.
4905 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004906 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004907 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004908
Chris Lattnerfce448f2007-02-26 03:13:59 +00004909 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004910 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4911 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004912 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004913 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004914 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004915 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4916 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004917 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004918 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004919 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004920
Evan Chengbce7c472005-12-14 02:19:23 +00004921 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004922 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004923 // on vectors in one instruction. We only perform this transformation on
4924 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004925 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004926 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004927 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004928 bool DoXform = true;
4929 SmallVector<SDNode*, 4> SetCCs;
4930 if (!N0.hasOneUse())
4931 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4932 if (DoXform) {
4933 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004934 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004935 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004936 LN0->getBasePtr(), N0.getValueType(),
4937 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004938 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004939 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004940 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004941 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004942 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004943 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004945 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004946 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004947
4948 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4949 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004950 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4951 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004952 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004953 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004954 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004955 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004956 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004957 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004958 LN0->getBasePtr(), MemVT,
4959 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004960 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004961 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004962 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004963 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004964 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004965 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004966 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004967 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004968
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004969 // fold (sext (and/or/xor (load x), cst)) ->
4970 // (and/or/xor (sextload x), (sext cst))
4971 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4972 N0.getOpcode() == ISD::XOR) &&
4973 isa<LoadSDNode>(N0.getOperand(0)) &&
4974 N0.getOperand(1).getOpcode() == ISD::Constant &&
4975 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4976 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4977 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4978 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4979 bool DoXform = true;
4980 SmallVector<SDNode*, 4> SetCCs;
4981 if (!N0.hasOneUse())
4982 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4983 SetCCs, TLI);
4984 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004985 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004986 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004987 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004988 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004989 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4990 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004991 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004992 ExtLoad, DAG.getConstant(Mask, VT));
4993 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004994 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004995 N0.getOperand(0).getValueType(), ExtLoad);
4996 CombineTo(N, And);
4997 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004998 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004999 ISD::SIGN_EXTEND);
5000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5001 }
5002 }
5003 }
5004
Chris Lattner65786b02007-04-11 05:32:27 +00005005 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00005006 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005007 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005008 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00005009 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00005010 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00005011 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00005012 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5013 // of the same size as the compared operands. Only optimize sext(setcc())
5014 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005015 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005016
5017 // We know that the # elements of the results is the same as the
5018 // # elements of the compare (and the # elements of the compare result
5019 // for that matter). Check to see that they are the same size. If so,
5020 // we know that the element size of the sext'd result matches the
5021 // element size of the compare operands.
5022 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005023 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005024 N0.getOperand(1),
5025 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005026
Dan Gohmane82c25e2010-04-30 17:19:19 +00005027 // If the desired elements are smaller or larger than the source
5028 // elements we can use a matching integer vector type and then
5029 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005030 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005031 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005032 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005033 N0.getOperand(0), N0.getOperand(1),
5034 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005035 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005036 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005037 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005038
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005039 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005040 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005041 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005042 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005043 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005044 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005045 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005046 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005047 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005048
5049 if (!VT.isVector()) {
5050 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5051 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5052 SDLoc DL(N);
5053 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5054 SDValue SetCC = DAG.getSetCC(DL,
5055 SetCCVT,
5056 N0.getOperand(0), N0.getOperand(1), CC);
5057 EVT SelectVT = getSetCCResultType(VT);
5058 return DAG.getSelect(DL, VT,
5059 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5060 NegOne, DAG.getConstant(0, VT));
5061
5062 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005063 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005064 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005065
Dan Gohman3eb10f72008-04-28 16:58:24 +00005066 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005067 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005068 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005069 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005070
Evan Chengf1005572010-04-28 07:10:39 +00005071 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005072}
5073
Rafael Espindola8f62b322012-04-09 16:06:03 +00005074// isTruncateOf - If N is a truncate of some other value, return true, record
5075// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5076// This function computes KnownZero to avoid a duplicated call to
5077// ComputeMaskedBits in the caller.
5078static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5079 APInt &KnownZero) {
5080 APInt KnownOne;
5081 if (N->getOpcode() == ISD::TRUNCATE) {
5082 Op = N->getOperand(0);
5083 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5084 return true;
5085 }
5086
5087 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5088 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5089 return false;
5090
5091 SDValue Op0 = N->getOperand(0);
5092 SDValue Op1 = N->getOperand(1);
5093 assert(Op0.getValueType() == Op1.getValueType());
5094
5095 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5096 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005097 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005098 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005099 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005100 Op = Op0;
5101 else
5102 return false;
5103
5104 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5105
5106 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5107 return false;
5108
5109 return true;
5110}
5111
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005112SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5113 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005114 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005115
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005116 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5117 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005118 return SDValue(Res, 0);
5119
Nate Begeman21158fc2005-09-01 00:19:25 +00005120 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005121 // fold (zext (aext x)) -> (zext x)
5122 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005123 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005124 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005125
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005126 // fold (zext (truncate x)) -> (zext x) or
5127 // (zext (truncate x)) -> (truncate x)
5128 // This is valid when the truncated bits of x are already zero.
5129 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005130 SDValue Op;
5131 APInt KnownZero;
5132 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5133 APInt TruncatedBits =
5134 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5135 APInt(Op.getValueSizeInBits(), 0) :
5136 APInt::getBitsSet(Op.getValueSizeInBits(),
5137 N0.getValueSizeInBits(),
5138 std::min(Op.getValueSizeInBits(),
5139 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005140 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005141 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005142 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005143 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005144 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005145
5146 return Op;
5147 }
5148 }
5149
Evan Cheng464dc9b2007-03-22 01:54:19 +00005150 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5151 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005152 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005153 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5154 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005155 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5156 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005157 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005158 // CombineTo deleted the truncate, if needed, but not what's under it.
5159 AddToWorkList(oye);
5160 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005161 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005162 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005163 }
5164
Chris Lattnera31f0a62006-09-21 06:00:20 +00005165 // fold (zext (truncate x)) -> (and x, mask)
5166 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005167 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005168
5169 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5170 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5171 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5172 if (NarrowLoad.getNode()) {
5173 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5174 if (NarrowLoad.getNode() != N0.getNode()) {
5175 CombineTo(N0.getNode(), NarrowLoad);
5176 // CombineTo deleted the truncate, if needed, but not what's under it.
5177 AddToWorkList(oye);
5178 }
5179 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5180 }
5181
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005182 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005183 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005184 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005185 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005186 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005187 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005188 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005189 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005190 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005191 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005192 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005193
Dan Gohmanad3e5492009-04-08 00:15:30 +00005194 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5195 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005196 if (N0.getOpcode() == ISD::AND &&
5197 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005198 N0.getOperand(1).getOpcode() == ISD::Constant &&
5199 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5200 N0.getValueType()) ||
5201 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005202 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005203 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005204 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005205 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005206 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005207 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005208 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005209 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005210 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005211 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005212 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005213
Evan Chengbce7c472005-12-14 02:19:23 +00005214 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005215 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005216 // on vectors in one instruction. We only perform this transformation on
5217 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005218 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005219 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005220 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005221 bool DoXform = true;
5222 SmallVector<SDNode*, 4> SetCCs;
5223 if (!N0.hasOneUse())
5224 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5225 if (DoXform) {
5226 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005227 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005228 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005229 LN0->getBasePtr(), N0.getValueType(),
5230 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005231 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005232 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005233 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005234 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005235
Andrew Trickef9de2a2013-05-25 02:42:55 +00005236 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005237 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005238 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005239 }
Evan Chengbce7c472005-12-14 02:19:23 +00005240 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005241
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005242 // fold (zext (and/or/xor (load x), cst)) ->
5243 // (and/or/xor (zextload x), (zext cst))
5244 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5245 N0.getOpcode() == ISD::XOR) &&
5246 isa<LoadSDNode>(N0.getOperand(0)) &&
5247 N0.getOperand(1).getOpcode() == ISD::Constant &&
5248 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5249 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5250 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5251 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5252 bool DoXform = true;
5253 SmallVector<SDNode*, 4> SetCCs;
5254 if (!N0.hasOneUse())
5255 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5256 SetCCs, TLI);
5257 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005258 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005259 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005260 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005261 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005262 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5263 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005264 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005265 ExtLoad, DAG.getConstant(Mask, VT));
5266 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005267 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005268 N0.getOperand(0).getValueType(), ExtLoad);
5269 CombineTo(N, And);
5270 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005271 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005272 ISD::ZERO_EXTEND);
5273 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5274 }
5275 }
5276 }
5277
Chris Lattner7dac1082005-12-14 19:05:06 +00005278 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5279 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005280 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5281 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005282 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005283 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005284 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005285 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005286 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005287 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005288 LN0->getBasePtr(), MemVT,
5289 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005290 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005291 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005292 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005293 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005294 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005295 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005296 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005297 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005298
Chris Lattner65786b02007-04-11 05:32:27 +00005299 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005300 if (!LegalOperations && VT.isVector() &&
5301 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005302 EVT N0VT = N0.getOperand(0).getValueType();
5303 if (getSetCCResultType(N0VT) == N0.getValueType())
5304 return SDValue();
5305
Evan Chengabd0ad52010-05-19 01:08:17 +00005306 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5307 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005308 EVT EltVT = VT.getVectorElementType();
5309 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5310 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005311 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005312 // We know that the # elements of the results is the same as the
5313 // # elements of the compare (and the # elements of the compare result
5314 // for that matter). Check to see that they are the same size. If so,
5315 // we know that the element size of the sext'd result matches the
5316 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005317 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5318 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005319 N0.getOperand(1),
5320 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005321 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Chengabd0ad52010-05-19 01:08:17 +00005322 &OneOps[0], OneOps.size()));
Dan Gohman4298df62011-05-17 22:20:36 +00005323
5324 // If the desired elements are smaller or larger than the source
5325 // elements we can use a matching integer vector type and then
5326 // truncate/sign extend
5327 EVT MatchingElementType =
5328 EVT::getIntegerVT(*DAG.getContext(),
5329 N0VT.getScalarType().getSizeInBits());
5330 EVT MatchingVectorType =
5331 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5332 N0VT.getVectorNumElements());
5333 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005334 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005335 N0.getOperand(1),
5336 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005337 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5338 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5339 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman4298df62011-05-17 22:20:36 +00005340 &OneOps[0], OneOps.size()));
Evan Chengabd0ad52010-05-19 01:08:17 +00005341 }
5342
5343 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005344 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005345 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005346 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005347 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005348 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005349 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005350
Evan Cheng852c4862009-12-15 03:00:32 +00005351 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005352 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005353 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005354 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5355 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005356 SDValue ShAmt = N0.getOperand(1);
5357 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005358 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005359 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005360 // If the original shl may be shifting out bits, do not perform this
5361 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005362 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5363 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5364 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005365 return SDValue();
5366 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005367
Andrew Trickef9de2a2013-05-25 02:42:55 +00005368 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005369
5370 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005371 if (VT.getSizeInBits() >= 256)
5372 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005373
Chris Lattnere95d1952011-02-13 19:09:16 +00005374 return DAG.getNode(N0.getOpcode(), DL, VT,
5375 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5376 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005377 }
5378
Evan Chengf1005572010-04-28 07:10:39 +00005379 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005380}
5381
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005382SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5383 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005384 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005385
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005386 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5387 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005388 return SDValue(Res, 0);
5389
Chris Lattner812646a2006-05-05 05:58:59 +00005390 // fold (aext (aext x)) -> (aext x)
5391 // fold (aext (zext x)) -> (zext x)
5392 // fold (aext (sext x)) -> (sext x)
5393 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5394 N0.getOpcode() == ISD::ZERO_EXTEND ||
5395 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005396 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005397
Evan Cheng464dc9b2007-03-22 01:54:19 +00005398 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5399 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5400 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005401 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5402 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005403 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5404 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005405 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005406 // CombineTo deleted the truncate, if needed, but not what's under it.
5407 AddToWorkList(oye);
5408 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005410 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005411 }
5412
Chris Lattner8746e2c2006-09-20 06:29:17 +00005413 // fold (aext (truncate x))
5414 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005415 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005416 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005417 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005418 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005419 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5420 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005421 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005422
Dan Gohmanad3e5492009-04-08 00:15:30 +00005423 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5424 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005425 if (N0.getOpcode() == ISD::AND &&
5426 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005427 N0.getOperand(1).getOpcode() == ISD::Constant &&
5428 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5429 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005430 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005431 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005432 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005433 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005434 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005435 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005436 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005437 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005438 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005439 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005440 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005441
Chris Lattner812646a2006-05-05 05:58:59 +00005442 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005443 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005444 // on vectors in one instruction. We only perform this transformation on
5445 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005446 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005447 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005448 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005449 bool DoXform = true;
5450 SmallVector<SDNode*, 4> SetCCs;
5451 if (!N0.hasOneUse())
5452 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5453 if (DoXform) {
5454 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005455 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005456 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005457 LN0->getBasePtr(), N0.getValueType(),
5458 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005459 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005460 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005461 N0.getValueType(), ExtLoad);
5462 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005463 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005464 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005465 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5466 }
Chris Lattner812646a2006-05-05 05:58:59 +00005467 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005468
Chris Lattner812646a2006-05-05 05:58:59 +00005469 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5470 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5471 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005472 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005473 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005474 N0.hasOneUse()) {
5475 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005476 EVT MemVT = LN0->getMemoryVT();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005477 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
Stuart Hastings81c43062011-02-16 16:23:55 +00005478 VT, LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005479 MemVT, LN0->getMemOperand());
Chris Lattner812646a2006-05-05 05:58:59 +00005480 CombineTo(N, ExtLoad);
Evan Cheng894be332008-08-29 23:20:46 +00005481 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005482 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005483 N0.getValueType(), ExtLoad),
Chris Lattner812646a2006-05-05 05:58:59 +00005484 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005485 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner812646a2006-05-05 05:58:59 +00005486 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005487
Chris Lattner65786b02007-04-11 05:32:27 +00005488 if (N0.getOpcode() == ISD::SETCC) {
Evan Chengabd0ad52010-05-19 01:08:17 +00005489 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5490 // Only do this before legalize for now.
5491 if (VT.isVector() && !LegalOperations) {
5492 EVT N0VT = N0.getOperand(0).getValueType();
5493 // We know that the # elements of the results is the same as the
5494 // # elements of the compare (and the # elements of the compare result
5495 // for that matter). Check to see that they are the same size. If so,
5496 // we know that the element size of the sext'd result matches the
5497 // element size of the compare operands.
5498 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005499 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005500 N0.getOperand(1),
5501 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005502 // If the desired elements are smaller or larger than the source
5503 // elements we can use a matching integer vector type and then
5504 // truncate/sign extend
5505 else {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005506 EVT MatchingElementType =
5507 EVT::getIntegerVT(*DAG.getContext(),
5508 N0VT.getScalarType().getSizeInBits());
5509 EVT MatchingVectorType =
5510 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5511 N0VT.getVectorNumElements());
5512 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005513 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005514 N0.getOperand(1),
5515 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005516 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005517 }
5518 }
5519
5520 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005521 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005522 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005523 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005524 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005525 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005526 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005527 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005528
Evan Chengf1005572010-04-28 07:10:39 +00005529 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005530}
5531
Chris Lattner5e6fe052007-10-13 06:35:54 +00005532/// GetDemandedBits - See if the specified operand can be simplified with the
5533/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005534/// simpler operand, otherwise return a null SDValue.
5535SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005536 switch (V.getOpcode()) {
5537 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005538 case ISD::Constant: {
5539 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5540 assert(CV != 0 && "Const value should be ConstSDNode.");
5541 const APInt &CVal = CV->getAPIntValue();
5542 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005543 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005544 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005545 break;
5546 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005547 case ISD::OR:
5548 case ISD::XOR:
5549 // If the LHS or RHS don't contribute bits to the or, drop them.
5550 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5551 return V.getOperand(1);
5552 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5553 return V.getOperand(0);
5554 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005555 case ISD::SRL:
5556 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005557 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005558 break;
5559 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5560 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005561 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005562
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005563 // Watch out for shift count overflow though.
5564 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005565 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005566 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005567 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005568 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005569 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005570 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005571 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005572 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005573}
5574
Evan Cheng464dc9b2007-03-22 01:54:19 +00005575/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5576/// bits and then truncated to a narrower type and where N is a multiple
5577/// of number of bits of the narrower type, transform it to a narrower load
5578/// from address + N / num of bits of new type. If the result is to be
5579/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005580SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005581 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005582
Evan Cheng464dc9b2007-03-22 01:54:19 +00005583 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005584 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005585 EVT VT = N->getValueType(0);
5586 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005587
Dan Gohman550c9af2008-08-14 20:04:46 +00005588 // This transformation isn't valid for vector loads.
5589 if (VT.isVector())
5590 return SDValue();
5591
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005592 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005593 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005594 if (Opc == ISD::SIGN_EXTEND_INREG) {
5595 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005596 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005597 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005598 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005599 ExtType = ISD::ZEXTLOAD;
5600 N0 = SDValue(N, 0);
5601 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5602 if (!N01) return SDValue();
5603 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5604 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005605 }
Richard Osborne272e0842011-01-31 17:41:44 +00005606 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5607 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005608
Owen Anderson53aa7a92009-08-10 22:56:29 +00005609 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005610
Chris Lattner9a499e92010-12-22 08:01:44 +00005611 // Do not generate loads of non-round integer types since these can
5612 // be expensive (and would be wrong if the type is not byte sized).
5613 if (!ExtVT.isRound())
5614 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005615
Evan Cheng464dc9b2007-03-22 01:54:19 +00005616 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005617 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005618 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005619 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005620 // Is the shift amount a multiple of size of VT?
5621 if ((ShAmt & (EVTBits-1)) == 0) {
5622 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005623 // Is the load width a multiple of size of VT?
5624 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005625 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005626 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005627
Chris Lattnercafc1e62010-12-22 08:02:57 +00005628 // At this point, we must have a load or else we can't do the transform.
5629 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005630
Chandler Carruthb27041c2012-12-11 00:36:57 +00005631 // Because a SRL must be assumed to *need* to zero-extend the high bits
5632 // (as opposed to anyext the high bits), we can't combine the zextload
5633 // lowering of SRL and an sextload.
5634 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5635 return SDValue();
5636
Chris Lattnera2050552010-10-01 05:36:09 +00005637 // If the shift amount is larger than the input type then we're not
5638 // accessing any of the loaded bytes. If the load was a zextload/extload
5639 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005640 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005641 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005642 }
5643 }
5644
Dan Gohman68fb0042010-11-03 01:47:46 +00005645 // If the load is shifted left (and the result isn't shifted back right),
5646 // we can fold the truncate through the shift.
5647 unsigned ShLeftAmt = 0;
5648 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005649 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005650 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5651 ShLeftAmt = N01->getZExtValue();
5652 N0 = N0.getOperand(0);
5653 }
5654 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005655
Chris Lattner222374d2010-12-22 07:36:50 +00005656 // If we haven't found a load, we can't narrow it. Don't transform one with
5657 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005658 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5659 return SDValue();
5660
5661 // Don't change the width of a volatile load.
5662 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5663 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005664 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005665
Chris Lattner9a499e92010-12-22 08:01:44 +00005666 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005667 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005668 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005669
Bill Schmidtd006c692013-01-14 22:04:38 +00005670 // For the transform to be legal, the load must produce only two values
5671 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005672 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005673 // transformation is not equivalent, and the downstream logic to replace
5674 // uses gets things wrong.
5675 if (LN0->getNumValues() > 2)
5676 return SDValue();
5677
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005678 // If the load that we're shrinking is an extload and we're not just
5679 // discarding the extension we can't simply shrink the load. Bail.
5680 // TODO: It would be possible to merge the extensions in some cases.
5681 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5682 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5683 return SDValue();
5684
Chris Lattner222374d2010-12-22 07:36:50 +00005685 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005686
Evan Cheng4c6f9172012-06-26 01:19:33 +00005687 if (PtrType == MVT::Untyped || PtrType.isExtended())
5688 // It's not possible to generate a constant of extended or untyped type.
5689 return SDValue();
5690
Chris Lattner222374d2010-12-22 07:36:50 +00005691 // For big endian targets, we need to adjust the offset to the pointer to
5692 // load the correct bytes.
5693 if (TLI.isBigEndian()) {
5694 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5695 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5696 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005697 }
5698
Chris Lattner222374d2010-12-22 07:36:50 +00005699 uint64_t PtrOff = ShAmt / 8;
5700 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005701 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005702 PtrType, LN0->getBasePtr(),
5703 DAG.getConstant(PtrOff, PtrType));
5704 AddToWorkList(NewPtr.getNode());
5705
Chris Lattner9a499e92010-12-22 08:01:44 +00005706 SDValue Load;
5707 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005708 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005709 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005710 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005711 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005712 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005713 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005714 LN0->getPointerInfo().getWithOffset(PtrOff),
5715 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005716 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005717
5718 // Replace the old load's chain with the new load's chain.
5719 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005720 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005721
5722 // Shift the result left, if we've swallowed a left shift.
5723 SDValue Result = Load;
5724 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005725 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005726 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5727 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005728 // If the shift amount is as large as the result size (but, presumably,
5729 // no larger than the source) then the useful bits of the result are
5730 // zero; we can't simply return the shortened shift, because the result
5731 // of that operation is undefined.
5732 if (ShLeftAmt >= VT.getSizeInBits())
5733 Result = DAG.getConstant(0, VT);
5734 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005735 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005736 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005737 }
5738
5739 // Return the new loaded value.
5740 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005741}
5742
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005743SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5744 SDValue N0 = N->getOperand(0);
5745 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005746 EVT VT = N->getValueType(0);
5747 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005748 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005749 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005750
Nate Begeman21158fc2005-09-01 00:19:25 +00005751 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005752 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005753 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005754
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005755 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005756 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005757 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005758
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005759 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5760 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005761 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005762 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005763 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005764
Dan Gohman345d63c2008-07-31 00:50:31 +00005765 // fold (sext_in_reg (sext x)) -> (sext x)
5766 // fold (sext_in_reg (aext x)) -> (sext x)
5767 // if x is small enough.
5768 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5769 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005770 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5771 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005772 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005773 }
5774
Chris Lattner9ad59152007-04-17 19:03:21 +00005775 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005776 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005777 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005778
Chris Lattner9ad59152007-04-17 19:03:21 +00005779 // fold operands of sext_in_reg based on knowledge that the top bits are not
5780 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005781 if (SimplifyDemandedBits(SDValue(N, 0)))
5782 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005783
Evan Cheng464dc9b2007-03-22 01:54:19 +00005784 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5785 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005786 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005787 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005788 return NarrowLoad;
5789
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005790 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005791 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005792 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5793 if (N0.getOpcode() == ISD::SRL) {
5794 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005795 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005796 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005797 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005798 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005799 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005800 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005801 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005802 }
5803 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005804
Nate Begeman02b23c62005-10-13 03:11:28 +00005805 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005806 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005807 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005808 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005809 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005810 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005811 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005812 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005813 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005814 LN0->getBasePtr(), EVT,
5815 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005816 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005817 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005818 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005820 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005821 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005822 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005823 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005824 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005825 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005826 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005827 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005828 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005829 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005830 LN0->getBasePtr(), EVT,
5831 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005832 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005833 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005834 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005835 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005836
5837 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5838 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5839 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5840 N0.getOperand(1), false);
5841 if (BSwap.getNode() != 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005842 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005843 BSwap, N1);
5844 }
5845
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005846 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5847 // into a build_vector.
5848 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5849 SmallVector<SDValue, 8> Elts;
5850 unsigned NumElts = N0->getNumOperands();
5851 unsigned ShAmt = VTBits - EVTBits;
5852
5853 for (unsigned i = 0; i != NumElts; ++i) {
5854 SDValue Op = N0->getOperand(i);
5855 if (Op->getOpcode() == ISD::UNDEF) {
5856 Elts.push_back(Op);
5857 continue;
5858 }
5859
5860 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005861 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5862 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005863 Op.getValueType()));
5864 }
5865
5866 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5867 }
5868
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005869 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005870}
5871
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005872SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5873 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005874 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005875 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005876
5877 // noop truncate
5878 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005879 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005880 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005881 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005882 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005883 // fold (truncate (truncate x)) -> (truncate x)
5884 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005885 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005886 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005887 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5888 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005889 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005890 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005891 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005892 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005893 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005894 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005895 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005896 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005897 // if the source and dest are the same type, we can drop both the extend
5898 // and the truncate.
5899 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005900 }
Evan Chengd63baea2007-03-21 20:14:05 +00005901
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005902 // Fold extract-and-trunc into a narrow extract. For example:
5903 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5904 // i32 y = TRUNCATE(i64 x)
5905 // -- becomes --
5906 // v16i8 b = BITCAST (v2i64 val)
5907 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5908 //
5909 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005910 // creates this pattern) and before operation legalization after which
5911 // we need to be more careful about the vector instructions that we generate.
5912 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005913 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005914
5915 EVT VecTy = N0.getOperand(0).getValueType();
5916 EVT ExTy = N0.getValueType();
5917 EVT TrTy = N->getValueType(0);
5918
5919 unsigned NumElem = VecTy.getVectorNumElements();
5920 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5921
5922 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5923 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5924
5925 SDValue EltNo = N0->getOperand(1);
5926 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5927 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005928 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005929 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5930
Andrew Trickef9de2a2013-05-25 02:42:55 +00005931 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005932 NVT, N0.getOperand(0));
5933
5934 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005935 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005936 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005937 }
5938 }
5939
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005940 // Fold a series of buildvector, bitcast, and truncate if possible.
5941 // For example fold
5942 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5943 // (2xi32 (buildvector x, y)).
5944 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5945 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5946 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5947 N0.getOperand(0).hasOneUse()) {
5948
5949 SDValue BuildVect = N0.getOperand(0);
5950 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5951 EVT TruncVecEltTy = VT.getVectorElementType();
5952
5953 // Check that the element types match.
5954 if (BuildVectEltTy == TruncVecEltTy) {
5955 // Now we only need to compute the offset of the truncated elements.
5956 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5957 unsigned TruncVecNumElts = VT.getVectorNumElements();
5958 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5959
5960 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5961 "Invalid number of elements");
5962
5963 SmallVector<SDValue, 8> Opnds;
5964 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5965 Opnds.push_back(BuildVect.getOperand(i));
5966
Andrew Trickef9de2a2013-05-25 02:42:55 +00005967 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005968 Opnds.size());
5969 }
5970 }
5971
Chris Lattner5e6fe052007-10-13 06:35:54 +00005972 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00005973 // only the low bits are being used.
5974 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00005975 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00005976 // may have different active low bits.
5977 if (!VT.isVector()) {
5978 SDValue Shorter =
5979 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5980 VT.getSizeInBits()));
5981 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005982 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00005983 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005984 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00005985 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00005986 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5987 SDValue Reduced = ReduceLoadWidth(N);
5988 if (Reduced.getNode())
5989 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00005990 // Handle the case where the load remains an extending load even
5991 // after truncation.
5992 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5993 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5994 if (!LN0->isVolatile() &&
5995 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5996 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5997 VT, LN0->getChain(), LN0->getBasePtr(),
5998 LN0->getMemoryVT(),
5999 LN0->getMemOperand());
6000 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6001 return NewLoad;
6002 }
6003 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006004 }
Michael Liao3ac82012012-10-17 23:45:54 +00006005 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6006 // where ... are all 'undef'.
6007 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6008 SmallVector<EVT, 8> VTs;
6009 SDValue V;
6010 unsigned Idx = 0;
6011 unsigned NumDefs = 0;
6012
6013 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6014 SDValue X = N0.getOperand(i);
6015 if (X.getOpcode() != ISD::UNDEF) {
6016 V = X;
6017 Idx = i;
6018 NumDefs++;
6019 }
6020 // Stop if more than one members are non-undef.
6021 if (NumDefs > 1)
6022 break;
6023 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6024 VT.getVectorElementType(),
6025 X.getValueType().getVectorNumElements()));
6026 }
6027
6028 if (NumDefs == 0)
6029 return DAG.getUNDEF(VT);
6030
6031 if (NumDefs == 1) {
6032 assert(V.getNode() && "The single defined operand is empty!");
6033 SmallVector<SDValue, 8> Opnds;
6034 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6035 if (i != Idx) {
6036 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6037 continue;
6038 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006039 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00006040 AddToWorkList(NV.getNode());
6041 Opnds.push_back(NV);
6042 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006043 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao3ac82012012-10-17 23:45:54 +00006044 &Opnds[0], Opnds.size());
6045 }
6046 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006047
6048 // Simplify the operands using demanded-bits information.
6049 if (!VT.isVector() &&
6050 SimplifyDemandedBits(SDValue(N, 0)))
6051 return SDValue(N, 0);
6052
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006053 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006054}
6055
Evan Chengb980f6f2008-05-12 23:04:07 +00006056static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006057 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006058 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006059 return Elt.getNode();
6060 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006061}
6062
6063/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006064/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006065SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006066 assert(N->getOpcode() == ISD::BUILD_PAIR);
6067
Nate Begeman624690c2009-06-05 21:37:30 +00006068 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6069 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006070 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006071 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006072 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006073 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006074
Evan Chengb980f6f2008-05-12 23:04:07 +00006075 if (ISD::isNON_EXTLoad(LD2) &&
6076 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006077 // If both are volatile this would reduce the number of volatile loads.
6078 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006079 !LD1->isVolatile() &&
6080 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006081 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006082 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006083 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006084 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006085
Duncan Sands8651e9c2008-06-13 19:07:40 +00006086 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006087 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006088 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006089 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006090 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006091 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006092
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006093 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006094}
6095
Wesley Peck527da1b2010-11-23 03:31:01 +00006096SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006097 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006098 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006099
Dan Gohmana8665142007-06-25 16:23:39 +00006100 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6101 // Only do this before legalize, since afterward the target may be depending
6102 // on the bitconvert.
6103 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006104 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006105 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006106 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006107 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006108
Owen Anderson53aa7a92009-08-10 22:56:29 +00006109 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006110 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006111 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006112 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006113 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006114 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006115
Dan Gohman921ddd62008-09-05 01:58:21 +00006116 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006117 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006118 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006119 if (Res.getNode() != N) {
6120 if (!LegalOperations ||
6121 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6122 return Res;
6123
6124 // Folding it resulted in an illegal node, and it's too late to
6125 // do that. Clean up the old node and forego the transformation.
6126 // Ideally this won't happen very often, because instcombine
6127 // and the earlier dagcombine runs (where illegal nodes are
6128 // permitted) should have folded most of them already.
6129 DAG.DeleteNode(Res.getNode());
6130 }
Chris Lattnera1874602005-12-23 05:30:37 +00006131 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006132
Bill Wendling4e0a6152009-01-30 22:44:24 +00006133 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006134 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006135 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006136 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006137
Chris Lattner54560f62005-12-23 05:44:41 +00006138 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006139 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006140 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006141 // Do not change the width of a volatile load.
6142 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006143 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6144 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006145 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006146 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006147 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006148 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006149
Evan Chenga4cf58a2007-05-07 21:27:48 +00006150 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006151 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006152 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006153 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006154 LN0->isInvariant(), OrigAlign,
6155 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006156 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006157 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006158 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006159 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006160 Load.getValue(1));
6161 return Load;
6162 }
Chris Lattner54560f62005-12-23 05:44:41 +00006163 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006164
Bill Wendling4e0a6152009-01-30 22:44:24 +00006165 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6166 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006167 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006168 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6169 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006170 N0.getNode()->hasOneUse() && VT.isInteger() &&
6171 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006172 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006173 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006174 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006175
Duncan Sands13237ac2008-06-06 12:08:01 +00006176 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006177 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006178 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006179 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006180 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006181 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006182 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006183 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006184
Bill Wendling4e0a6152009-01-30 22:44:24 +00006185 // fold (bitconvert (fcopysign cst, x)) ->
6186 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6187 // Note that we don't handle (copysign x, cst) because this can always be
6188 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006189 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006190 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006191 VT.isInteger() && !VT.isVector()) {
6192 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006193 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006194 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006195 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006196 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006197 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006198
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006199 // If X has a different width than the result/lhs, sext it or truncate it.
6200 unsigned VTWidth = VT.getSizeInBits();
6201 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006202 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006203 AddToWorkList(X.getNode());
6204 } else if (OrigXWidth > VTWidth) {
6205 // To get the sign bit in the right place, we have to shift it right
6206 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006207 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006208 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006209 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6210 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006211 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006212 AddToWorkList(X.getNode());
6213 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006214
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006215 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006216 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006217 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006218 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006219
Andrew Trickef9de2a2013-05-25 02:42:55 +00006220 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006221 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006222 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006223 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006224 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006225
Andrew Trickef9de2a2013-05-25 02:42:55 +00006226 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006227 }
Chris Lattner888560d2008-01-27 17:42:27 +00006228 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006229
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006230 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006231 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006232 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6233 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006234 return CombineLD;
6235 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006236
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006237 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006238}
6239
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006240SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006241 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006242 return CombineConsecutiveLoads(N, VT);
6243}
6244
Wesley Peck527da1b2010-11-23 03:31:01 +00006245/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006246/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006247/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006248SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006249ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006250 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006251
Chris Lattnere4e64b62006-04-02 02:53:43 +00006252 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006253 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006254
Duncan Sands13237ac2008-06-06 12:08:01 +00006255 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6256 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006257
Chris Lattnere4e64b62006-04-02 02:53:43 +00006258 // If this is a conversion of N elements of one type to N elements of another
6259 // type, convert each element. This handles FP<->INT cases.
6260 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006261 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6262 BV->getValueType(0).getVectorNumElements());
6263
6264 // Due to the FP element handling below calling this routine recursively,
6265 // we can end up with a scalar-to-vector node here.
6266 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006267 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6268 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006269 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006270
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006271 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006272 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006273 SDValue Op = BV->getOperand(i);
6274 // If the vector element type is not legal, the BUILD_VECTOR operands
6275 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006276 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006277 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6278 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006279 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006280 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006281 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006282 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006283 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006284 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006285
Chris Lattnere4e64b62006-04-02 02:53:43 +00006286 // Otherwise, we're growing or shrinking the elements. To avoid having to
6287 // handle annoying details of growing/shrinking FP values, we convert them to
6288 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006289 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006290 // Convert the input float vector to a int vector where the elements are the
6291 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006292 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006293 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006294 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006295 SrcEltVT = IntVT;
6296 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006297
Chris Lattnere4e64b62006-04-02 02:53:43 +00006298 // Now we know the input is an integer vector. If the output is a FP type,
6299 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006300 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006301 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006302 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006303 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006304
Chris Lattnere4e64b62006-04-02 02:53:43 +00006305 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006306 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006307 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006308
Chris Lattnere4e64b62006-04-02 02:53:43 +00006309 // Okay, we know the src/dst types are both integers of differing types.
6310 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006311 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006312 if (SrcBitSize < DstBitSize) {
6313 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006314
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006315 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006316 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006317 i += NumInputsPerOutput) {
6318 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006319 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006320 bool EltIsUndef = true;
6321 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6322 // Shift the previously computed bits over.
6323 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006324 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006325 if (Op.getOpcode() == ISD::UNDEF) continue;
6326 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006327
Jay Foad583abbc2010-12-07 08:25:19 +00006328 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006329 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006330 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006331
Chris Lattnere4e64b62006-04-02 02:53:43 +00006332 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006333 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006334 else
6335 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6336 }
6337
Owen Anderson117c9e82009-08-12 00:36:31 +00006338 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006339 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006340 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006341 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006342
Chris Lattnere4e64b62006-04-02 02:53:43 +00006343 // Finally, this must be the case where we are shrinking elements: each input
6344 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006345 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006346 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006347 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6348 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006349 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006350
Dan Gohmana8665142007-06-25 16:23:39 +00006351 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006352 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6353 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006354 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006355 continue;
6356 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006357
Jay Foad583abbc2010-12-07 08:25:19 +00006358 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6359 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006360
Chris Lattnere4e64b62006-04-02 02:53:43 +00006361 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006362 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006363 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006364 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006365 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006366 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006367 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006368 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006369 }
6370
6371 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006372 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006373 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6374 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006375
Andrew Trickef9de2a2013-05-25 02:42:55 +00006376 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006377 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006378}
6379
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006380SDValue DAGCombiner::visitFADD(SDNode *N) {
6381 SDValue N0 = N->getOperand(0);
6382 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006383 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6384 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006385 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006386
Dan Gohmana8665142007-06-25 16:23:39 +00006387 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006388 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006389 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006390 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006391 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006392
Lang Hamesa33db652012-06-14 20:37:15 +00006393 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006394 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006395 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006396 // canonicalize constant to RHS
6397 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006398 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006399 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006400 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6401 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006402 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006403 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006404 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006405 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006406 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006407 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006408 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006409 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006410 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006411 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006412 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006413
Chris Lattner0199fd62007-01-08 23:04:05 +00006414 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006415 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6416 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6417 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006418 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6419 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006420 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006421
Shuxin Yang93b1f122013-03-25 22:52:29 +00006422 // No FP constant should be created after legalization as Instruction
6423 // Selection pass has hard time in dealing with FP constant.
6424 //
6425 // We don't need test this condition for transformation like following, as
6426 // the DAG being transformed implies it is legal to take FP constant as
6427 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006428 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006429 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006430 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006431 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6432
Owen Andersonb351c8d2012-11-01 02:00:53 +00006433 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006434 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006435 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006436 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006437
6438 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006439 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006440 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006441 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006442
Owen Andersoncc61f872012-08-30 23:35:16 +00006443 // In unsafe math mode, we can fold chains of FADD's of the same value
6444 // into multiplications. This transform is not safe in general because
6445 // we are reducing the number of rounding steps.
6446 if (DAG.getTarget().Options.UnsafeFPMath &&
6447 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6448 !N0CFP && !N1CFP) {
6449 if (N0.getOpcode() == ISD::FMUL) {
6450 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6451 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6452
Stephen Line31f2d22013-06-14 18:17:35 +00006453 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006454 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006455 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006456 SDValue(CFP00, 0),
6457 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006458 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006459 N1, NewCFP);
6460 }
6461
Stephen Line31f2d22013-06-14 18:17:35 +00006462 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006463 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006464 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006465 SDValue(CFP01, 0),
6466 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006467 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006468 N1, NewCFP);
6469 }
6470
Stephen Line31f2d22013-06-14 18:17:35 +00006471 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006472 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6473 N1.getOperand(0) == N1.getOperand(1) &&
6474 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006475 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006476 SDValue(CFP00, 0),
6477 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006478 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006479 N0.getOperand(1), NewCFP);
6480 }
6481
Stephen Line31f2d22013-06-14 18:17:35 +00006482 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006483 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6484 N1.getOperand(0) == N1.getOperand(1) &&
6485 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006486 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006487 SDValue(CFP01, 0),
6488 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006489 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006490 N0.getOperand(0), NewCFP);
6491 }
6492 }
6493
6494 if (N1.getOpcode() == ISD::FMUL) {
6495 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6496 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6497
Stephen Line31f2d22013-06-14 18:17:35 +00006498 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006499 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006500 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006501 SDValue(CFP10, 0),
6502 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006503 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006504 N0, NewCFP);
6505 }
6506
Stephen Line31f2d22013-06-14 18:17:35 +00006507 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006508 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006509 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006510 SDValue(CFP11, 0),
6511 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006512 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006513 N0, NewCFP);
6514 }
6515
Owen Andersoncc61f872012-08-30 23:35:16 +00006516
Stephen Line31f2d22013-06-14 18:17:35 +00006517 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6518 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6519 N0.getOperand(0) == N0.getOperand(1) &&
6520 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006521 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006522 SDValue(CFP10, 0),
6523 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006524 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006525 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006526 }
6527
Stephen Line31f2d22013-06-14 18:17:35 +00006528 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6529 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6530 N0.getOperand(0) == N0.getOperand(1) &&
6531 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006532 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006533 SDValue(CFP11, 0),
6534 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006535 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006536 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006537 }
6538 }
6539
Shuxin Yang93b1f122013-03-25 22:52:29 +00006540 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006541 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006542 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006543 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006544 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006545 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006546 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006547 }
6548
Shuxin Yang93b1f122013-03-25 22:52:29 +00006549 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006550 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006551 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006552 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006553 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006554 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006555 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006556 }
6557
Stephen Lin4e69d012013-06-14 21:33:58 +00006558 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006559 if (AllowNewFpConst &&
6560 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006561 N0.getOperand(0) == N0.getOperand(1) &&
6562 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006563 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006564 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006565 N0.getOperand(0),
6566 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006567 }
6568
Lang Hames39fb1d02012-06-19 22:51:23 +00006569 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006570 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006571 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006572 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6573 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006574
6575 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006576 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006577 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006578 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006579
Michael Liaoec3850122012-09-01 04:09:16 +00006580 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006581 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006582 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006583 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006584 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006585 }
6586
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006587 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006588}
6589
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006590SDValue DAGCombiner::visitFSUB(SDNode *N) {
6591 SDValue N0 = N->getOperand(0);
6592 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006593 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6594 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006595 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006596 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006597
Dan Gohmana8665142007-06-25 16:23:39 +00006598 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006599 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006600 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006601 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006602 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006603
Nate Begeman418c6e42005-10-18 00:28:13 +00006604 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006605 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006606 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006607 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006608 if (DAG.getTarget().Options.UnsafeFPMath &&
6609 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006610 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006611 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006612 if (DAG.getTarget().Options.UnsafeFPMath &&
6613 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006614 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006615 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006616 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006617 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006618 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006619 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006620 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006621 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006622 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006623
Bill Wendlingdf170db2012-03-15 05:12:00 +00006624 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006625 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006626 // (fsub x, (fadd x, y)) -> (fneg y) &
6627 // (fsub x, (fadd y, x)) -> (fneg y)
6628 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006629 if (N0 == N1)
6630 return DAG.getConstantFP(0.0f, VT);
6631
Bill Wendlingdf170db2012-03-15 05:12:00 +00006632 if (N1.getOpcode() == ISD::FADD) {
6633 SDValue N10 = N1->getOperand(0);
6634 SDValue N11 = N1->getOperand(1);
6635
6636 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6637 &DAG.getTarget().Options))
6638 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006639
Stephen Lin8e8424e2013-07-09 00:44:49 +00006640 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6641 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006642 return GetNegatedExpression(N10, DAG, LegalOperations);
6643 }
6644 }
6645
Lang Hames39fb1d02012-06-19 22:51:23 +00006646 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006647 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006648 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006649 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6650 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006651
6652 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006653 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006654 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006655 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006656 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006657
6658 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6659 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006660 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006661 return DAG.getNode(ISD::FMA, dl, VT,
6662 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006663 N1.getOperand(0)),
6664 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006665
Stephen Lin8e8424e2013-07-09 00:44:49 +00006666 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006667 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006668 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6669 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6670 SDValue N00 = N0.getOperand(0).getOperand(0);
6671 SDValue N01 = N0.getOperand(0).getOperand(1);
6672 return DAG.getNode(ISD::FMA, dl, VT,
6673 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6674 DAG.getNode(ISD::FNEG, dl, VT, N1));
6675 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006676 }
6677
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006678 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006679}
6680
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006681SDValue DAGCombiner::visitFMUL(SDNode *N) {
6682 SDValue N0 = N->getOperand(0);
6683 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006684 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6685 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006686 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006687 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006688
Dan Gohmana8665142007-06-25 16:23:39 +00006689 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006690 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006691 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006692 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006693 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006694
Nate Begemanec48a1b2005-10-17 20:40:11 +00006695 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006696 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006698 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006699 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006700 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006701 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006702 if (DAG.getTarget().Options.UnsafeFPMath &&
6703 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006704 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006705 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006706 if (DAG.getTarget().Options.UnsafeFPMath &&
6707 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006708 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006709 // fold (fmul A, 1.0) -> A
6710 if (N1CFP && N1CFP->isExactlyValue(1.0))
6711 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006712 // fold (fmul X, 2.0) -> (fadd X, X)
6713 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006714 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006715 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006716 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006717 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006718 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006719
Bill Wendling3dc5d242009-01-30 22:57:07 +00006720 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006721 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006722 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006723 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006724 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006725 // Both can be negated for free, check to see if at least one is cheaper
6726 // negated.
6727 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006728 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006729 GetNegatedExpression(N0, DAG, LegalOperations),
6730 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006731 }
6732 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006733
Chris Lattner0199fd62007-01-08 23:04:05 +00006734 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006735 if (DAG.getTarget().Options.UnsafeFPMath &&
6736 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006737 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006738 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6739 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006740 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006741
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006742 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006743}
6744
Owen Anderson41b06652012-05-02 22:17:40 +00006745SDValue DAGCombiner::visitFMA(SDNode *N) {
6746 SDValue N0 = N->getOperand(0);
6747 SDValue N1 = N->getOperand(1);
6748 SDValue N2 = N->getOperand(2);
6749 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6750 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6751 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006752 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006753
Owen Andersonb351c8d2012-11-01 02:00:53 +00006754 if (DAG.getTarget().Options.UnsafeFPMath) {
6755 if (N0CFP && N0CFP->isZero())
6756 return N2;
6757 if (N1CFP && N1CFP->isZero())
6758 return N2;
6759 }
Owen Anderson41b06652012-05-02 22:17:40 +00006760 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006761 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006762 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006763 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006764
Owen Andersonc7aaf522012-05-30 18:50:39 +00006765 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006766 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006767 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006768
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006769 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6770 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6771 N2.getOpcode() == ISD::FMUL &&
6772 N0 == N2.getOperand(0) &&
6773 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6774 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6775 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6776 }
6777
6778
6779 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6780 if (DAG.getTarget().Options.UnsafeFPMath &&
6781 N0.getOpcode() == ISD::FMUL && N1CFP &&
6782 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6783 return DAG.getNode(ISD::FMA, dl, VT,
6784 N0.getOperand(0),
6785 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6786 N2);
6787 }
6788
6789 // (fma x, 1, y) -> (fadd x, y)
6790 // (fma x, -1, y) -> (fadd (fneg x), y)
6791 if (N1CFP) {
6792 if (N1CFP->isExactlyValue(1.0))
6793 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6794
6795 if (N1CFP->isExactlyValue(-1.0) &&
6796 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6797 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6798 AddToWorkList(RHSNeg.getNode());
6799 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6800 }
6801 }
6802
6803 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006804 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6805 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006806 DAG.getNode(ISD::FADD, dl, VT,
6807 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006808
6809 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6810 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006811 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6812 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006813 DAG.getNode(ISD::FADD, dl, VT,
6814 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006815
6816
Owen Anderson41b06652012-05-02 22:17:40 +00006817 return SDValue();
6818}
6819
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006820SDValue DAGCombiner::visitFDIV(SDNode *N) {
6821 SDValue N0 = N->getOperand(0);
6822 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006823 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6824 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006825 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006826 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006827
Dan Gohmana8665142007-06-25 16:23:39 +00006828 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006829 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006830 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006831 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006832 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006833
Nate Begeman569c4392006-01-18 22:35:16 +00006834 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006835 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006836 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006837
Duncan Sands2f1dc382012-04-08 18:08:12 +00006838 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006839 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006840 // Compute the reciprocal 1.0 / c2.
6841 APFloat N1APF = N1CFP->getValueAPF();
6842 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6843 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006844 // Only do the transform if the reciprocal is a legal fp immediate that
6845 // isn't too nasty (eg NaN, denormal, ...).
6846 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006847 (!LegalOperations ||
6848 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6849 // backend)... we should handle this gracefully after Legalize.
6850 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6851 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6852 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006853 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006854 DAG.getConstantFP(Recip, VT));
6855 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006856
Bill Wendling3dc5d242009-01-30 22:57:07 +00006857 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006858 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006859 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006860 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006861 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006862 // Both can be negated for free, check to see if at least one is cheaper
6863 // negated.
6864 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006865 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006866 GetNegatedExpression(N0, DAG, LegalOperations),
6867 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006868 }
6869 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006870
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006871 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006872}
6873
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006874SDValue DAGCombiner::visitFREM(SDNode *N) {
6875 SDValue N0 = N->getOperand(0);
6876 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006877 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6878 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006879 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006880
Nate Begeman569c4392006-01-18 22:35:16 +00006881 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006882 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006883 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006884
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006885 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006886}
6887
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006888SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6889 SDValue N0 = N->getOperand(0);
6890 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006891 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6892 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006893 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006894
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006895 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006896 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006897
Chris Lattner3bc40502006-03-05 05:30:57 +00006898 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006899 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006900 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6901 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006902 if (!V.isNegative()) {
6903 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006904 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006905 } else {
6906 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006907 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6908 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006909 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006910 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006911
Chris Lattner3bc40502006-03-05 05:30:57 +00006912 // copysign(fabs(x), y) -> copysign(x, y)
6913 // copysign(fneg(x), y) -> copysign(x, y)
6914 // copysign(copysign(x,z), y) -> copysign(x, y)
6915 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6916 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006917 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006918 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006919
6920 // copysign(x, abs(y)) -> abs(x)
6921 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006922 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006923
Chris Lattner3bc40502006-03-05 05:30:57 +00006924 // copysign(x, copysign(y,z)) -> copysign(x, z)
6925 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006926 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006927 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006928
Chris Lattner3bc40502006-03-05 05:30:57 +00006929 // copysign(x, fp_extend(y)) -> copysign(x, y)
6930 // copysign(x, fp_round(y)) -> copysign(x, y)
6931 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006932 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006933 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006934
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006935 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006936}
6937
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006938SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6939 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006941 EVT VT = N->getValueType(0);
6942 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006943
Nate Begeman21158fc2005-09-01 00:19:25 +00006944 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006945 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006946 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006947 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006948 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006949 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006950
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006951 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6952 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006953 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6954 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006955 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006956 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006957 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006958 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006959
Alp Tokercb402912014-01-24 17:20:08 +00006960 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006961 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6962 // having to say they don't support SELECT_CC on every type the DAG knows
6963 // about, since there is no way to mark an opcode illegal at all value types
6964 // (See also visitSELECT)
6965 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6966 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6967 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6968 !VT.isVector() &&
6969 (!LegalOperations ||
6970 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6971 SDValue Ops[] =
6972 { N0.getOperand(0), N0.getOperand(1),
6973 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6974 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006975 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006976 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006977
Nadav Rotem90560762012-07-23 07:59:50 +00006978 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6979 // (select_cc x, y, 1.0, 0.0,, cc)
6980 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6981 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6982 (!LegalOperations ||
6983 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6984 SDValue Ops[] =
6985 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6986 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6987 N0.getOperand(0).getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006988 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006989 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006990 }
6991
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006992 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006993}
6994
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006995SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6996 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006997 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006998 EVT VT = N->getValueType(0);
6999 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007000
Nate Begeman21158fc2005-09-01 00:19:25 +00007001 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007002 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007003 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007004 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007005 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007006 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007007
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007008 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7009 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007010 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7011 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007012 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007013 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007014 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007015 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007016
Alp Tokercb402912014-01-24 17:20:08 +00007017 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00007018 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7019 // having to say they don't support SELECT_CC on every type the DAG knows
7020 // about, since there is no way to mark an opcode illegal at all value types
7021 // (See also visitSELECT)
7022 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7023 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007024
Nadav Rotem90560762012-07-23 07:59:50 +00007025 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7026 (!LegalOperations ||
7027 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7028 SDValue Ops[] =
7029 { N0.getOperand(0), N0.getOperand(1),
7030 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7031 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00007032 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00007033 }
7034 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007035
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007036 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007037}
7038
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007039SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7040 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007041 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007042 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007043
Nate Begeman21158fc2005-09-01 00:19:25 +00007044 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007045 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007046 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007047
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007048 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007049}
7050
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007051SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7052 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007053 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007054 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007055
Nate Begeman21158fc2005-09-01 00:19:25 +00007056 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007057 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007058 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007059
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007060 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007061}
7062
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007063SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7064 SDValue N0 = N->getOperand(0);
7065 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007066 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007067 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007068
Nate Begeman21158fc2005-09-01 00:19:25 +00007069 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007070 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007071 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007072
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007073 // fold (fp_round (fp_extend x)) -> x
7074 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7075 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007076
Chris Lattner0feb1b02008-01-24 06:45:35 +00007077 // fold (fp_round (fp_round x)) -> (fp_round x)
7078 if (N0.getOpcode() == ISD::FP_ROUND) {
7079 // This is a value preserving truncation if both round's are.
7080 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007081 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007082 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007083 DAG.getIntPtrConstant(IsTrunc));
7084 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007085
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007086 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007087 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007088 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007089 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007090 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007091 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007092 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007093 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007094
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007095 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007096}
7097
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007098SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7099 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007100 EVT VT = N->getValueType(0);
7101 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007103
Nate Begeman21158fc2005-09-01 00:19:25 +00007104 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007105 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007106 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007107 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007108 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007109
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007110 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007111}
7112
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007113SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7114 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007115 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007116 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007117
Chris Lattner5919b482007-12-29 06:55:23 +00007118 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007119 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007120 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007121 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007122
Nate Begeman21158fc2005-09-01 00:19:25 +00007123 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007124 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007125 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007126
7127 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7128 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007129 if (N0.getOpcode() == ISD::FP_ROUND
7130 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007131 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007132 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007133 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007134 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007135 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007136 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007137 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007138
Chris Lattner72733e52008-01-17 07:00:52 +00007139 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007140 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007141 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007142 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007143 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007144 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007145 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007146 LN0->getBasePtr(), N0.getValueType(),
7147 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007148 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007149 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007150 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007151 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007152 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007153 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007154 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007155
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007156 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007157}
7158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007159SDValue DAGCombiner::visitFNEG(SDNode *N) {
7160 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007161 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007162
Craig Topper82384612012-09-11 01:45:21 +00007163 if (VT.isVector()) {
7164 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7165 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007166 }
7167
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007168 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7169 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007170 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007171
Chris Lattner888560d2008-01-27 17:42:27 +00007172 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7173 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007174 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007175 !VT.isVector() &&
7176 N0.getNode()->hasOneUse() &&
7177 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007178 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007179 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007180 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007181 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007182 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007183 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007184 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007185 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007186 }
7187 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007188
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007189 // (fneg (fmul c, x)) -> (fmul -c, x)
7190 if (N0.getOpcode() == ISD::FMUL) {
7191 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Lin8e8424e2013-07-09 00:44:49 +00007192 if (CFP1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007193 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007194 N0.getOperand(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007195 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007196 N0.getOperand(1)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007197 }
7198
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007199 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007200}
7201
Owen Andersona40319b2012-08-13 23:32:49 +00007202SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7203 SDValue N0 = N->getOperand(0);
7204 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7205 EVT VT = N->getValueType(0);
7206
7207 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007208 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007209 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007210
7211 return SDValue();
7212}
7213
7214SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7215 SDValue N0 = N->getOperand(0);
7216 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7217 EVT VT = N->getValueType(0);
7218
7219 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007220 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007221 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007222
7223 return SDValue();
7224}
7225
7226SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7227 SDValue N0 = N->getOperand(0);
7228 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7229 EVT VT = N->getValueType(0);
7230
7231 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007232 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007233 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007234
7235 return SDValue();
7236}
7237
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007238SDValue DAGCombiner::visitFABS(SDNode *N) {
7239 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007240 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007241 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007242
Craig Topper82384612012-09-11 01:45:21 +00007243 if (VT.isVector()) {
7244 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7245 if (FoldedVOp.getNode()) return FoldedVOp;
7246 }
7247
Nate Begeman21158fc2005-09-01 00:19:25 +00007248 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007249 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007250 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007251 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007252 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007253 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007254 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007255 // fold (fabs (fcopysign x, y)) -> (fabs x)
7256 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007257 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007258
Chris Lattner888560d2008-01-27 17:42:27 +00007259 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7260 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007261 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007262 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007263 N0.getOperand(0).getValueType().isInteger() &&
7264 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007265 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007266 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007267 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007268 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007269 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007270 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007271 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007272 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007273 }
7274 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007275
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007276 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007277}
7278
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007279SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7280 SDValue Chain = N->getOperand(0);
7281 SDValue N1 = N->getOperand(1);
7282 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007283
Dan Gohman82e80012009-11-17 00:47:23 +00007284 // If N is a constant we could fold this into a fallthrough or unconditional
7285 // branch. However that doesn't happen very often in normal code, because
7286 // Instcombine/SimplifyCFG should have handled the available opportunities.
7287 // If we did this folding here, it would be necessary to update the
7288 // MachineBasicBlock CFG, which is awkward.
7289
Nate Begeman7e7f4392006-02-01 07:19:44 +00007290 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7291 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007292 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007293 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7294 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007295 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007296 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007297 N1.getOperand(0), N1.getOperand(1), N2);
7298 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007299
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007300 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7301 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7302 (N1.getOperand(0).hasOneUse() &&
7303 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7304 SDNode *Trunc = 0;
7305 if (N1.getOpcode() == ISD::TRUNCATE) {
7306 // Look pass the truncate.
7307 Trunc = N1.getNode();
7308 N1 = N1.getOperand(0);
7309 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007310
Bill Wendlingaa28be62009-03-26 06:14:09 +00007311 // Match this pattern so that we can generate simpler code:
7312 //
7313 // %a = ...
7314 // %b = and i32 %a, 2
7315 // %c = srl i32 %b, 1
7316 // brcond i32 %c ...
7317 //
7318 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007319 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007320 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007321 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007322 // %c = setcc eq %b, 0
7323 // brcond %c ...
7324 //
7325 // This applies only when the AND constant value has one bit set and the
7326 // SRL constant is equal to the log2 of the AND constant. The back-end is
7327 // smart enough to convert the result into a TEST/JMP sequence.
7328 SDValue Op0 = N1.getOperand(0);
7329 SDValue Op1 = N1.getOperand(1);
7330
7331 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007332 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007333 SDValue AndOp1 = Op0.getOperand(1);
7334
7335 if (AndOp1.getOpcode() == ISD::Constant) {
7336 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7337
7338 if (AndConst.isPowerOf2() &&
7339 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7340 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007341 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007342 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007343 Op0, DAG.getConstant(0, Op0.getValueType()),
7344 ISD::SETNE);
7345
Andrew Trickef9de2a2013-05-25 02:42:55 +00007346 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007347 MVT::Other, Chain, SetCC, N2);
7348 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7349 // will convert it back to (X & C1) >> C2.
7350 CombineTo(N, NewBRCond, false);
7351 // Truncate is dead.
7352 if (Trunc) {
7353 removeFromWorkList(Trunc);
7354 DAG.DeleteNode(Trunc);
7355 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007356 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007357 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007358 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007359 removeFromWorkList(N1.getNode());
7360 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007361 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007362 }
7363 }
7364 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007365
7366 if (Trunc)
7367 // Restore N1 if the above transformation doesn't match.
7368 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007369 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007370
Evan Cheng228c31f2010-02-27 07:36:59 +00007371 // Transform br(xor(x, y)) -> br(x != y)
7372 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7373 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7374 SDNode *TheXor = N1.getNode();
7375 SDValue Op0 = TheXor->getOperand(0);
7376 SDValue Op1 = TheXor->getOperand(1);
7377 if (Op0.getOpcode() == Op1.getOpcode()) {
7378 // Avoid missing important xor optimizations.
7379 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007380 if (Tmp.getNode()) {
7381 if (Tmp.getNode() != TheXor) {
7382 DEBUG(dbgs() << "\nReplacing.8 ";
7383 TheXor->dump(&DAG);
7384 dbgs() << "\nWith: ";
7385 Tmp.getNode()->dump(&DAG);
7386 dbgs() << '\n');
7387 WorkListRemover DeadNodes(*this);
7388 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7389 removeFromWorkList(TheXor);
7390 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007391 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007392 MVT::Other, Chain, Tmp, N2);
7393 }
7394
Benjamin Kramer93354432013-03-30 21:28:18 +00007395 // visitXOR has changed XOR's operands or replaced the XOR completely,
7396 // bail out.
7397 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007398 }
7399 }
7400
7401 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7402 bool Equal = false;
7403 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7404 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7405 Op0.getOpcode() == ISD::XOR) {
7406 TheXor = Op0.getNode();
7407 Equal = true;
7408 }
7409
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007410 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007411 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007412 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007413 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007414 SetCCVT,
7415 Op0, Op1,
7416 Equal ? ISD::SETEQ : ISD::SETNE);
7417 // Replace the uses of XOR with SETCC
7418 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007419 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007420 removeFromWorkList(N1.getNode());
7421 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007422 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007423 MVT::Other, Chain, SetCC, N2);
7424 }
7425 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007426
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007427 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007428}
7429
Chris Lattnera49e16f2005-10-05 06:47:48 +00007430// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7431//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007432SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007433 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007434 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007435
Dan Gohman82e80012009-11-17 00:47:23 +00007436 // If N is a constant we could fold this into a fallthrough or unconditional
7437 // branch. However that doesn't happen very often in normal code, because
7438 // Instcombine/SimplifyCFG should have handled the available opportunities.
7439 // If we did this folding here, it would be necessary to update the
7440 // MachineBasicBlock CFG, which is awkward.
7441
Duncan Sands93b66092008-06-09 11:32:28 +00007442 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007443 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007444 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007445 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007446 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007447
Nate Begemanbd7df032005-10-05 21:43:42 +00007448 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007449 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007450 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007451 N->getOperand(0), Simp.getOperand(2),
7452 Simp.getOperand(0), Simp.getOperand(1),
7453 N->getOperand(4));
7454
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007455 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007456}
7457
Evan Chengfa832632012-01-13 01:37:24 +00007458/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7459/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007460/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007461static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7462 SelectionDAG &DAG,
7463 const TargetLowering &TLI) {
7464 EVT VT;
7465 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7466 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7467 return false;
7468 VT = Use->getValueType(0);
7469 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7470 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7471 return false;
7472 VT = ST->getValue().getValueType();
7473 } else
7474 return false;
7475
Chandler Carruth95f83e02013-01-07 15:14:13 +00007476 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007477 if (N->getOpcode() == ISD::ADD) {
7478 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7479 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007480 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007481 AM.BaseOffs = Offset->getSExtValue();
7482 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007483 // [reg +/- reg]
7484 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007485 } else if (N->getOpcode() == ISD::SUB) {
7486 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7487 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007488 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007489 AM.BaseOffs = -Offset->getSExtValue();
7490 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007491 // [reg +/- reg]
7492 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007493 } else
7494 return false;
7495
7496 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7497}
7498
Duncan Sands075293f2008-06-15 20:12:31 +00007499/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7500/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007501/// and it has other uses besides the load / store. After the
7502/// transformation, the new indexed load / store has effectively folded
7503/// the add / subtract in and all of its other uses are redirected to the
7504/// new load / store.
7505bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007506 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007507 return false;
7508
7509 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007510 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007511 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007512 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007513 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007514 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007515 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007516 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007517 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7518 return false;
7519 Ptr = LD->getBasePtr();
7520 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007521 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007522 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007523 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007524 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7525 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7526 return false;
7527 Ptr = ST->getBasePtr();
7528 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007529 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007530 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007531 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007532
Chris Lattnereabc15c2006-11-11 00:56:29 +00007533 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7534 // out. There is no reason to make this a preinc/predec.
7535 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007536 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007537 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007538
Chris Lattnereabc15c2006-11-11 00:56:29 +00007539 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007540 SDValue BasePtr;
7541 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007542 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7543 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7544 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007545
7546 // Backends without true r+i pre-indexed forms may need to pass a
7547 // constant base with a variable offset so that constant coercion
7548 // will work with the patterns in canonical form.
7549 bool Swapped = false;
7550 if (isa<ConstantSDNode>(BasePtr)) {
7551 std::swap(BasePtr, Offset);
7552 Swapped = true;
7553 }
7554
Evan Cheng044a0a82007-05-03 23:52:19 +00007555 // Don't create a indexed load / store with zero offset.
7556 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007557 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007558 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007559
Chris Lattnera0a80032006-11-11 01:00:15 +00007560 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007561 // 1) The new base ptr is a frame index.
7562 // 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 +00007563 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007564 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007565 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007566 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007567
Chris Lattnera0a80032006-11-11 01:00:15 +00007568 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7569 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007570 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007571 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007572
Chris Lattnera0a80032006-11-11 01:00:15 +00007573 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007574 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007575 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007576 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007577 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007578 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007579
Hal Finkel25819052013-02-08 21:35:47 +00007580 // If the offset is a constant, there may be other adds of constants that
7581 // can be folded with this one. We should do this to avoid having to keep
7582 // a copy of the original base pointer.
7583 SmallVector<SDNode *, 16> OtherUses;
7584 if (isa<ConstantSDNode>(Offset))
7585 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7586 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7587 SDNode *Use = *I;
7588 if (Use == Ptr.getNode())
7589 continue;
7590
7591 if (Use->isPredecessorOf(N))
7592 continue;
7593
7594 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7595 OtherUses.clear();
7596 break;
7597 }
7598
7599 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7600 if (Op1.getNode() == BasePtr.getNode())
7601 std::swap(Op0, Op1);
7602 assert(Op0.getNode() == BasePtr.getNode() &&
7603 "Use of ADD/SUB but not an operand");
7604
7605 if (!isa<ConstantSDNode>(Op1)) {
7606 OtherUses.clear();
7607 break;
7608 }
7609
7610 // FIXME: In some cases, we can be smarter about this.
7611 if (Op1.getValueType() != Offset.getValueType()) {
7612 OtherUses.clear();
7613 break;
7614 }
7615
7616 OtherUses.push_back(Use);
7617 }
7618
7619 if (Swapped)
7620 std::swap(BasePtr, Offset);
7621
Evan Chenga4d187b2007-05-24 02:35:39 +00007622 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007623 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007624
7625 // Caches for hasPredecessorHelper
7626 SmallPtrSet<const SDNode *, 32> Visited;
7627 SmallVector<const SDNode *, 16> Worklist;
7628
Gabor Greiff304a7a2008-08-28 21:40:38 +00007629 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7630 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007631 SDNode *Use = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007632 if (Use == N)
7633 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007634 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007635 return false;
7636
Evan Chengfa832632012-01-13 01:37:24 +00007637 // If Ptr may be folded in addressing mode of other use, then it's
7638 // not profitable to do this transformation.
7639 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007640 RealUse = true;
7641 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007642
Chris Lattnereabc15c2006-11-11 00:56:29 +00007643 if (!RealUse)
7644 return false;
7645
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007646 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007647 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007648 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007649 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007650 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007651 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007652 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007653 ++PreIndexedNodes;
7654 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007655 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007656 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007657 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007658 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007659 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007660 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007661 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007662 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7663 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007664 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007665 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007666 }
7667
Chris Lattnereabc15c2006-11-11 00:56:29 +00007668 // Finally, since the node is now dead, remove it from the graph.
7669 DAG.DeleteNode(N);
7670
Hal Finkel25819052013-02-08 21:35:47 +00007671 if (Swapped)
7672 std::swap(BasePtr, Offset);
7673
7674 // Replace other uses of BasePtr that can be updated to use Ptr
7675 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7676 unsigned OffsetIdx = 1;
7677 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7678 OffsetIdx = 0;
7679 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7680 BasePtr.getNode() && "Expected BasePtr operand");
7681
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007682 // We need to replace ptr0 in the following expression:
7683 // x0 * offset0 + y0 * ptr0 = t0
7684 // knowing that
7685 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007686 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007687 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7688 // indexed load/store and the expresion that needs to be re-written.
7689 //
7690 // Therefore, we have:
7691 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007692
7693 ConstantSDNode *CN =
7694 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007695 int X0, X1, Y0, Y1;
7696 APInt Offset0 = CN->getAPIntValue();
7697 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007698
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007699 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7700 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7701 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7702 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007703
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007704 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7705
7706 APInt CNV = Offset0;
7707 if (X0 < 0) CNV = -CNV;
7708 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7709 else CNV = CNV - Offset1;
7710
7711 // We can now generate the new expression.
7712 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7713 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7714
7715 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007716 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007717 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7718 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7719 removeFromWorkList(OtherUses[i]);
7720 DAG.DeleteNode(OtherUses[i]);
7721 }
7722
Chris Lattnereabc15c2006-11-11 00:56:29 +00007723 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007724 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007725 removeFromWorkList(Ptr.getNode());
7726 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007727
7728 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007729}
7730
Duncan Sands075293f2008-06-15 20:12:31 +00007731/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007732/// add / sub of the base pointer node into a post-indexed load / store.
7733/// The transformation folded the add / subtract into the new indexed
7734/// load / store effectively and all of its uses are redirected to the
7735/// new load / store.
7736bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007737 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007738 return false;
7739
7740 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007741 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007742 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007743 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007744 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007745 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007746 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007747 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7748 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7749 return false;
7750 Ptr = LD->getBasePtr();
7751 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007752 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007753 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007754 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007755 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7756 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7757 return false;
7758 Ptr = ST->getBasePtr();
7759 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007760 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007761 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007762 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007763
Gabor Greiff304a7a2008-08-28 21:40:38 +00007764 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007765 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007766
Gabor Greiff304a7a2008-08-28 21:40:38 +00007767 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7768 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007769 SDNode *Op = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007770 if (Op == N ||
7771 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7772 continue;
7773
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007774 SDValue BasePtr;
7775 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007776 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7777 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007778 // Don't create a indexed load / store with zero offset.
7779 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007780 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007781 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007782
Chris Lattnereabc15c2006-11-11 00:56:29 +00007783 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007784 // 1) All uses are load / store ops that use it as base ptr (and
7785 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007786 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7787 // nor a successor of N. Otherwise, if Op is folded that would
7788 // create a cycle.
7789
Evan Chengcfc05132009-05-06 18:25:01 +00007790 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7791 continue;
7792
Chris Lattnereabc15c2006-11-11 00:56:29 +00007793 // Check for #1.
7794 bool TryNext = false;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007795 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7796 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007797 SDNode *Use = *II;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007798 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007799 continue;
7800
Chris Lattnereabc15c2006-11-11 00:56:29 +00007801 // If all the uses are load / store addresses, then don't do the
7802 // transformation.
7803 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7804 bool RealUse = false;
7805 for (SDNode::use_iterator III = Use->use_begin(),
7806 EEE = Use->use_end(); III != EEE; ++III) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007807 SDNode *UseUse = *III;
Stephen Lincfe7f352013-07-08 00:37:03 +00007808 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007809 RealUse = true;
7810 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007811
Chris Lattnereabc15c2006-11-11 00:56:29 +00007812 if (!RealUse) {
7813 TryNext = true;
7814 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007815 }
7816 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007817 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007818
Chris Lattnereabc15c2006-11-11 00:56:29 +00007819 if (TryNext)
7820 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007821
Chris Lattnereabc15c2006-11-11 00:56:29 +00007822 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007823 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007824 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007825 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007826 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007827 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007828 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007829 ++PostIndexedNodes;
7830 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007831 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007832 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007833 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007834 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007835 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007836 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007837 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007838 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7839 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007840 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007841 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007842 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007843
Chris Lattnereabc15c2006-11-11 00:56:29 +00007844 // Finally, since the node is now dead, remove it from the graph.
7845 DAG.DeleteNode(N);
7846
7847 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007848 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007849 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007850 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007851 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007852 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007853 }
7854 }
7855 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007856
Chris Lattnerffad2162006-11-11 00:39:41 +00007857 return false;
7858}
7859
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007860SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007861 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007862 SDValue Chain = LD->getChain();
7863 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007864
Evan Chenga684cd22007-05-01 00:38:21 +00007865 // If load is not volatile and there are no uses of the loaded value (and
7866 // the updated indexed value in case of indexed loads), change uses of the
7867 // chain value into uses of the chain input (i.e. delete the dead load).
7868 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007869 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007870 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007871 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007872 // It's not safe to use the two value CombineTo variant here. e.g.
7873 // v1, chain2 = load chain1, loc
7874 // v2, chain3 = load chain2, loc
7875 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007876 // Now we replace use of chain2 with chain1. This makes the second load
7877 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007878 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007879 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007880 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007881 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007882 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007883 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007884 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007885
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007886 if (N->use_empty()) {
7887 removeFromWorkList(N);
7888 DAG.DeleteNode(N);
7889 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007890
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007892 }
Evan Chengb68343c2007-05-01 08:53:39 +00007893 } else {
7894 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007895 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper0515cd42012-01-07 18:31:09 +00007896 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007897 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007898 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007899 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007900 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007901 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007902 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007903 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007904 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007905 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007906 DAG.getUNDEF(N->getValueType(1)));
7907 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007908 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007909 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007911 }
Evan Chenga684cd22007-05-01 00:38:21 +00007912 }
7913 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007914
Chris Lattnere260ed82005-10-10 22:04:48 +00007915 // If this load is directly stored, replace the load value with the stored
7916 // value.
7917 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007918 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007919 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007920 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007921 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7922 if (PrevST->getBasePtr() == Ptr &&
7923 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007924 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007925 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007926 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007927
Evan Cheng43cd9e32010-04-01 06:04:33 +00007928 // Try to infer better alignment information than the load already has.
7929 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007930 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007931 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7932 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007933 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007934 LD->getValueType(0),
7935 Chain, Ptr, LD->getPointerInfo(),
7936 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007937 LD->isVolatile(), LD->isNonTemporal(), Align,
7938 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007939 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7940 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007941 }
7942 }
7943
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007944 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7945 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00007946#ifndef NDEBUG
7947 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7948 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7949 UseAA = false;
7950#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00007951 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007952 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007953 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007954
Jim Laskey708d0db2006-10-04 16:53:27 +00007955 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007956 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007957 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007958
Jim Laskeyd07be232006-09-25 16:29:54 +00007959 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007960 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007961 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007962 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007963 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007964 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007965 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007966 BetterChain, Ptr, LD->getMemoryVT(),
7967 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007968 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007969
Jim Laskey708d0db2006-10-04 16:53:27 +00007970 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007971 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007972 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007973
Nate Begeman879d8f12009-09-15 00:18:30 +00007974 // Make sure the new and old chains are cleaned up.
7975 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007976
Jim Laskeydcf983c2006-10-13 23:32:28 +00007977 // Replace uses with load result and token factor. Don't add users
7978 // to work list.
7979 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00007980 }
7981 }
7982
Evan Cheng357017f2006-11-03 03:06:21 +00007983 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00007984 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007985 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00007986
Quentin Colombetde0e0622013-10-11 18:29:42 +00007987 // Try to slice up N to more direct loads if the slices are mapped to
7988 // different register banks or pairing can take place.
7989 if (SliceUpLoad(N))
7990 return SDValue(N, 0);
7991
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007992 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00007993}
7994
Quentin Colombetde0e0622013-10-11 18:29:42 +00007995namespace {
7996/// \brief Helper structure used to slice a load in smaller loads.
7997/// Basically a slice is obtained from the following sequence:
7998/// Origin = load Ty1, Base
7999/// Shift = srl Ty1 Origin, CstTy Amount
8000/// Inst = trunc Shift to Ty2
8001///
8002/// Then, it will be rewriten into:
8003/// Slice = load SliceTy, Base + SliceOffset
8004/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8005///
8006/// SliceTy is deduced from the number of bits that are actually used to
8007/// build Inst.
8008struct LoadedSlice {
8009 /// \brief Helper structure used to compute the cost of a slice.
8010 struct Cost {
8011 /// Are we optimizing for code size.
8012 bool ForCodeSize;
8013 /// Various cost.
8014 unsigned Loads;
8015 unsigned Truncates;
8016 unsigned CrossRegisterBanksCopies;
8017 unsigned ZExts;
8018 unsigned Shift;
8019
8020 Cost(bool ForCodeSize = false)
8021 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8022 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8023
8024 /// \brief Get the cost of one isolated slice.
8025 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8026 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8027 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8028 EVT TruncType = LS.Inst->getValueType(0);
8029 EVT LoadedType = LS.getLoadedType();
8030 if (TruncType != LoadedType &&
8031 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8032 ZExts = 1;
8033 }
8034
8035 /// \brief Account for slicing gain in the current cost.
8036 /// Slicing provide a few gains like removing a shift or a
8037 /// truncate. This method allows to grow the cost of the original
8038 /// load with the gain from this slice.
8039 void addSliceGain(const LoadedSlice &LS) {
8040 // Each slice saves a truncate.
8041 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8042 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8043 LS.Inst->getOperand(0).getValueType()))
8044 ++Truncates;
8045 // If there is a shift amount, this slice gets rid of it.
8046 if (LS.Shift)
8047 ++Shift;
8048 // If this slice can merge a cross register bank copy, account for it.
8049 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8050 ++CrossRegisterBanksCopies;
8051 }
8052
8053 Cost &operator+=(const Cost &RHS) {
8054 Loads += RHS.Loads;
8055 Truncates += RHS.Truncates;
8056 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8057 ZExts += RHS.ZExts;
8058 Shift += RHS.Shift;
8059 return *this;
8060 }
8061
8062 bool operator==(const Cost &RHS) const {
8063 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8064 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8065 ZExts == RHS.ZExts && Shift == RHS.Shift;
8066 }
8067
8068 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8069
8070 bool operator<(const Cost &RHS) const {
8071 // Assume cross register banks copies are as expensive as loads.
8072 // FIXME: Do we want some more target hooks?
8073 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8074 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8075 // Unless we are optimizing for code size, consider the
8076 // expensive operation first.
8077 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8078 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8079 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8080 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8081 }
8082
8083 bool operator>(const Cost &RHS) const { return RHS < *this; }
8084
8085 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8086
8087 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8088 };
8089 // The last instruction that represent the slice. This should be a
8090 // truncate instruction.
8091 SDNode *Inst;
8092 // The original load instruction.
8093 LoadSDNode *Origin;
8094 // The right shift amount in bits from the original load.
8095 unsigned Shift;
8096 // The DAG from which Origin came from.
8097 // This is used to get some contextual information about legal types, etc.
8098 SelectionDAG *DAG;
8099
8100 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8101 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8102 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8103
8104 LoadedSlice(const LoadedSlice &LS)
8105 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8106
8107 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8108 /// \return Result is \p BitWidth and has used bits set to 1 and
8109 /// not used bits set to 0.
8110 APInt getUsedBits() const {
8111 // Reproduce the trunc(lshr) sequence:
8112 // - Start from the truncated value.
8113 // - Zero extend to the desired bit width.
8114 // - Shift left.
8115 assert(Origin && "No original load to compare against.");
8116 unsigned BitWidth = Origin->getValueSizeInBits(0);
8117 assert(Inst && "This slice is not bound to an instruction");
8118 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8119 "Extracted slice is bigger than the whole type!");
8120 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8121 UsedBits.setAllBits();
8122 UsedBits = UsedBits.zext(BitWidth);
8123 UsedBits <<= Shift;
8124 return UsedBits;
8125 }
8126
8127 /// \brief Get the size of the slice to be loaded in bytes.
8128 unsigned getLoadedSize() const {
8129 unsigned SliceSize = getUsedBits().countPopulation();
8130 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8131 return SliceSize / 8;
8132 }
8133
8134 /// \brief Get the type that will be loaded for this slice.
8135 /// Note: This may not be the final type for the slice.
8136 EVT getLoadedType() const {
8137 assert(DAG && "Missing context");
8138 LLVMContext &Ctxt = *DAG->getContext();
8139 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8140 }
8141
8142 /// \brief Get the alignment of the load used for this slice.
8143 unsigned getAlignment() const {
8144 unsigned Alignment = Origin->getAlignment();
8145 unsigned Offset = getOffsetFromBase();
8146 if (Offset != 0)
8147 Alignment = MinAlign(Alignment, Alignment + Offset);
8148 return Alignment;
8149 }
8150
8151 /// \brief Check if this slice can be rewritten with legal operations.
8152 bool isLegal() const {
8153 // An invalid slice is not legal.
8154 if (!Origin || !Inst || !DAG)
8155 return false;
8156
8157 // Offsets are for indexed load only, we do not handle that.
8158 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8159 return false;
8160
8161 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8162
8163 // Check that the type is legal.
8164 EVT SliceType = getLoadedType();
8165 if (!TLI.isTypeLegal(SliceType))
8166 return false;
8167
8168 // Check that the load is legal for this type.
8169 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8170 return false;
8171
8172 // Check that the offset can be computed.
8173 // 1. Check its type.
8174 EVT PtrType = Origin->getBasePtr().getValueType();
8175 if (PtrType == MVT::Untyped || PtrType.isExtended())
8176 return false;
8177
8178 // 2. Check that it fits in the immediate.
8179 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8180 return false;
8181
8182 // 3. Check that the computation is legal.
8183 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8184 return false;
8185
8186 // Check that the zext is legal if it needs one.
8187 EVT TruncateType = Inst->getValueType(0);
8188 if (TruncateType != SliceType &&
8189 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8190 return false;
8191
8192 return true;
8193 }
8194
8195 /// \brief Get the offset in bytes of this slice in the original chunk of
8196 /// bits.
8197 /// \pre DAG != NULL.
8198 uint64_t getOffsetFromBase() const {
8199 assert(DAG && "Missing context.");
8200 bool IsBigEndian =
8201 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8202 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8203 uint64_t Offset = Shift / 8;
8204 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8205 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8206 "The size of the original loaded type is not a multiple of a"
8207 " byte.");
8208 // If Offset is bigger than TySizeInBytes, it means we are loading all
8209 // zeros. This should have been optimized before in the process.
8210 assert(TySizeInBytes > Offset &&
8211 "Invalid shift amount for given loaded size");
8212 if (IsBigEndian)
8213 Offset = TySizeInBytes - Offset - getLoadedSize();
8214 return Offset;
8215 }
8216
8217 /// \brief Generate the sequence of instructions to load the slice
8218 /// represented by this object and redirect the uses of this slice to
8219 /// this new sequence of instructions.
8220 /// \pre this->Inst && this->Origin are valid Instructions and this
8221 /// object passed the legal check: LoadedSlice::isLegal returned true.
8222 /// \return The last instruction of the sequence used to load the slice.
8223 SDValue loadSlice() const {
8224 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8225 const SDValue &OldBaseAddr = Origin->getBasePtr();
8226 SDValue BaseAddr = OldBaseAddr;
8227 // Get the offset in that chunk of bytes w.r.t. the endianess.
8228 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8229 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8230 if (Offset) {
8231 // BaseAddr = BaseAddr + Offset.
8232 EVT ArithType = BaseAddr.getValueType();
8233 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8234 DAG->getConstant(Offset, ArithType));
8235 }
8236
8237 // Create the type of the loaded slice according to its size.
8238 EVT SliceType = getLoadedType();
8239
8240 // Create the load for the slice.
8241 SDValue LastInst = DAG->getLoad(
8242 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8243 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8244 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8245 // If the final type is not the same as the loaded type, this means that
8246 // we have to pad with zero. Create a zero extend for that.
8247 EVT FinalType = Inst->getValueType(0);
8248 if (SliceType != FinalType)
8249 LastInst =
8250 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8251 return LastInst;
8252 }
8253
8254 /// \brief Check if this slice can be merged with an expensive cross register
8255 /// bank copy. E.g.,
8256 /// i = load i32
8257 /// f = bitcast i32 i to float
8258 bool canMergeExpensiveCrossRegisterBankCopy() const {
8259 if (!Inst || !Inst->hasOneUse())
8260 return false;
8261 SDNode *Use = *Inst->use_begin();
8262 if (Use->getOpcode() != ISD::BITCAST)
8263 return false;
8264 assert(DAG && "Missing context");
8265 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8266 EVT ResVT = Use->getValueType(0);
8267 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8268 const TargetRegisterClass *ArgRC =
8269 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8270 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8271 return false;
8272
8273 // At this point, we know that we perform a cross-register-bank copy.
8274 // Check if it is expensive.
8275 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8276 // Assume bitcasts are cheap, unless both register classes do not
8277 // explicitly share a common sub class.
8278 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8279 return false;
8280
8281 // Check if it will be merged with the load.
8282 // 1. Check the alignment constraint.
8283 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8284 ResVT.getTypeForEVT(*DAG->getContext()));
8285
8286 if (RequiredAlignment > getAlignment())
8287 return false;
8288
8289 // 2. Check that the load is a legal operation for that type.
8290 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8291 return false;
8292
8293 // 3. Check that we do not have a zext in the way.
8294 if (Inst->getValueType(0) != getLoadedType())
8295 return false;
8296
8297 return true;
8298 }
8299};
8300}
8301
Quentin Colombetde0e0622013-10-11 18:29:42 +00008302/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8303/// \p UsedBits looks like 0..0 1..1 0..0.
8304static bool areUsedBitsDense(const APInt &UsedBits) {
8305 // If all the bits are one, this is dense!
8306 if (UsedBits.isAllOnesValue())
8307 return true;
8308
8309 // Get rid of the unused bits on the right.
8310 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8311 // Get rid of the unused bits on the left.
8312 if (NarrowedUsedBits.countLeadingZeros())
8313 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8314 // Check that the chunk of bits is completely used.
8315 return NarrowedUsedBits.isAllOnesValue();
8316}
8317
8318/// \brief Check whether or not \p First and \p Second are next to each other
8319/// in memory. This means that there is no hole between the bits loaded
8320/// by \p First and the bits loaded by \p Second.
8321static bool areSlicesNextToEachOther(const LoadedSlice &First,
8322 const LoadedSlice &Second) {
8323 assert(First.Origin == Second.Origin && First.Origin &&
8324 "Unable to match different memory origins.");
8325 APInt UsedBits = First.getUsedBits();
8326 assert((UsedBits & Second.getUsedBits()) == 0 &&
8327 "Slices are not supposed to overlap.");
8328 UsedBits |= Second.getUsedBits();
8329 return areUsedBitsDense(UsedBits);
8330}
8331
8332/// \brief Adjust the \p GlobalLSCost according to the target
8333/// paring capabilities and the layout of the slices.
8334/// \pre \p GlobalLSCost should account for at least as many loads as
8335/// there is in the slices in \p LoadedSlices.
8336static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8337 LoadedSlice::Cost &GlobalLSCost) {
8338 unsigned NumberOfSlices = LoadedSlices.size();
8339 // If there is less than 2 elements, no pairing is possible.
8340 if (NumberOfSlices < 2)
8341 return;
8342
8343 // Sort the slices so that elements that are likely to be next to each
8344 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008345 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8346 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8347 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8348 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8349 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008350 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8351 // First (resp. Second) is the first (resp. Second) potentially candidate
8352 // to be placed in a paired load.
8353 const LoadedSlice *First = NULL;
8354 const LoadedSlice *Second = NULL;
8355 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8356 // Set the beginning of the pair.
8357 First = Second) {
8358
8359 Second = &LoadedSlices[CurrSlice];
8360
8361 // If First is NULL, it means we start a new pair.
8362 // Get to the next slice.
8363 if (!First)
8364 continue;
8365
8366 EVT LoadedType = First->getLoadedType();
8367
8368 // If the types of the slices are different, we cannot pair them.
8369 if (LoadedType != Second->getLoadedType())
8370 continue;
8371
8372 // Check if the target supplies paired loads for this type.
8373 unsigned RequiredAlignment = 0;
8374 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8375 // move to the next pair, this type is hopeless.
8376 Second = NULL;
8377 continue;
8378 }
8379 // Check if we meet the alignment requirement.
8380 if (RequiredAlignment > First->getAlignment())
8381 continue;
8382
8383 // Check that both loads are next to each other in memory.
8384 if (!areSlicesNextToEachOther(*First, *Second))
8385 continue;
8386
8387 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8388 --GlobalLSCost.Loads;
8389 // Move to the next pair.
8390 Second = NULL;
8391 }
8392}
8393
8394/// \brief Check the profitability of all involved LoadedSlice.
8395/// Currently, it is considered profitable if there is exactly two
8396/// involved slices (1) which are (2) next to each other in memory, and
8397/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8398///
8399/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8400/// the elements themselves.
8401///
8402/// FIXME: When the cost model will be mature enough, we can relax
8403/// constraints (1) and (2).
8404static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8405 const APInt &UsedBits, bool ForCodeSize) {
8406 unsigned NumberOfSlices = LoadedSlices.size();
8407 if (StressLoadSlicing)
8408 return NumberOfSlices > 1;
8409
8410 // Check (1).
8411 if (NumberOfSlices != 2)
8412 return false;
8413
8414 // Check (2).
8415 if (!areUsedBitsDense(UsedBits))
8416 return false;
8417
8418 // Check (3).
8419 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8420 // The original code has one big load.
8421 OrigCost.Loads = 1;
8422 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8423 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8424 // Accumulate the cost of all the slices.
8425 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8426 GlobalSlicingCost += SliceCost;
8427
8428 // Account as cost in the original configuration the gain obtained
8429 // with the current slices.
8430 OrigCost.addSliceGain(LS);
8431 }
8432
8433 // If the target supports paired load, adjust the cost accordingly.
8434 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8435 return OrigCost > GlobalSlicingCost;
8436}
8437
8438/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8439/// operations, split it in the various pieces being extracted.
8440///
8441/// This sort of thing is introduced by SROA.
8442/// This slicing takes care not to insert overlapping loads.
8443/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8444bool DAGCombiner::SliceUpLoad(SDNode *N) {
8445 if (Level < AfterLegalizeDAG)
8446 return false;
8447
8448 LoadSDNode *LD = cast<LoadSDNode>(N);
8449 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8450 !LD->getValueType(0).isInteger())
8451 return false;
8452
8453 // Keep track of already used bits to detect overlapping values.
8454 // In that case, we will just abort the transformation.
8455 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8456
8457 SmallVector<LoadedSlice, 4> LoadedSlices;
8458
8459 // Check if this load is used as several smaller chunks of bits.
8460 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8461 // of computation for each trunc.
8462 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8463 UI != UIEnd; ++UI) {
8464 // Skip the uses of the chain.
8465 if (UI.getUse().getResNo() != 0)
8466 continue;
8467
8468 SDNode *User = *UI;
8469 unsigned Shift = 0;
8470
8471 // Check if this is a trunc(lshr).
8472 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8473 isa<ConstantSDNode>(User->getOperand(1))) {
8474 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8475 User = *User->use_begin();
8476 }
8477
8478 // At this point, User is a Truncate, iff we encountered, trunc or
8479 // trunc(lshr).
8480 if (User->getOpcode() != ISD::TRUNCATE)
8481 return false;
8482
8483 // The width of the type must be a power of 2 and greater than 8-bits.
8484 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008485 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008486 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008487 unsigned Width = User->getValueSizeInBits(0);
8488 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8489 return 0;
8490
8491 // Build the slice for this chain of computations.
8492 LoadedSlice LS(User, LD, Shift, &DAG);
8493 APInt CurrentUsedBits = LS.getUsedBits();
8494
8495 // Check if this slice overlaps with another.
8496 if ((CurrentUsedBits & UsedBits) != 0)
8497 return false;
8498 // Update the bits used globally.
8499 UsedBits |= CurrentUsedBits;
8500
8501 // Check if the new slice would be legal.
8502 if (!LS.isLegal())
8503 return false;
8504
8505 // Record the slice.
8506 LoadedSlices.push_back(LS);
8507 }
8508
8509 // Abort slicing if it does not seem to be profitable.
8510 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8511 return false;
8512
8513 ++SlicedLoads;
8514
8515 // Rewrite each chain to use an independent load.
8516 // By construction, each chain can be represented by a unique load.
8517
8518 // Prepare the argument for the new token factor for all the slices.
8519 SmallVector<SDValue, 8> ArgChains;
8520 for (SmallVectorImpl<LoadedSlice>::const_iterator
8521 LSIt = LoadedSlices.begin(),
8522 LSItEnd = LoadedSlices.end();
8523 LSIt != LSItEnd; ++LSIt) {
8524 SDValue SliceInst = LSIt->loadSlice();
8525 CombineTo(LSIt->Inst, SliceInst, true);
8526 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8527 SliceInst = SliceInst.getOperand(0);
8528 assert(SliceInst->getOpcode() == ISD::LOAD &&
8529 "It takes more than a zext to get to the loaded slice!!");
8530 ArgChains.push_back(SliceInst.getValue(1));
8531 }
8532
8533 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8534 &ArgChains[0], ArgChains.size());
8535 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8536 return true;
8537}
8538
Chris Lattner4041ab62010-04-15 04:48:01 +00008539/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8540/// load is having specific bytes cleared out. If so, return the byte size
8541/// being masked out and the shift amount.
8542static std::pair<unsigned, unsigned>
8543CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8544 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008545
Chris Lattner4041ab62010-04-15 04:48:01 +00008546 // Check for the structure we're looking for.
8547 if (V->getOpcode() != ISD::AND ||
8548 !isa<ConstantSDNode>(V->getOperand(1)) ||
8549 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8550 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008551
Chris Lattner3245afd2010-04-15 06:10:49 +00008552 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008553 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008554 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008555
Chris Lattner3245afd2010-04-15 06:10:49 +00008556 // The store should be chained directly to the load or be an operand of a
8557 // tokenfactor.
8558 if (LD == Chain.getNode())
8559 ; // ok.
8560 else if (Chain->getOpcode() != ISD::TokenFactor)
8561 return Result; // Fail.
8562 else {
8563 bool isOk = false;
8564 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8565 if (Chain->getOperand(i).getNode() == LD) {
8566 isOk = true;
8567 break;
8568 }
8569 if (!isOk) return Result;
8570 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008571
Chris Lattner4041ab62010-04-15 04:48:01 +00008572 // This only handles simple types.
8573 if (V.getValueType() != MVT::i16 &&
8574 V.getValueType() != MVT::i32 &&
8575 V.getValueType() != MVT::i64)
8576 return Result;
8577
8578 // Check the constant mask. Invert it so that the bits being masked out are
8579 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8580 // follow the sign bit for uniformity.
8581 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008582 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008583 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008584 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008585 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8586 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008587
Chris Lattner4041ab62010-04-15 04:48:01 +00008588 // See if we have a continuous run of bits. If so, we have 0*1+0*
8589 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8590 return Result;
8591
8592 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8593 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8594 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008595
Chris Lattner4041ab62010-04-15 04:48:01 +00008596 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8597 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008598 case 1:
8599 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008600 case 4: break;
8601 default: return Result; // All one mask, or 5-byte mask.
8602 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008603
Chris Lattner4041ab62010-04-15 04:48:01 +00008604 // Verify that the first bit starts at a multiple of mask so that the access
8605 // is aligned the same as the access width.
8606 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008607
Chris Lattner4041ab62010-04-15 04:48:01 +00008608 Result.first = MaskedBytes;
8609 Result.second = NotMaskTZ/8;
8610 return Result;
8611}
8612
8613
8614/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8615/// provides a value as specified by MaskInfo. If so, replace the specified
8616/// store with a narrower store of truncated IVal.
8617static SDNode *
8618ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8619 SDValue IVal, StoreSDNode *St,
8620 DAGCombiner *DC) {
8621 unsigned NumBytes = MaskInfo.first;
8622 unsigned ByteShift = MaskInfo.second;
8623 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008624
Chris Lattner4041ab62010-04-15 04:48:01 +00008625 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8626 // that uses this. If not, this is not a replacement.
8627 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8628 ByteShift*8, (ByteShift+NumBytes)*8);
8629 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008630
Chris Lattner4041ab62010-04-15 04:48:01 +00008631 // Check that it is legal on the target to do this. It is legal if the new
8632 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8633 // legalization.
8634 MVT VT = MVT::getIntegerVT(NumBytes*8);
8635 if (!DC->isTypeLegal(VT))
8636 return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008637
Chris Lattner4041ab62010-04-15 04:48:01 +00008638 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8639 // shifted by ByteShift and truncated down to NumBytes.
8640 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008641 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008642 DAG.getConstant(ByteShift*8,
8643 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008644
8645 // Figure out the offset for the store and the alignment of the access.
8646 unsigned StOffset;
8647 unsigned NewAlign = St->getAlignment();
8648
8649 if (DAG.getTargetLoweringInfo().isLittleEndian())
8650 StOffset = ByteShift;
8651 else
8652 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008653
Chris Lattner4041ab62010-04-15 04:48:01 +00008654 SDValue Ptr = St->getBasePtr();
8655 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008656 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008657 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8658 NewAlign = MinAlign(NewAlign, StOffset);
8659 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008660
Chris Lattner4041ab62010-04-15 04:48:01 +00008661 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008662 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008663
Chris Lattner4041ab62010-04-15 04:48:01 +00008664 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008665 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008666 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008667 false, false, NewAlign).getNode();
8668}
8669
Evan Chenga9cda8a2009-05-28 00:35:15 +00008670
8671/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8672/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8673/// of the loaded bits, try narrowing the load and store if it would end up
8674/// being a win for performance or code size.
8675SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8676 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008677 if (ST->isVolatile())
8678 return SDValue();
8679
Evan Chenga9cda8a2009-05-28 00:35:15 +00008680 SDValue Chain = ST->getChain();
8681 SDValue Value = ST->getValue();
8682 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008683 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008684
8685 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008686 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008687
8688 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008689
Chris Lattner4041ab62010-04-15 04:48:01 +00008690 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8691 // is a byte mask indicating a consecutive number of bytes, check to see if
8692 // Y is known to provide just those bytes. If so, we try to replace the
8693 // load + replace + store sequence with a single (narrower) store, which makes
8694 // the load dead.
8695 if (Opc == ISD::OR) {
8696 std::pair<unsigned, unsigned> MaskedLoad;
8697 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8698 if (MaskedLoad.first)
8699 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8700 Value.getOperand(1), ST,this))
8701 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008702
Chris Lattner4041ab62010-04-15 04:48:01 +00008703 // Or is commutative, so try swapping X and Y.
8704 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8705 if (MaskedLoad.first)
8706 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8707 Value.getOperand(0), ST,this))
8708 return SDValue(NewST, 0);
8709 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008710
Evan Chenga9cda8a2009-05-28 00:35:15 +00008711 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8712 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008713 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008714
8715 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008716 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8717 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008718 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008719 if (LD->getBasePtr() != Ptr ||
8720 LD->getPointerInfo().getAddrSpace() !=
8721 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008722 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008723
8724 // Find the type to narrow it the load / op / store to.
8725 SDValue N1 = Value.getOperand(1);
8726 unsigned BitWidth = N1.getValueSizeInBits();
8727 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8728 if (Opc == ISD::AND)
8729 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008730 if (Imm == 0 || Imm.isAllOnesValue())
8731 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008732 unsigned ShAmt = Imm.countTrailingZeros();
8733 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8734 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008735 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008736 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008737 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008738 TLI.isNarrowingProfitable(VT, NewVT))) {
8739 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008740 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008741 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008742 if (NewBW >= BitWidth)
8743 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008744
8745 // If the lsb changed does not start at the type bitwidth boundary,
8746 // start at the previous one.
8747 if (ShAmt % NewBW)
8748 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008749 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8750 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008751 if ((Imm & Mask) == Imm) {
8752 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8753 if (Opc == ISD::AND)
8754 NewImm ^= APInt::getAllOnesValue(NewBW);
8755 uint64_t PtrOff = ShAmt / 8;
8756 // For big endian targets, we need to adjust the offset to the pointer to
8757 // load the correct bytes.
8758 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008759 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008760
8761 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008762 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008763 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008764 return SDValue();
8765
Andrew Trickef9de2a2013-05-25 02:42:55 +00008766 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008767 Ptr.getValueType(), Ptr,
8768 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008769 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008770 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008771 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008772 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008773 LD->isInvariant(), NewAlign,
8774 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008775 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008776 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008777 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008778 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008779 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008780 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008781
8782 AddToWorkList(NewPtr.getNode());
8783 AddToWorkList(NewLD.getNode());
8784 AddToWorkList(NewVal.getNode());
8785 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008786 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008787 ++OpsNarrowed;
8788 return NewST;
8789 }
8790 }
8791
Evan Cheng6673ff02009-05-28 18:41:02 +00008792 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008793}
8794
Evan Chengd42641c2011-02-02 01:06:55 +00008795/// TransformFPLoadStorePair - For a given floating point load / store pair,
8796/// if the load value isn't used by any other operations, then consider
8797/// transforming the pair to integer load / store operations if the target
8798/// deems the transformation profitable.
8799SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8800 StoreSDNode *ST = cast<StoreSDNode>(N);
8801 SDValue Chain = ST->getChain();
8802 SDValue Value = ST->getValue();
8803 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8804 Value.hasOneUse() &&
8805 Chain == SDValue(Value.getNode(), 1)) {
8806 LoadSDNode *LD = cast<LoadSDNode>(Value);
8807 EVT VT = LD->getMemoryVT();
8808 if (!VT.isFloatingPoint() ||
8809 VT != ST->getMemoryVT() ||
8810 LD->isNonTemporal() ||
8811 ST->isNonTemporal() ||
8812 LD->getPointerInfo().getAddrSpace() != 0 ||
8813 ST->getPointerInfo().getAddrSpace() != 0)
8814 return SDValue();
8815
8816 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8817 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8818 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8819 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8820 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8821 return SDValue();
8822
8823 unsigned LDAlign = LD->getAlignment();
8824 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008825 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008826 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008827 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8828 return SDValue();
8829
Andrew Trickef9de2a2013-05-25 02:42:55 +00008830 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008831 LD->getChain(), LD->getBasePtr(),
8832 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008833 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008834
Andrew Trickef9de2a2013-05-25 02:42:55 +00008835 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008836 NewLD, ST->getBasePtr(),
8837 ST->getPointerInfo(),
8838 false, false, STAlign);
8839
8840 AddToWorkList(NewLD.getNode());
8841 AddToWorkList(NewST.getNode());
8842 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008843 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008844 ++LdStFP2Int;
8845 return NewST;
8846 }
8847
8848 return SDValue();
8849}
8850
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008851/// Helper struct to parse and store a memory address as base + index + offset.
8852/// We ignore sign extensions when it is safe to do so.
8853/// The following two expressions are not equivalent. To differentiate we need
8854/// to store whether there was a sign extension involved in the index
8855/// computation.
8856/// (load (i64 add (i64 copyfromreg %c)
8857/// (i64 signextend (add (i8 load %index)
8858/// (i8 1))))
8859/// vs
8860///
8861/// (load (i64 add (i64 copyfromreg %c)
8862/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8863/// (i32 1)))))
8864struct BaseIndexOffset {
8865 SDValue Base;
8866 SDValue Index;
8867 int64_t Offset;
8868 bool IsIndexSignExt;
8869
8870 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8871
8872 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8873 bool IsIndexSignExt) :
8874 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8875
8876 bool equalBaseIndex(const BaseIndexOffset &Other) {
8877 return Other.Base == Base && Other.Index == Index &&
8878 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008879 }
8880
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008881 /// Parses tree in Ptr for base, index, offset addresses.
8882 static BaseIndexOffset match(SDValue Ptr) {
8883 bool IsIndexSignExt = false;
8884
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008885 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8886 // instruction, then it could be just the BASE or everything else we don't
8887 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008888 if (Ptr->getOpcode() != ISD::ADD)
8889 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8890
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008891 // We know that we have at least an ADD instruction. Try to pattern match
8892 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008893 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8894 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8895 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8896 IsIndexSignExt);
8897 }
8898
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008899 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008900 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008901 // (i64 add (i64 %array_ptr)
8902 // (i64 mul (i64 %induction_var)
8903 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008904 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008905 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008906
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008907 // Look at Base + Index + Offset cases.
8908 SDValue Base = Ptr->getOperand(0);
8909 SDValue IndexOffset = Ptr->getOperand(1);
8910
8911 // Skip signextends.
8912 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8913 IndexOffset = IndexOffset->getOperand(0);
8914 IsIndexSignExt = true;
8915 }
8916
8917 // Either the case of Base + Index (no offset) or something else.
8918 if (IndexOffset->getOpcode() != ISD::ADD)
8919 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8920
8921 // Now we have the case of Base + Index + offset.
8922 SDValue Index = IndexOffset->getOperand(0);
8923 SDValue Offset = IndexOffset->getOperand(1);
8924
8925 if (!isa<ConstantSDNode>(Offset))
8926 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8927
8928 // Ignore signextends.
8929 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8930 Index = Index->getOperand(0);
8931 IsIndexSignExt = true;
8932 } else IsIndexSignExt = false;
8933
8934 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8935 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8936 }
8937};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008938
8939/// Holds a pointer to an LSBaseSDNode as well as information on where it
8940/// is located in a sequence of memory operations connected by a chain.
8941struct MemOpLink {
8942 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8943 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8944 // Ptr to the mem node.
8945 LSBaseSDNode *MemNode;
8946 // Offset from the base ptr.
8947 int64_t OffsetFromBase;
8948 // What is the sequence number of this mem node.
8949 // Lowest mem operand in the DAG starts at zero.
8950 unsigned SequenceNum;
8951};
8952
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008953bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8954 EVT MemVT = St->getMemoryVT();
8955 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008956 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8957 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008958
8959 // Don't merge vectors into wider inputs.
8960 if (MemVT.isVector() || !MemVT.isSimple())
8961 return false;
8962
8963 // Perform an early exit check. Do not bother looking at stored values that
8964 // are not constants or loads.
8965 SDValue StoredVal = St->getValue();
8966 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8967 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8968 !IsLoadSrc)
8969 return false;
8970
8971 // Only look at ends of store sequences.
8972 SDValue Chain = SDValue(St, 1);
8973 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8974 return false;
8975
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008976 // This holds the base pointer, index, and the offset in bytes from the base
8977 // pointer.
8978 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008979
8980 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008981 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008982 return false;
8983
8984 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008985 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008986 return false;
8987
Nadav Rotem307d7672012-11-29 00:00:08 +00008988 // Save the LoadSDNodes that we find in the chain.
8989 // We need to make sure that these nodes do not interfere with
8990 // any of the store nodes.
8991 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8992
8993 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008994 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00008995
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008996 // Walk up the chain and look for nodes with offsets from the same
8997 // base pointer. Stop when reaching an instruction with a different kind
8998 // or instruction which has a different base pointer.
8999 unsigned Seq = 0;
9000 StoreSDNode *Index = St;
9001 while (Index) {
9002 // If the chain has more than one use, then we can't reorder the mem ops.
9003 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9004 break;
9005
9006 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009007 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009008
9009 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009010 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009011 break;
9012
9013 // Check that the alignment is the same.
9014 if (Index->getAlignment() != St->getAlignment())
9015 break;
9016
9017 // The memory operands must not be volatile.
9018 if (Index->isVolatile() || Index->isIndexed())
9019 break;
9020
9021 // No truncation.
9022 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9023 if (St->isTruncatingStore())
9024 break;
9025
9026 // The stored memory type must be the same.
9027 if (Index->getMemoryVT() != MemVT)
9028 break;
9029
9030 // We do not allow unaligned stores because we want to prevent overriding
9031 // stores.
9032 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9033 break;
9034
9035 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009036 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009037
Nadav Rotem307d7672012-11-29 00:00:08 +00009038 // Find the next memory operand in the chain. If the next operand in the
9039 // chain is a store then move up and continue the scan with the next
9040 // memory operand. If the next operand is a load save it and use alias
9041 // information to check if it interferes with anything.
9042 SDNode *NextInChain = Index->getChain().getNode();
9043 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009044 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009045 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009046 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009047 break;
9048 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009049 if (Ldn->isVolatile()) {
9050 Index = NULL;
9051 break;
9052 }
9053
Nadav Rotem307d7672012-11-29 00:00:08 +00009054 // Save the load node for later. Continue the scan.
9055 AliasLoadNodes.push_back(Ldn);
9056 NextInChain = Ldn->getChain().getNode();
9057 continue;
9058 } else {
9059 Index = NULL;
9060 break;
9061 }
9062 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009063 }
9064
9065 // Check if there is anything to merge.
9066 if (StoreNodes.size() < 2)
9067 return false;
9068
9069 // Sort the memory operands according to their distance from the base pointer.
9070 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009071 [](MemOpLink LHS, MemOpLink RHS) {
9072 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9073 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9074 LHS.SequenceNum > RHS.SequenceNum);
9075 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009076
9077 // Scan the memory operations on the chain and find the first non-consecutive
9078 // store memory address.
9079 unsigned LastConsecutiveStore = 0;
9080 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009081 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9082
9083 // Check that the addresses are consecutive starting from the second
9084 // element in the list of stores.
9085 if (i > 0) {
9086 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9087 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9088 break;
9089 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009090
Nadav Rotem307d7672012-11-29 00:00:08 +00009091 bool Alias = false;
9092 // Check if this store interferes with any of the loads that we found.
9093 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9094 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9095 Alias = true;
9096 break;
9097 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009098 // We found a load that alias with this store. Stop the sequence.
9099 if (Alias)
9100 break;
9101
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009102 // Mark this node as useful.
9103 LastConsecutiveStore = i;
9104 }
9105
9106 // The node with the lowest store address.
9107 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9108
9109 // Store the constants into memory as one consecutive store.
9110 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009111 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009112 unsigned LastLegalVectorType = 0;
9113 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009114 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9115 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9116 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009117
9118 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009119 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009120 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009121 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009122 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009123 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009124 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009125 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009126
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009127 // Find a legal type for the constant store.
9128 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9129 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9130 if (TLI.isTypeLegal(StoreTy))
9131 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009132 // Or check whether a truncstore is legal.
9133 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9134 TargetLowering::TypePromoteInteger) {
9135 EVT LegalizedStoredValueTy =
9136 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9137 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9138 LastLegalType = i+1;
9139 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009140
9141 // Find a legal type for the vector store.
9142 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9143 if (TLI.isTypeLegal(Ty))
9144 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009145 }
9146
Bob Wilson3365b802012-12-20 01:36:20 +00009147 // We only use vectors if the constant is known to be zero and the
9148 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009149 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009150 LastLegalVectorType = 0;
9151
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009152 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009153 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009154 return false;
9155
Nadav Rotem495b1a42013-02-14 18:28:52 +00009156 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009157 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9158
9159 // Make sure we have something to merge.
9160 if (NumElem < 2)
9161 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009162
9163 unsigned EarliestNodeUsed = 0;
9164 for (unsigned i=0; i < NumElem; ++i) {
9165 // Find a chain for the new wide-store operand. Notice that some
9166 // of the store nodes that we found may not be selected for inclusion
9167 // in the wide store. The chain we use needs to be the chain of the
9168 // earliest store node which is *used* and replaced by the wide store.
9169 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9170 EarliestNodeUsed = i;
9171 }
9172
9173 // The earliest Node in the DAG.
9174 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009175 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009176
Nadav Rotemb27777f2012-10-04 22:35:15 +00009177 SDValue StoredVal;
9178 if (UseVector) {
9179 // Find a legal type for the vector store.
9180 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9181 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9182 StoredVal = DAG.getConstant(0, Ty);
9183 } else {
9184 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9185 APInt StoreInt(StoreBW, 0);
9186
9187 // Construct a single integer constant which is made of the smaller
9188 // constant inputs.
9189 bool IsLE = TLI.isLittleEndian();
9190 for (unsigned i = 0; i < NumElem ; ++i) {
9191 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9192 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9193 SDValue Val = St->getValue();
9194 StoreInt<<=ElementSizeBytes*8;
9195 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9196 StoreInt|=C->getAPIntValue().zext(StoreBW);
9197 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9198 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9199 } else {
9200 assert(false && "Invalid constant element type");
9201 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009202 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009203
9204 // Create the new Load and Store operations.
9205 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9206 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009207 }
9208
Nadav Rotemb27777f2012-10-04 22:35:15 +00009209 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009210 FirstInChain->getBasePtr(),
9211 FirstInChain->getPointerInfo(),
9212 false, false,
9213 FirstInChain->getAlignment());
9214
9215 // Replace the first store with the new store
9216 CombineTo(EarliestOp, NewStore);
9217 // Erase all other stores.
9218 for (unsigned i = 0; i < NumElem ; ++i) {
9219 if (StoreNodes[i].MemNode == EarliestOp)
9220 continue;
9221 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009222 // ReplaceAllUsesWith will replace all uses that existed when it was
9223 // called, but graph optimizations may cause new ones to appear. For
9224 // example, the case in pr14333 looks like
9225 //
9226 // St's chain -> St -> another store -> X
9227 //
9228 // And the only difference from St to the other store is the chain.
9229 // When we change it's chain to be St's chain they become identical,
9230 // get CSEed and the net result is that X is now a use of St.
9231 // Since we know that St is redundant, just iterate.
9232 while (!St->use_empty())
9233 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009234 removeFromWorkList(St);
9235 DAG.DeleteNode(St);
9236 }
9237
9238 return true;
9239 }
9240
9241 // Below we handle the case of multiple consecutive stores that
9242 // come from multiple consecutive loads. We merge them into a single
9243 // wide load and a single wide store.
9244
9245 // Look for load nodes which are used by the stored values.
9246 SmallVector<MemOpLink, 8> LoadNodes;
9247
9248 // Find acceptable loads. Loads need to have the same chain (token factor),
9249 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009250 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009251 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9252 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9253 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9254 if (!Ld) break;
9255
9256 // Loads must only have one use.
9257 if (!Ld->hasNUsesOfValue(1, 0))
9258 break;
9259
9260 // Check that the alignment is the same as the stores.
9261 if (Ld->getAlignment() != St->getAlignment())
9262 break;
9263
9264 // The memory operands must not be volatile.
9265 if (Ld->isVolatile() || Ld->isIndexed())
9266 break;
9267
9268 // We do not accept ext loads.
9269 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9270 break;
9271
9272 // The stored memory type must be the same.
9273 if (Ld->getMemoryVT() != MemVT)
9274 break;
9275
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009276 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009277 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009278 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009279 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009280 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009281 break;
9282 } else {
9283 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009284 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009285 }
9286
9287 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009288 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009289 }
9290
9291 if (LoadNodes.size() < 2)
9292 return false;
9293
9294 // Scan the memory operations on the chain and find the first non-consecutive
9295 // load memory address. These variables hold the index in the store node
9296 // array.
9297 unsigned LastConsecutiveLoad = 0;
9298 // This variable refers to the size and not index in the array.
9299 unsigned LastLegalVectorType = 0;
9300 unsigned LastLegalIntegerType = 0;
9301 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009302 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9303 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9304 // All loads much share the same chain.
9305 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9306 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009307
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009308 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9309 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9310 break;
9311 LastConsecutiveLoad = i;
9312
9313 // Find a legal type for the vector store.
9314 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9315 if (TLI.isTypeLegal(StoreTy))
9316 LastLegalVectorType = i + 1;
9317
9318 // Find a legal type for the integer store.
9319 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9320 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9321 if (TLI.isTypeLegal(StoreTy))
9322 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009323 // Or check whether a truncstore and extload is legal.
9324 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9325 TargetLowering::TypePromoteInteger) {
9326 EVT LegalizedStoredValueTy =
9327 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9328 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9329 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9330 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9331 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9332 LastLegalIntegerType = i+1;
9333 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009334 }
9335
9336 // Only use vector types if the vector type is larger than the integer type.
9337 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009338 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009339 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9340
9341 // We add +1 here because the LastXXX variables refer to location while
9342 // the NumElem refers to array/index size.
9343 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9344 NumElem = std::min(LastLegalType, NumElem);
9345
9346 if (NumElem < 2)
9347 return false;
9348
9349 // The earliest Node in the DAG.
9350 unsigned EarliestNodeUsed = 0;
9351 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9352 for (unsigned i=1; i<NumElem; ++i) {
9353 // Find a chain for the new wide-store operand. Notice that some
9354 // of the store nodes that we found may not be selected for inclusion
9355 // in the wide store. The chain we use needs to be the chain of the
9356 // earliest store node which is *used* and replaced by the wide store.
9357 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9358 EarliestNodeUsed = i;
9359 }
9360
9361 // Find if it is better to use vectors or integers to load and store
9362 // to memory.
9363 EVT JointMemOpVT;
9364 if (UseVectorTy) {
9365 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9366 } else {
9367 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9368 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9369 }
9370
Andrew Trickef9de2a2013-05-25 02:42:55 +00009371 SDLoc LoadDL(LoadNodes[0].MemNode);
9372 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009373
9374 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9375 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9376 FirstLoad->getChain(),
9377 FirstLoad->getBasePtr(),
9378 FirstLoad->getPointerInfo(),
9379 false, false, false,
9380 FirstLoad->getAlignment());
9381
9382 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9383 FirstInChain->getBasePtr(),
9384 FirstInChain->getPointerInfo(), false, false,
9385 FirstInChain->getAlignment());
9386
Nadav Rotemac920662012-10-03 19:30:31 +00009387 // Replace one of the loads with the new load.
9388 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9389 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9390 SDValue(NewLoad.getNode(), 1));
9391
9392 // Remove the rest of the load chains.
9393 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009394 // Replace all chain users of the old load nodes with the chain of the new
9395 // load node.
9396 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009397 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9398 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009399
Nadav Rotemac920662012-10-03 19:30:31 +00009400 // Replace the first store with the new store.
9401 CombineTo(EarliestOp, NewStore);
9402 // Erase all other stores.
9403 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009404 // Remove all Store nodes.
9405 if (StoreNodes[i].MemNode == EarliestOp)
9406 continue;
9407 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9408 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9409 removeFromWorkList(St);
9410 DAG.DeleteNode(St);
9411 }
9412
9413 return true;
9414}
9415
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009416SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009417 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009418 SDValue Chain = ST->getChain();
9419 SDValue Value = ST->getValue();
9420 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009421
Evan Chenga4cf58a2007-05-07 21:27:48 +00009422 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009423 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009424 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009425 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009426 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009427 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009428 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009429 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009430 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009431 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009432 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009433 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009434 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009435 ST->isNonTemporal(), OrigAlign,
9436 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009437 }
Owen Andersona5192842011-04-14 17:30:49 +00009438
Chris Lattner41c80e82011-04-09 02:32:02 +00009439 // Turn 'store undef, Ptr' -> nothing.
9440 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9441 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009442
Nate Begeman8e20c762006-12-11 02:23:46 +00009443 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009444 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009445 // NOTE: If the original store is volatile, this transform must not increase
9446 // the number of stores. For example, on x86-32 an f64 can be stored in one
9447 // processor operation but an i64 (which is not legal) requires two. So the
9448 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009449 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009450 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009451 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009452 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009453 case MVT::f16: // We don't do this for these yet.
9454 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009455 case MVT::f128:
9456 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009457 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009458 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009459 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009460 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009461 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009462 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009463 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009464 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009465 }
9466 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009467 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009468 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009469 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009470 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009471 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009472 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009473 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009474 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009475 }
Owen Andersona5192842011-04-14 17:30:49 +00009476
Chris Lattner41c80e82011-04-09 02:32:02 +00009477 if (!ST->isVolatile() &&
9478 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009479 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009480 // argument passing. Since this is so common, custom legalize the
9481 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009482 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009483 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9484 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009485 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009486
Dan Gohman2af30632007-07-09 22:18:38 +00009487 unsigned Alignment = ST->getAlignment();
9488 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009489 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009490 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009491
Andrew Trickef9de2a2013-05-25 02:42:55 +00009492 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009493 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009494 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009495 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009496 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009497 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009498 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009499 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009500 Ptr, ST->getPointerInfo().getWithOffset(4),
9501 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009502 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009503 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009504 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009505 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009506
Chris Lattnerb7524b62006-12-12 04:16:14 +00009507 break;
Evan Cheng21836982006-12-11 17:25:19 +00009508 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009509 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009510 }
9511
Evan Cheng43cd9e32010-04-01 06:04:33 +00009512 // Try to infer better alignment information than the store already has.
9513 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009514 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9515 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009516 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009517 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009518 ST->isVolatile(), ST->isNonTemporal(), Align,
9519 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009520 }
9521 }
9522
Evan Chengd42641c2011-02-02 01:06:55 +00009523 // Try transforming a pair floating point load / store ops to integer
9524 // load / store ops.
9525 SDValue NewST = TransformFPLoadStorePair(N);
9526 if (NewST.getNode())
9527 return NewST;
9528
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009529 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9530 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009531#ifndef NDEBUG
9532 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9533 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9534 UseAA = false;
9535#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009536 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009537 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009538 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009539
Jim Laskey708d0db2006-10-04 16:53:27 +00009540 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009541 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009542 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009543
9544 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009545 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009546 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009547 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009548 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009549 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009550 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009551 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009552
Jim Laskeyd07be232006-09-25 16:29:54 +00009553 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009554 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009555 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009556
Nate Begeman879d8f12009-09-15 00:18:30 +00009557 // Make sure the new and old chains are cleaned up.
9558 AddToWorkList(Token.getNode());
9559
Jim Laskeydcf983c2006-10-13 23:32:28 +00009560 // Don't add users to work list.
9561 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009562 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009563 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009564
Evan Cheng33157702006-11-05 09:31:14 +00009565 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009566 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009567 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009568
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009569 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009570 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009571 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009572 // See if we can simplify the input to this truncstore with knowledge that
9573 // only the low bits are being used. For example:
9574 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009575 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009576 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009577 APInt::getLowBitsSet(
9578 Value.getValueType().getScalarType().getSizeInBits(),
9579 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009580 AddToWorkList(Value.getNode());
9581 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009582 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009583 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009584
Chris Lattnerf47e3062007-10-13 06:58:48 +00009585 // Otherwise, see if we can simplify the operation with
9586 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009587 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009588 APInt::getLowBitsSet(
9589 Value.getValueType().getScalarType().getSizeInBits(),
9590 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009591 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009592 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009593
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009594 // If this is a load followed by a store to the same location, then the store
9595 // is dead/noop.
9596 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009597 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009598 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009599 // There can't be any side effects between the load and store, such as
9600 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009601 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009602 // The store is dead, remove it.
9603 return Chain;
9604 }
9605 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009606
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009607 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9608 // truncating store. We can do this even if this is already a truncstore.
9609 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009610 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009611 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009612 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009613 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009614 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009615 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009616
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009617 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009618 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009619 if (!LegalTypes) {
9620 bool EverChanged = false;
9621
9622 do {
9623 // There can be multiple store sequences on the same chain.
9624 // Keep trying to merge store sequences until we are unable to do so
9625 // or until we merge the last store on the chain.
9626 bool Changed = MergeConsecutiveStores(ST);
9627 EverChanged |= Changed;
9628 if (!Changed) break;
9629 } while (ST->getOpcode() != ISD::DELETED_NODE);
9630
9631 if (EverChanged)
9632 return SDValue(N, 0);
9633 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009634
Evan Chenga9cda8a2009-05-28 00:35:15 +00009635 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009636}
9637
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009638SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9639 SDValue InVec = N->getOperand(0);
9640 SDValue InVal = N->getOperand(1);
9641 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009642 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009643
Bob Wilson42603952010-05-19 23:42:58 +00009644 // If the inserted element is an UNDEF, just use the input vector.
9645 if (InVal.getOpcode() == ISD::UNDEF)
9646 return InVec;
9647
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009648 EVT VT = InVec.getValueType();
9649
Owen Andersonb2c80da2011-02-25 21:41:48 +00009650 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009651 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9652 return SDValue();
9653
Eli Friedmanb7910b72011-09-09 21:04:06 +00009654 // Check that we know which element is being inserted
9655 if (!isa<ConstantSDNode>(EltNo))
9656 return SDValue();
9657 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009658
Eli Friedmanb7910b72011-09-09 21:04:06 +00009659 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9660 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9661 // vector elements.
9662 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009663 // Do not combine these two vectors if the output vector will not replace
9664 // the input vector.
9665 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009666 Ops.append(InVec.getNode()->op_begin(),
9667 InVec.getNode()->op_end());
9668 } else if (InVec.getOpcode() == ISD::UNDEF) {
9669 unsigned NElts = VT.getVectorNumElements();
9670 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9671 } else {
9672 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009673 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009674
9675 // Insert the element
9676 if (Elt < Ops.size()) {
9677 // All the operands of BUILD_VECTOR must have the same type;
9678 // we enforce that here.
9679 EVT OpVT = Ops[0].getValueType();
9680 if (InVal.getValueType() != OpVT)
9681 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9682 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9683 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9684 Ops[Elt] = InVal;
9685 }
9686
9687 // Return the new vector
9688 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9689 VT, &Ops[0], Ops.size());
Chris Lattner5336a592006-03-19 01:27:56 +00009690}
9691
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009692SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009693 // (vextract (scalar_to_vector val, 0) -> val
9694 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009695 EVT VT = InVec.getValueType();
9696 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009697
Duncan Sands6be291a2011-05-09 08:03:33 +00009698 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9699 // Check if the result type doesn't match the inserted element type. A
9700 // SCALAR_TO_VECTOR may truncate the inserted element and the
9701 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9702 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009703 if (InOp.getValueType() != NVT) {
9704 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009705 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009706 }
9707 return InOp;
9708 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009709
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009710 SDValue EltNo = N->getOperand(1);
9711 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9712
9713 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9714 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009715 // we may introduce new vector instructions which are not backed by TD
9716 // patterns. For example on AVX, extracting elements from a wide vector
9717 // without using extract_subvector.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009718 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9719 && ConstEltNo && !LegalOperations) {
9720 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9721 int NumElem = VT.getVectorNumElements();
9722 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9723 // Find the new index to extract from.
9724 int OrigElt = SVOp->getMaskElt(Elt);
9725
9726 // Extracting an undef index is undef.
9727 if (OrigElt == -1)
9728 return DAG.getUNDEF(NVT);
9729
9730 // Select the right vector half to extract from.
9731 if (OrigElt < NumElem) {
9732 InVec = InVec->getOperand(0);
9733 } else {
9734 InVec = InVec->getOperand(1);
9735 OrigElt -= NumElem;
9736 }
9737
Tom Stellardd42c5942013-08-05 22:22:01 +00009738 EVT IndexTy = TLI.getVectorIdxTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009739 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00009740 InVec, DAG.getConstant(OrigElt, IndexTy));
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009741 }
9742
Evan Cheng1120279a2008-05-13 08:35:03 +00009743 // Perform only after legalization to ensure build_vector / vector_shuffle
9744 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009745 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009746
Mon P Wangca6d6de2009-01-17 00:07:25 +00009747 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9748 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9749 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009750
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009751 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009752 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009753 bool NewLoad = false;
Mon P Wangb5eb7202008-12-11 00:26:16 +00009754 bool BCNumEltsChanged = false;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009755 EVT ExtVT = VT.getVectorElementType();
9756 EVT LVT = ExtVT;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009757
Evan Cheng7bf83092012-03-13 22:00:52 +00009758 // If the result of load has to be truncated, then it's not necessarily
9759 // profitable.
Evan Chengd5f8e572012-03-13 22:16:11 +00009760 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng7bf83092012-03-13 22:00:52 +00009761 return SDValue();
9762
Wesley Peck527da1b2010-11-23 03:31:01 +00009763 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009764 // Don't duplicate a load with other uses.
9765 if (!InVec.hasOneUse())
9766 return SDValue();
9767
Owen Anderson53aa7a92009-08-10 22:56:29 +00009768 EVT BCVT = InVec.getOperand(0).getValueType();
9769 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009770 return SDValue();
Mon P Wangb5eb7202008-12-11 00:26:16 +00009771 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9772 BCNumEltsChanged = true;
Evan Cheng1120279a2008-05-13 08:35:03 +00009773 InVec = InVec.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009774 ExtVT = BCVT.getVectorElementType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009775 NewLoad = true;
9776 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009777
Evan Cheng1120279a2008-05-13 08:35:03 +00009778 LoadSDNode *LN0 = NULL;
Nate Begeman5f829d82009-04-29 05:20:52 +00009779 const ShuffleVectorSDNode *SVN = NULL;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009780 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009781 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009782 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009783 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009784 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009785 // Don't duplicate a load with other uses.
9786 if (!InVec.hasOneUse())
9787 return SDValue();
9788
Evan Cheng1120279a2008-05-13 08:35:03 +00009789 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009790 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009791 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9792 // =>
9793 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009794
Eli Friedmane96286c2011-12-26 22:49:32 +00009795 // Don't duplicate a load with other uses.
9796 if (!InVec.hasOneUse())
9797 return SDValue();
9798
Mon P Wangb5eb7202008-12-11 00:26:16 +00009799 // If the bit convert changed the number of elements, it is unsafe
9800 // to examine the mask.
9801 if (BCNumEltsChanged)
9802 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009803
9804 // Select the input vector, guarding against out of range extract vector.
9805 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009806 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009807 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9808
Eli Friedmane96286c2011-12-26 22:49:32 +00009809 if (InVec.getOpcode() == ISD::BITCAST) {
9810 // Don't duplicate a load with other uses.
9811 if (!InVec.hasOneUse())
9812 return SDValue();
9813
Evan Cheng1120279a2008-05-13 08:35:03 +00009814 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009815 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009816 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009817 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009818 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009819 }
9820 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009821
Eli Friedmane96286c2011-12-26 22:49:32 +00009822 // Make sure we found a non-volatile load and the extractelement is
9823 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009824 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009825 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009826
Eric Christopherc6418b12010-11-03 20:44:42 +00009827 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9828 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009829 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009830
Evan Cheng1120279a2008-05-13 08:35:03 +00009831 unsigned Align = LN0->getAlignment();
9832 if (NewLoad) {
9833 // Check the resultant load doesn't need a higher alignment than the
9834 // original load.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009835 unsigned NewAlign =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009836 TLI.getDataLayout()
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009837 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendling27d9dd42009-01-30 23:36:47 +00009838
Dan Gohman4aa18462009-01-28 17:46:25 +00009839 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009840 return SDValue();
Bill Wendling27d9dd42009-01-30 23:36:47 +00009841
Evan Cheng1120279a2008-05-13 08:35:03 +00009842 Align = NewAlign;
9843 }
9844
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009845 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009846 unsigned PtrOff = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00009847
Eric Christopherc6418b12010-11-03 20:44:42 +00009848 if (Elt) {
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009849 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009850 EVT PtrType = NewPtr.getValueType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009851 if (TLI.isBigEndian())
Duncan Sands13237ac2008-06-06 12:08:01 +00009852 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009853 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng1120279a2008-05-13 08:35:03 +00009854 DAG.getConstant(PtrOff, PtrType));
9855 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009856
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009857 // The replacement we need to do here is a little tricky: we need to
9858 // replace an extractelement of a load with a load.
9859 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmane96286c2011-12-26 22:49:32 +00009860 // Note that this replacement assumes that the extractvalue is the only
9861 // use of the load; that's okay because we don't want to perform this
9862 // transformation in other cases anyway.
Evan Cheng7bf83092012-03-13 22:00:52 +00009863 SDValue Load;
Evan Chengd5f8e572012-03-13 22:16:11 +00009864 SDValue Chain;
Evan Cheng7bf83092012-03-13 22:00:52 +00009865 if (NVT.bitsGT(LVT)) {
9866 // If the result type of vextract is wider than the load, then issue an
9867 // extending load instead.
9868 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9869 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009870 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng7bf83092012-03-13 22:00:52 +00009871 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009872 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9873 Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009874 Chain = Load.getValue(1);
9875 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009876 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng7bf83092012-03-13 22:00:52 +00009877 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lincfe7f352013-07-08 00:37:03 +00009878 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009879 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009880 Chain = Load.getValue(1);
9881 if (NVT.bitsLT(LVT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009882 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009883 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009884 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009885 }
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009886 WorkListRemover DeadNodes(*this);
9887 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chengd5f8e572012-03-13 22:16:11 +00009888 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009889 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009890 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9891 // worklist explicitly as well.
9892 AddToWorkList(Load.getNode());
Craig Topperaaeae982012-03-20 05:28:39 +00009893 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009894 // Make sure to revisit this node to clean it up; it will usually be dead.
9895 AddToWorkList(N);
9896 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009897 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009898
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009899 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009900}
Evan Cheng0de312d2007-10-06 08:19:55 +00009901
Michael Liao6d106b72012-10-23 23:06:52 +00009902// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9903SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9904 // We perform this optimization post type-legalization because
9905 // the type-legalizer often scalarizes integer-promoted vectors.
9906 // Performing this optimization before may create bit-casts which
9907 // will be type-legalized to complex code sequences.
9908 // We perform this optimization only before the operation legalizer because we
9909 // may introduce illegal operations.
9910 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9911 return SDValue();
9912
Dan Gohmana8665142007-06-25 16:23:39 +00009913 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009914 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009915 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009916
Nadav Rotembf6568b2011-10-29 21:23:04 +00009917 // Check to see if this is a BUILD_VECTOR of a bunch of values
9918 // which come from any_extend or zero_extend nodes. If so, we can create
9919 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009920 // optimizations. We do not handle sign-extend because we can't fill the sign
9921 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009922 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009923 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009924
Craig Topper02cb0fb2012-01-17 09:09:48 +00009925 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009926 SDValue In = N->getOperand(i);
9927 // Ignore undef inputs.
9928 if (In.getOpcode() == ISD::UNDEF) continue;
9929
9930 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9931 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9932
Nadav Rotemf3103612011-10-31 20:08:25 +00009933 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009934 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009935 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009936 break;
9937 }
9938
9939 // The input is a ZeroExt or AnyExt. Check the original type.
9940 EVT InTy = In.getOperand(0).getValueType();
9941
9942 // Check that all of the widened source types are the same.
9943 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009944 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009945 SourceType = InTy;
9946 else if (InTy != SourceType) {
9947 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009948 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009949 break;
9950 }
9951
9952 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009953 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009954 }
9955
Nadav Rotemf3103612011-10-31 20:08:25 +00009956 // In order to have valid types, all of the inputs must be extended from the
9957 // same source type and all of the inputs must be any or zero extend.
9958 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009959 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009960 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +00009961 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9962 isPowerOf2_32(SourceType.getSizeInBits());
9963
Nadav Rotem6fd1d322012-03-15 08:49:06 +00009964 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9965 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +00009966 if (!ValidTypes)
9967 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +00009968
Michael Liao6d106b72012-10-23 23:06:52 +00009969 bool isLE = TLI.isLittleEndian();
9970 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9971 assert(ElemRatio > 1 && "Invalid element size ratio");
9972 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9973 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009974
Michael Liao6d106b72012-10-23 23:06:52 +00009975 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9976 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009977
Michael Liao6d106b72012-10-23 23:06:52 +00009978 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +00009979 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +00009980 SDValue Cast = N->getOperand(i);
9981 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9982 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9983 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9984 SDValue In;
9985 if (Cast.getOpcode() == ISD::UNDEF)
9986 In = DAG.getUNDEF(SourceType);
9987 else
9988 In = Cast->getOperand(0);
9989 unsigned Index = isLE ? (i * ElemRatio) :
9990 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +00009991
Michael Liao6d106b72012-10-23 23:06:52 +00009992 assert(Index < Ops.size() && "Invalid index");
9993 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009994 }
Chris Lattner5336a592006-03-19 01:27:56 +00009995
Michael Liao6d106b72012-10-23 23:06:52 +00009996 // The type of the new BUILD_VECTOR node.
9997 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9998 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9999 "Invalid vector size");
10000 // Check if the new vector type is legal.
10001 if (!isTypeLegal(VecVT)) return SDValue();
10002
10003 // Make the new BUILD_VECTOR.
10004 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10005
10006 // The new BUILD_VECTOR node has the potential to be further optimized.
10007 AddToWorkList(BV.getNode());
10008 // Bitcast to the desired type.
10009 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10010}
10011
Michael Liao59229792012-10-24 04:14:18 +000010012SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10013 EVT VT = N->getValueType(0);
10014
10015 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010016 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010017
10018 EVT SrcVT = MVT::Other;
10019 unsigned Opcode = ISD::DELETED_NODE;
10020 unsigned NumDefs = 0;
10021
10022 for (unsigned i = 0; i != NumInScalars; ++i) {
10023 SDValue In = N->getOperand(i);
10024 unsigned Opc = In.getOpcode();
10025
10026 if (Opc == ISD::UNDEF)
10027 continue;
10028
10029 // If all scalar values are floats and converted from integers.
10030 if (Opcode == ISD::DELETED_NODE &&
10031 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10032 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010033 }
Tom Stellard567f8862013-01-02 22:13:01 +000010034
Michael Liao59229792012-10-24 04:14:18 +000010035 if (Opc != Opcode)
10036 return SDValue();
10037
10038 EVT InVT = In.getOperand(0).getValueType();
10039
10040 // If all scalar values are typed differently, bail out. It's chosen to
10041 // simplify BUILD_VECTOR of integer types.
10042 if (SrcVT == MVT::Other)
10043 SrcVT = InVT;
10044 if (SrcVT != InVT)
10045 return SDValue();
10046 NumDefs++;
10047 }
10048
10049 // If the vector has just one element defined, it's not worth to fold it into
10050 // a vectorized one.
10051 if (NumDefs < 2)
10052 return SDValue();
10053
10054 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10055 && "Should only handle conversion from integer to float.");
10056 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10057
10058 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010059
10060 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10061 return SDValue();
10062
Michael Liao59229792012-10-24 04:14:18 +000010063 SmallVector<SDValue, 8> Opnds;
10064 for (unsigned i = 0; i != NumInScalars; ++i) {
10065 SDValue In = N->getOperand(i);
10066
10067 if (In.getOpcode() == ISD::UNDEF)
10068 Opnds.push_back(DAG.getUNDEF(SrcVT));
10069 else
10070 Opnds.push_back(In.getOperand(0));
10071 }
10072 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10073 &Opnds[0], Opnds.size());
10074 AddToWorkList(BV.getNode());
10075
10076 return DAG.getNode(Opcode, dl, VT, BV);
10077}
10078
Michael Liao6d106b72012-10-23 23:06:52 +000010079SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10080 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010081 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010082 EVT VT = N->getValueType(0);
10083
10084 // A vector built entirely of undefs is undef.
10085 if (ISD::allOperandsUndef(N))
10086 return DAG.getUNDEF(VT);
10087
10088 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10089 if (V.getNode())
10090 return V;
10091
Michael Liao59229792012-10-24 04:14:18 +000010092 V = reduceBuildVecConvertToConvertBuildVec(N);
10093 if (V.getNode())
10094 return V;
10095
Dan Gohmana8665142007-06-25 16:23:39 +000010096 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10097 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10098 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010099
10100 // May only combine to shuffle after legalize if shuffle is legal.
10101 if (LegalOperations &&
10102 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10103 return SDValue();
10104
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010105 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010106 for (unsigned i = 0; i != NumInScalars; ++i) {
10107 // Ignore undef inputs.
10108 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010109
Dan Gohmana8665142007-06-25 16:23:39 +000010110 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010111 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010112 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010113 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010114 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010115 break;
10116 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010117
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010118 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010119 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010120 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10121 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010122
Gabor Greiff304a7a2008-08-28 21:40:38 +000010123 if (VecIn1.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010124 VecIn1 = ExtractedFromVec;
Gabor Greiff304a7a2008-08-28 21:40:38 +000010125 } else if (VecIn2.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010126 VecIn2 = ExtractedFromVec;
10127 } else {
10128 // Too many inputs.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010129 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010130 break;
10131 }
10132 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010133
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010134 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010135 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010136 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010137 for (unsigned i = 0; i != NumInScalars; ++i) {
10138 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010139 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010140 continue;
10141 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010142
Rafael Espindolab93db662009-04-24 12:40:33 +000010143 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010144 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010145 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010146 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010147 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10148 if (ExtIndex > VT.getVectorNumElements())
10149 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010150
Nate Begeman5f829d82009-04-29 05:20:52 +000010151 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010152 continue;
10153 }
10154
10155 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010156 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010157 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010158 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010159
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010160 // We can't generate a shuffle node with mismatched input and output types.
10161 // Attempt to transform a single input vector to the correct type.
10162 if ((VT != VecIn1.getValueType())) {
10163 // We don't support shuffeling between TWO values of different types.
10164 if (VecIn2.getNode() != 0)
10165 return SDValue();
10166
10167 // We only support widening of vectors which are half the size of the
10168 // output registers. For example XMM->YMM widening on X86 with AVX.
10169 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10170 return SDValue();
10171
James Molloy1e5c6112012-09-10 14:01:21 +000010172 // If the input vector type has a different base type to the output
10173 // vector type, bail out.
10174 if (VecIn1.getValueType().getVectorElementType() !=
10175 VT.getVectorElementType())
10176 return SDValue();
10177
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010178 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010179 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010180 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010181 }
10182
10183 // If VecIn2 is unused then change it to undef.
10184 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10185
Nadav Rotem841c9a82012-09-20 08:53:31 +000010186 // Check that we were able to transform all incoming values to the same
10187 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010188 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10189 VecIn1.getValueType() != VT)
10190 return SDValue();
10191
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010192 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010193 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010194 return SDValue();
10195
Dan Gohmana8665142007-06-25 16:23:39 +000010196 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010197 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010198 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010199 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010200 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010201 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010202
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010203 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010204}
10205
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010206SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010207 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10208 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10209 // inputs come from at most two distinct vectors, turn this into a shuffle
10210 // node.
10211
10212 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010213 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010214 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010215
Nadav Rotem01892102012-07-14 21:30:27 +000010216 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010217 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010218 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010219 return DAG.getUNDEF(VT);
10220
10221 // Optimize concat_vectors where one of the vectors is undef.
10222 if (N->getNumOperands() == 2 &&
10223 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10224 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010225 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010226
10227 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10228 if (In->getOpcode() == ISD::BITCAST &&
10229 !In->getOperand(0)->getValueType(0).isVector()) {
10230 SDValue Scalar = In->getOperand(0);
10231 EVT SclTy = Scalar->getValueType(0);
10232
10233 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10234 return SDValue();
10235
10236 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10237 VT.getSizeInBits() / SclTy.getSizeInBits());
10238 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10239 return SDValue();
10240
10241 SDLoc dl = SDLoc(N);
10242 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10243 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10244 }
10245 }
Nadav Rotem01892102012-07-14 21:30:27 +000010246
Robert Lougher7d9084f2014-02-11 15:42:46 +000010247 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10248 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10249 if (N->getNumOperands() == 2 &&
10250 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10251 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10252 EVT VT = N->getValueType(0);
10253 SDValue N0 = N->getOperand(0);
10254 SDValue N1 = N->getOperand(1);
10255 SmallVector<SDValue, 8> Opnds;
10256 unsigned BuildVecNumElts = N0.getNumOperands();
10257
10258 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10259 Opnds.push_back(N0.getOperand(i));
10260 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10261 Opnds.push_back(N1.getOperand(i));
10262
10263 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10264 Opnds.size());
10265 }
10266
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010267 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10268 // nodes often generate nop CONCAT_VECTOR nodes.
10269 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10270 // place the incoming vectors at the exact same location.
10271 SDValue SingleSource = SDValue();
10272 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10273
10274 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10275 SDValue Op = N->getOperand(i);
10276
10277 if (Op.getOpcode() == ISD::UNDEF)
10278 continue;
10279
10280 // Check if this is the identity extract:
10281 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10282 return SDValue();
10283
10284 // Find the single incoming vector for the extract_subvector.
10285 if (SingleSource.getNode()) {
10286 if (Op.getOperand(0) != SingleSource)
10287 return SDValue();
10288 } else {
10289 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010290
10291 // Check the source type is the same as the type of the result.
10292 // If not, this concat may extend the vector, so we can not
10293 // optimize it away.
10294 if (SingleSource.getValueType() != N->getValueType(0))
10295 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010296 }
10297
10298 unsigned IdentityIndex = i * PartNumElem;
10299 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10300 // The extract index must be constant.
10301 if (!CS)
10302 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010303
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010304 // Check that we are reading from the identity index.
10305 if (CS->getZExtValue() != IdentityIndex)
10306 return SDValue();
10307 }
10308
10309 if (SingleSource.getNode())
10310 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010311
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010312 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010313}
10314
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010315SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10316 EVT NVT = N->getValueType(0);
10317 SDValue V = N->getOperand(0);
10318
Michael Liao7a442c802012-10-17 20:48:33 +000010319 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10320 // Combine:
10321 // (extract_subvec (concat V1, V2, ...), i)
10322 // Into:
10323 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010324 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10325 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010326 if (V->getOperand(0).getValueType() != NVT)
10327 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010328 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10329 unsigned NumElems = NVT.getVectorNumElements();
10330 assert((Idx % NumElems) == 0 &&
10331 "IDX in concat is not a multiple of the result vector length.");
10332 return V->getOperand(Idx / NumElems);
10333 }
10334
Michael Liaobb05a1d2013-03-25 23:47:35 +000010335 // Skip bitcasting
10336 if (V->getOpcode() == ISD::BITCAST)
10337 V = V.getOperand(0);
10338
10339 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010340 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010341 // Handle only simple case where vector being inserted and vector
10342 // being extracted are of same type, and are half size of larger vectors.
10343 EVT BigVT = V->getOperand(0).getValueType();
10344 EVT SmallVT = V->getOperand(1).getValueType();
10345 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10346 return SDValue();
10347
10348 // Only handle cases where both indexes are constants with the same type.
10349 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10350 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10351
10352 if (InsIdx && ExtIdx &&
10353 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10354 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10355 // Combine:
10356 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10357 // Into:
10358 // indices are equal or bit offsets are equal => V1
10359 // otherwise => (extract_subvec V1, ExtIdx)
10360 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10361 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10362 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10363 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10364 DAG.getNode(ISD::BITCAST, dl,
10365 N->getOperand(0).getValueType(),
10366 V->getOperand(0)), N->getOperand(1));
10367 }
10368 }
10369
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010370 return SDValue();
10371}
10372
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010373// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10374static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10375 EVT VT = N->getValueType(0);
10376 unsigned NumElts = VT.getVectorNumElements();
10377
10378 SDValue N0 = N->getOperand(0);
10379 SDValue N1 = N->getOperand(1);
10380 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10381
10382 SmallVector<SDValue, 4> Ops;
10383 EVT ConcatVT = N0.getOperand(0).getValueType();
10384 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10385 unsigned NumConcats = NumElts / NumElemsPerConcat;
10386
10387 // Look at every vector that's inserted. We're looking for exact
10388 // subvector-sized copies from a concatenated vector
10389 for (unsigned I = 0; I != NumConcats; ++I) {
10390 // Make sure we're dealing with a copy.
10391 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010392 bool AllUndef = true, NoUndef = true;
10393 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10394 if (SVN->getMaskElt(J) >= 0)
10395 AllUndef = false;
10396 else
10397 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010398 }
10399
Hao Liubc601962013-05-13 02:07:05 +000010400 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010401 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10402 return SDValue();
10403
10404 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10405 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10406 return SDValue();
10407
10408 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10409 if (FirstElt < N0.getNumOperands())
10410 Ops.push_back(N0.getOperand(FirstElt));
10411 else
10412 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10413
10414 } else if (AllUndef) {
10415 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10416 } else { // Mixed with general masks and undefs, can't do optimization.
10417 return SDValue();
10418 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010419 }
10420
Andrew Trickef9de2a2013-05-25 02:42:55 +000010421 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010422 Ops.size());
10423}
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));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010637 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010638 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peck527da1b2010-11-23 03:31:01 +000010639 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010640 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010641 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010642 }
10643 }
Bill Wendling31b50992009-01-30 23:59:18 +000010644
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010645 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010646}
10647
Dan Gohmana8665142007-06-25 16:23:39 +000010648/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010649SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010650 assert(N->getValueType(0).isVector() &&
10651 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010652
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010653 SDValue LHS = N->getOperand(0);
10654 SDValue RHS = N->getOperand(1);
10655 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010656 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010657
Dan Gohmana8665142007-06-25 16:23:39 +000010658 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010659 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010660 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010661 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010662 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010663 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10664 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010665 return SDValue();
10666
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010667 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010668 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010669 SDValue LHSOp = LHS.getOperand(i);
10670 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010671
Evan Cheng64d28462006-05-31 06:08:35 +000010672 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010673 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10674 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010675 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010676 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010677 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010678 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010679 break;
10680 }
Bill Wendling31b50992009-01-30 23:59:18 +000010681
Bob Wilson54081442010-12-17 23:06:49 +000010682 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010683 EVT RVT = RHSOp.getValueType();
10684 if (RVT != VT) {
10685 // Integer BUILD_VECTOR operands may have types larger than the element
10686 // size (e.g., when the element type is not legal). Prior to type
10687 // legalization, the types may not match between the two BUILD_VECTORS.
10688 // Truncate one of the operands to make them match.
10689 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010690 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010691 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010692 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010693 VT = RVT;
10694 }
10695 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010696 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010697 LHSOp, RHSOp);
10698 if (FoldOp.getOpcode() != ISD::UNDEF &&
10699 FoldOp.getOpcode() != ISD::Constant &&
10700 FoldOp.getOpcode() != ISD::ConstantFP)
10701 break;
10702 Ops.push_back(FoldOp);
10703 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010704 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010705
Bob Wilson54081442010-12-17 23:06:49 +000010706 if (Ops.size() == LHS.getNumOperands())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010707 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilson54081442010-12-17 23:06:49 +000010708 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattner0442a182006-04-02 03:25:57 +000010709 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010710
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010711 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010712}
10713
Craig Topper82384612012-09-11 01:45:21 +000010714/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10715SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010716 assert(N->getValueType(0).isVector() &&
10717 "SimplifyVUnaryOp only works on vectors!");
10718
10719 SDValue N0 = N->getOperand(0);
10720
10721 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10722 return SDValue();
10723
10724 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10725 SmallVector<SDValue, 8> Ops;
10726 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10727 SDValue Op = N0.getOperand(i);
10728 if (Op.getOpcode() != ISD::UNDEF &&
10729 Op.getOpcode() != ISD::ConstantFP)
10730 break;
10731 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010732 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010733 if (FoldOp.getOpcode() != ISD::UNDEF &&
10734 FoldOp.getOpcode() != ISD::ConstantFP)
10735 break;
10736 Ops.push_back(FoldOp);
10737 AddToWorkList(FoldOp.getNode());
10738 }
10739
10740 if (Ops.size() != N0.getNumOperands())
10741 return SDValue();
10742
Andrew Trickef9de2a2013-05-25 02:42:55 +000010743 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topper82384612012-09-11 01:45:21 +000010744 N0.getValueType(), &Ops[0], Ops.size());
10745}
10746
Andrew Trickef9de2a2013-05-25 02:42:55 +000010747SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010748 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010749 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010750
Bill Wendling31b50992009-01-30 23:59:18 +000010751 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010752 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010753
Nate Begeman2042aa52005-10-08 00:29:44 +000010754 // If we got a simplified select_cc node back from SimplifySelectCC, then
10755 // break it down into a new SETCC node, and a new SELECT node, and then return
10756 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010757 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010758 // Check to see if we got a select_cc back (to turn into setcc/select).
10759 // Otherwise, just return whatever node we got back, like fabs.
10760 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010761 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010762 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010763 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010764 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010765 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010766 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10767 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010768 }
Bill Wendling31b50992009-01-30 23:59:18 +000010769
Nate Begeman2042aa52005-10-08 00:29:44 +000010770 return SCC;
10771 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010772 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010773}
10774
Chris Lattner6c14c352005-10-18 06:04:22 +000010775/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10776/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010777/// select. Callers of this should assume that TheSelect is deleted if this
10778/// returns true. As such, they should return the appropriate thing (e.g. the
10779/// node) back to the top-level of the DAG combiner loop to avoid it being
10780/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010781bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010782 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010783
Nadav Rotema49a02a2011-02-11 19:57:47 +000010784 // Cannot simplify select with vector condition
10785 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10786
Chris Lattner6c14c352005-10-18 06:04:22 +000010787 // If this is a select from two identical things, try to pull the operation
10788 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010789 if (LHS.getOpcode() != RHS.getOpcode() ||
10790 !LHS.hasOneUse() || !RHS.hasOneUse())
10791 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010792
Chris Lattner254c4452010-09-21 15:46:59 +000010793 // If this is a load and the token chain is identical, replace the select
10794 // of two loads with a load through a select of the address to load from.
10795 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10796 // constants have been dropped into the constant pool.
10797 if (LHS.getOpcode() == ISD::LOAD) {
10798 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10799 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010800
Chris Lattner254c4452010-09-21 15:46:59 +000010801 // Token chains must be identical.
10802 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010803 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010804 LLD->isVolatile() || RLD->isVolatile() ||
10805 // If this is an EXTLOAD, the VT's must match.
10806 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010807 // If this is an EXTLOAD, the kind of extension must match.
10808 (LLD->getExtensionType() != RLD->getExtensionType() &&
10809 // The only exception is if one of the extensions is anyext.
10810 LLD->getExtensionType() != ISD::EXTLOAD &&
10811 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010812 // FIXME: this discards src value information. This is
10813 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010814 // both potential memory locations. Since we are discarding
10815 // src value info, don't do the transformation if the memory
10816 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010817 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010818 RLD->getPointerInfo().getAddrSpace() != 0 ||
10819 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10820 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010821 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010822
Chris Lattnere3267522010-09-21 15:58:55 +000010823 // Check that the select condition doesn't reach either load. If so,
10824 // folding this will induce a cycle into the DAG. If not, this is safe to
10825 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010826 SDValue Addr;
10827 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010828 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10829 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10830 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10831 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010832 // The loads must not depend on one another.
10833 if (LLD->isPredecessorOf(RLD) ||
10834 RLD->isPredecessorOf(LLD))
10835 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010836 Addr = DAG.getSelect(SDLoc(TheSelect),
10837 LLD->getBasePtr().getValueType(),
10838 TheSelect->getOperand(0), LLD->getBasePtr(),
10839 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010840 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010841 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10842 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10843
10844 if ((LLD->hasAnyUseOfValue(1) &&
10845 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010846 (RLD->hasAnyUseOfValue(1) &&
10847 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010848 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010849
Andrew Trickef9de2a2013-05-25 02:42:55 +000010850 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010851 LLD->getBasePtr().getValueType(),
10852 TheSelect->getOperand(0),
10853 TheSelect->getOperand(1),
10854 LLD->getBasePtr(), RLD->getBasePtr(),
10855 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010856 }
10857
Chris Lattnere3267522010-09-21 15:58:55 +000010858 SDValue Load;
10859 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10860 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010861 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010862 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010863 LLD->getChain(), Addr, MachinePointerInfo(),
10864 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010865 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010866 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010867 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10868 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010869 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010870 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010871 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010872 LLD->getChain(), Addr, MachinePointerInfo(),
10873 LLD->getMemoryVT(), LLD->isVolatile(),
10874 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010875 }
Chris Lattnere3267522010-09-21 15:58:55 +000010876
10877 // Users of the select now use the result of the load.
10878 CombineTo(TheSelect, Load);
10879
10880 // Users of the old loads now use the new load's chain. We know the
10881 // old-load value is dead now.
10882 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10883 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10884 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010885 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010886
Chris Lattner6c14c352005-10-18 06:04:22 +000010887 return false;
10888}
10889
Chris Lattner43d63772009-03-11 05:08:08 +000010890/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10891/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010892SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010893 SDValue N2, SDValue N3,
10894 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010895 // (x ? y : y) -> y.
10896 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010897
Owen Anderson53aa7a92009-08-10 22:56:29 +000010898 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010899 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10900 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10901 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010902
10903 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010904 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010905 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010906 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10907 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010908
10909 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010910 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010911 return N2;
10912 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010913 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010914 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010915
Nate Begeman2042aa52005-10-08 00:29:44 +000010916 // Check to see if we can simplify the select into an fabs node
10917 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10918 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010919 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010920 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10921 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10922 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10923 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010924 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010925
Nate Begeman2042aa52005-10-08 00:29:44 +000010926 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10927 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10928 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10929 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010930 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010931 }
10932 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010933
Chris Lattner43d63772009-03-11 05:08:08 +000010934 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10935 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10936 // in it. This is a win when the constant is not otherwise available because
10937 // it replaces two constant pool loads with one. We only do this if the FP
10938 // type is known to be legal, because if it isn't, then we are before legalize
10939 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010940 // messing with soft float) and if the ConstantFP is not legal, because if
10941 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010942 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10943 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10944 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010945 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10946 TargetLowering::Legal) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010947 // If both constants have multiple uses, then we won't need to do an
10948 // extra load, they are likely around in registers for other users.
10949 (TV->hasOneUse() || FV->hasOneUse())) {
10950 Constant *Elts[] = {
10951 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10952 const_cast<ConstantFP*>(TV->getConstantFPValue())
10953 };
Chris Lattner229907c2011-07-18 04:54:35 +000010954 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010955 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010956
Chris Lattner43d63772009-03-11 05:08:08 +000010957 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010958 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010959 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10960 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000010961 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000010962
10963 // Get the offsets to the 0 and 1 element of the array so that we can
10964 // select between them.
10965 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010966 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000010967 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000010968
Chris Lattner43d63772009-03-11 05:08:08 +000010969 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000010970 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000010971 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010972 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010973 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10974 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010975 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000010976 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000010977 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010978 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000010979 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000010980 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000010981 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000010982
10983 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010984 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010985
Nate Begeman2042aa52005-10-08 00:29:44 +000010986 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000010987 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000010988 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000010989 (N1C->isNullValue() || // (a < 0) ? b : 0
10990 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000010991 EVT XType = N0.getValueType();
10992 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000010993 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000010994 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000010995 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010996 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10997 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000010998 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000010999 SDValue ShCt = DAG.getConstant(ShCtV,
11000 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011001 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011002 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011003 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011004
Duncan Sands11dd4242008-06-08 20:54:56 +000011005 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011006 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011007 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011008 }
Bill Wendling31b50992009-01-30 23:59:18 +000011009
11010 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011011 }
Bill Wendling31b50992009-01-30 23:59:18 +000011012
Andrew Trickef9de2a2013-05-25 02:42:55 +000011013 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011014 XType, N0,
11015 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011016 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000011017 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011018
Duncan Sands11dd4242008-06-08 20:54:56 +000011019 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011020 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011021 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011022 }
Bill Wendling31b50992009-01-30 23:59:18 +000011023
11024 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011025 }
11026 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011027
Owen Anderson3231d132010-09-22 22:58:22 +000011028 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11029 // where y is has a single bit set.
11030 // A plaintext description would be, we can turn the SELECT_CC into an AND
11031 // when the condition can be materialized as an all-ones register. Any
11032 // single bit-test can be materialized as an all-ones register with
11033 // shift-left and shift-right-arith.
11034 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11035 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011036 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011037 N2C && N2C->isNullValue()) {
11038 SDValue AndLHS = N0->getOperand(0);
11039 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11040 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11041 // Shift the tested bit over the sign bit.
11042 APInt AndMask = ConstAndRHS->getAPIntValue();
11043 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011044 DAG.getConstant(AndMask.countLeadingZeros(),
11045 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011046 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011047
Owen Anderson3231d132010-09-22 22:58:22 +000011048 // Now arithmetic right shift it all the way over, so the result is either
11049 // all-ones, or zero.
11050 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011051 DAG.getConstant(AndMask.getBitWidth()-1,
11052 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011053 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011054
Owen Anderson3231d132010-09-22 22:58:22 +000011055 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11056 }
11057 }
11058
Nate Begeman6828ed92005-10-10 21:26:48 +000011059 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011060 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000011061 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11062 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011063
Chris Lattnera083ffc2007-04-11 06:50:51 +000011064 // If the caller doesn't want us to simplify this into a zext of a compare,
11065 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011066 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011067 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011068
Nate Begeman6828ed92005-10-10 21:26:48 +000011069 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011070 // NOTE: Don't create a SETCC if it's not legal on this target.
11071 if (!LegalOperations ||
11072 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011073 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011074 SDValue Temp, SCC;
11075 // cast from setcc result type to select result type
11076 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011077 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011078 N0, N1, CC);
11079 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011080 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011081 N2.getValueType());
11082 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011083 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011084 N2.getValueType(), SCC);
11085 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011086 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11087 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011088 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011089 }
11090
11091 AddToWorkList(SCC.getNode());
11092 AddToWorkList(Temp.getNode());
11093
11094 if (N2C->getAPIntValue() == 1)
11095 return Temp;
11096
11097 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011098 return DAG.getNode(
11099 ISD::SHL, DL, N2.getValueType(), Temp,
11100 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11101 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011102 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011103 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011104
Nate Begeman2042aa52005-10-08 00:29:44 +000011105 // Check to see if this is the equivalent of setcc
11106 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11107 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011108 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011109 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011110 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011111 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11112 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011113 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011114 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011115 return Res;
11116 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011117
Bill Wendling31b50992009-01-30 23:59:18 +000011118 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011119 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011120 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011121 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011122 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011123 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011124 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011125 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011126 }
Bill Wendling31b50992009-01-30 23:59:18 +000011127 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011128 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011129 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011130 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011131 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011132 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011133 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011134 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011135 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011136 }
Bill Wendling31b50992009-01-30 23:59:18 +000011137 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011138 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011139 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011140 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011141 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011142 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011143 }
11144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011145
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011146 // Check to see if this is an integer abs.
11147 // select_cc setg[te] X, 0, X, -X ->
11148 // select_cc setgt X, -1, X, -X ->
11149 // select_cc setl[te] X, 0, -X, X ->
11150 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011151 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011152 if (N1C) {
11153 ConstantSDNode *SubC = NULL;
11154 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11155 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11156 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11157 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11158 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11159 (N1C->isOne() && CC == ISD::SETLT)) &&
11160 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11161 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11162
Owen Anderson53aa7a92009-08-10 22:56:29 +000011163 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011164 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011165 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011166 N0,
11167 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011168 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011169 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011170 XType, N0, Shift);
11171 AddToWorkList(Shift.getNode());
11172 AddToWorkList(Add.getNode());
11173 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011174 }
11175 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011176
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011177 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011178}
11179
Evan Cheng92658d52007-02-08 22:13:59 +000011180/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011181SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011182 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011183 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011184 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011185 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011186 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011187}
11188
Nate Begemanc6f067a2005-10-20 02:15:44 +000011189/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11190/// return a DAG expression to select that will generate the same value by
11191/// multiplying by a magic number. See:
11192/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011193SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011194 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011195 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011196
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011197 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011198 ii != ee; ++ii)
11199 AddToWorkList(*ii);
11200 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011201}
11202
11203/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11204/// return a DAG expression to select that will generate the same value by
11205/// multiplying by a magic number. See:
11206/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011207SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011208 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011209 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011210
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011211 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011212 ii != ee; ++ii)
11213 AddToWorkList(*ii);
11214 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011215}
11216
Nate Begeman18150d52009-09-25 06:05:26 +000011217/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011218// to alias with anything but itself. Provides base object and offset as
11219// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011220static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011221 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011222 // Assume it is a primitive operation.
Nate Begeman18150d52009-09-25 06:05:26 +000011223 Base = Ptr; Offset = 0; GV = 0; CV = 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011224
Jim Laskey0463e082006-10-07 23:37:56 +000011225 // If it's an adding a simple constant then integrate the offset.
11226 if (Base.getOpcode() == ISD::ADD) {
11227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11228 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011229 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011230 }
11231 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011232
Nate Begeman18150d52009-09-25 06:05:26 +000011233 // Return the underlying GlobalValue, and update the Offset. Return false
11234 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11235 // by multiple nodes with different offsets.
11236 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11237 GV = G->getGlobal();
11238 Offset += G->getOffset();
11239 return false;
11240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011241
Nate Begeman18150d52009-09-25 06:05:26 +000011242 // Return the underlying Constant value, and update the Offset. Return false
11243 // for ConstantSDNodes since the same constant pool entry may be represented
11244 // by multiple nodes with different offsets.
11245 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011246 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11247 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011248 Offset += C->getOffset();
11249 return false;
11250 }
Jim Laskey0463e082006-10-07 23:37:56 +000011251 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011252 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011253}
11254
11255/// isAlias - Return true if there is any possibility that the two addresses
11256/// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011257bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011258 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +000011259 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011260 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011261 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +000011262 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011263 unsigned SrcValueAlign2,
11264 const MDNode *TBAAInfo2) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011265 // If they are the same then they must be aliases.
11266 if (Ptr1 == Ptr2) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011267
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011268 // If they are both volatile then they cannot be reordered.
11269 if (IsVolatile1 && IsVolatile2) return true;
11270
Jim Laskey0463e082006-10-07 23:37:56 +000011271 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011272 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011273 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011274 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011275 const void *CV1, *CV2;
Nate Begeman18150d52009-09-25 06:05:26 +000011276 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11277 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011278
Nate Begeman18150d52009-09-25 06:05:26 +000011279 // If they have a same base address then check to see if they overlap.
11280 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Bill Wendling31b50992009-01-30 23:59:18 +000011281 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011282
Owen Anderson272ff942010-09-20 20:39:59 +000011283 // It is possible for different frame indices to alias each other, mostly
11284 // when tail call optimization reuses return address slots for arguments.
11285 // To catch this case, look up the actual index of frame indices to compute
11286 // the real alias relationship.
11287 if (isFrameIndex1 && isFrameIndex2) {
11288 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11289 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11290 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11291 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11292 }
11293
Wesley Peck527da1b2010-11-23 03:31:01 +000011294 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011295 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011296 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11297 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011298
Nate Begeman879d8f12009-09-15 00:18:30 +000011299 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11300 // compared to the size and offset of the access, we may be able to prove they
11301 // do not alias. This check is conservative for now to catch cases created by
11302 // splitting vector types.
11303 if ((SrcValueAlign1 == SrcValueAlign2) &&
11304 (SrcValueOffset1 != SrcValueOffset2) &&
11305 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11306 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11307 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
Wesley Peck527da1b2010-11-23 03:31:01 +000011308
Nate Begeman879d8f12009-09-15 00:18:30 +000011309 // There is no overlap between these relatively aligned accesses of similar
11310 // size, return no alias.
11311 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11312 return false;
11313 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011314
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011315 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11316 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011317#ifndef NDEBUG
11318 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11319 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11320 UseAA = false;
11321#endif
Hal Finkel31658832013-09-15 02:19:49 +000011322 if (UseAA && SrcValue1 && SrcValue2) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011323 // Use alias analysis information.
Dan Gohman9625d812007-08-27 16:32:11 +000011324 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11325 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11326 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011327 AliasAnalysis::AliasResult AAResult =
Hal Finkeldbebb522014-01-25 19:24:54 +000011328 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11329 UseTBAA ? TBAAInfo1 : 0),
11330 AliasAnalysis::Location(SrcValue2, Overlap2,
11331 UseTBAA ? TBAAInfo2 : 0));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011332 if (AAResult == AliasAnalysis::NoAlias)
11333 return false;
11334 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011335
11336 // Otherwise we have to assume they alias.
11337 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011338}
11339
Nadav Rotem307d7672012-11-29 00:00:08 +000011340bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11341 SDValue Ptr0, Ptr1;
11342 int64_t Size0, Size1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011343 bool IsVolatile0, IsVolatile1;
Nadav Rotem307d7672012-11-29 00:00:08 +000011344 const Value *SrcValue0, *SrcValue1;
11345 int SrcValueOffset0, SrcValueOffset1;
11346 unsigned SrcValueAlign0, SrcValueAlign1;
11347 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011348 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotem307d7672012-11-29 00:00:08 +000011349 SrcValueAlign0, SrcTBAAInfo0);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011350 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotem307d7672012-11-29 00:00:08 +000011351 SrcValueAlign1, SrcTBAAInfo1);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011352 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011353 SrcValueAlign0, SrcTBAAInfo0,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011354 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011355 SrcValueAlign1, SrcTBAAInfo1);
Nadav Rotem307d7672012-11-29 00:00:08 +000011356}
11357
Jim Laskey0463e082006-10-07 23:37:56 +000011358/// FindAliasInfo - Extracts the relevant alias information from the memory
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011359/// node. Returns true if the operand was a nonvolatile load.
Jim Laskey08edf332006-10-11 13:47:09 +000011360bool DAGCombiner::FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011361 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011362 const Value *&SrcValue,
11363 int &SrcValueOffset,
11364 unsigned &SrcValueAlign,
11365 const MDNode *&TBAAInfo) const {
11366 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11367
11368 Ptr = LS->getBasePtr();
11369 Size = LS->getMemoryVT().getSizeInBits() >> 3;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011370 IsVolatile = LS->isVolatile();
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011371 SrcValue = LS->getSrcValue();
11372 SrcValueOffset = LS->getSrcValueOffset();
11373 SrcValueAlign = LS->getOriginalAlignment();
11374 TBAAInfo = LS->getTBAAInfo();
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011375 return isa<LoadSDNode>(LS) && !IsVolatile;
Jim Laskey0463e082006-10-07 23:37:56 +000011376}
11377
Jim Laskey708d0db2006-10-04 16:53:27 +000011378/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11379/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011380void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011381 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011382 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011383 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011384
Jim Laskeyd07be232006-09-25 16:29:54 +000011385 // Get alias information for node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011386 SDValue Ptr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011387 int64_t Size;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011388 bool IsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011389 const Value *SrcValue;
11390 int SrcValueOffset;
11391 unsigned SrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011392 const MDNode *SrcTBAAInfo;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011393 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11394 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
Jim Laskeyd07be232006-09-25 16:29:54 +000011395
Jim Laskey708d0db2006-10-04 16:53:27 +000011396 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011397 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011398 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011399
Jim Laskey6549d222006-10-05 15:07:25 +000011400 // Look at each chain and determine if it is an alias. If so, add it to the
11401 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011402 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011403 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011404 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011405 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011406
11407 // For TokenFactor nodes, look at each operand and only continue up the
11408 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011409 // find more and revert to original chain since the xform is unlikely to be
11410 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011411 //
11412 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011413 // chain we found before we hit a tokenfactor rather than the original
11414 // chain.
11415 if (Depth > 6 || Aliases.size() == 2) {
11416 Aliases.clear();
11417 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011418 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011419 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011420
Nate Begeman879d8f12009-09-15 00:18:30 +000011421 // Don't bother if we've been before.
11422 if (!Visited.insert(Chain.getNode()))
11423 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011424
Jim Laskey6549d222006-10-05 15:07:25 +000011425 switch (Chain.getOpcode()) {
11426 case ISD::EntryToken:
11427 // Entry token is ideal chain operand, but handled in FindBetterChain.
11428 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011429
Jim Laskey6549d222006-10-05 15:07:25 +000011430 case ISD::LOAD:
11431 case ISD::STORE: {
11432 // Get alias information for Chain.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011433 SDValue OpPtr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011434 int64_t OpSize;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011435 bool OpIsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011436 const Value *OpSrcValue;
11437 int OpSrcValueOffset;
11438 unsigned OpSrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011439 const MDNode *OpSrcTBAAInfo;
Gabor Greiff304a7a2008-08-28 21:40:38 +000011440 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011441 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011442 OpSrcValueAlign,
11443 OpSrcTBAAInfo);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011444
Jim Laskey6549d222006-10-05 15:07:25 +000011445 // If chain is alias then stop here.
11446 if (!(IsLoad && IsOpLoad) &&
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011447 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11448 SrcValueAlign, SrcTBAAInfo,
11449 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011450 OpSrcValueAlign, OpSrcTBAAInfo)) {
Jim Laskey6549d222006-10-05 15:07:25 +000011451 Aliases.push_back(Chain);
11452 } else {
11453 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011454 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011455 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011456 }
Jim Laskey6549d222006-10-05 15:07:25 +000011457 break;
11458 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011459
Jim Laskey6549d222006-10-05 15:07:25 +000011460 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011461 // We have to check each of the operands of the token factor for "small"
11462 // token factors, so we queue them up. Adding the operands to the queue
11463 // (stack) in reverse order maintains the original order and increases the
11464 // likelihood that getNode will find a matching token factor (CSE.)
11465 if (Chain.getNumOperands() > 16) {
11466 Aliases.push_back(Chain);
11467 break;
11468 }
Jim Laskey6549d222006-10-05 15:07:25 +000011469 for (unsigned n = Chain.getNumOperands(); n;)
11470 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011471 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011472 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011473
Jim Laskey6549d222006-10-05 15:07:25 +000011474 default:
11475 // For all other instructions we will just have to take what we can get.
11476 Aliases.push_back(Chain);
11477 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011478 }
11479 }
Hal Finkel51a98382014-01-24 20:12:02 +000011480
11481 // We need to be careful here to also search for aliases through the
11482 // value operand of a store, etc. Consider the following situation:
11483 // Token1 = ...
11484 // L1 = load Token1, %52
11485 // S1 = store Token1, L1, %51
11486 // L2 = load Token1, %52+8
11487 // S2 = store Token1, L2, %51+8
11488 // Token2 = Token(S1, S2)
11489 // L3 = load Token2, %53
11490 // S3 = store Token2, L3, %52
11491 // L4 = load Token2, %53+8
11492 // S4 = store Token2, L4, %52+8
11493 // If we search for aliases of S3 (which loads address %52), and we look
11494 // only through the chain, then we'll miss the trivial dependence on L1
11495 // (which also loads from %52). We then might change all loads and
11496 // stores to use Token1 as their chain operand, which could result in
11497 // copying %53 into %52 before copying %52 into %51 (which should
11498 // happen first).
11499 //
11500 // The problem is, however, that searching for such data dependencies
11501 // can become expensive, and the cost is not directly related to the
11502 // chain depth. Instead, we'll rule out such configurations here by
11503 // insisting that we've visited all chain users (except for users
11504 // of the original chain, which is not necessary). When doing this,
11505 // we need to look through nodes we don't care about (otherwise, things
11506 // like register copies will interfere with trivial cases).
11507
11508 SmallVector<const SDNode *, 16> Worklist;
11509 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11510 IE = Visited.end(); I != IE; ++I)
11511 if (*I != OriginalChain.getNode())
11512 Worklist.push_back(*I);
11513
11514 while (!Worklist.empty()) {
11515 const SDNode *M = Worklist.pop_back_val();
11516
11517 // We have already visited M, and want to make sure we've visited any uses
11518 // of M that we care about. For uses that we've not visisted, and don't
11519 // care about, queue them to the worklist.
11520
11521 for (SDNode::use_iterator UI = M->use_begin(),
11522 UIE = M->use_end(); UI != UIE; ++UI)
11523 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11524 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11525 // We've not visited this use, and we care about it (it could have an
11526 // ordering dependency with the original node).
11527 Aliases.clear();
11528 Aliases.push_back(OriginalChain);
11529 return;
11530 }
11531
11532 // We've not visited this use, but we don't care about it. Mark it as
11533 // visited and enqueue it to the worklist.
11534 Worklist.push_back(*UI);
11535 }
11536 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011537}
11538
11539/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11540/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011541SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11542 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011543
Jim Laskey708d0db2006-10-04 16:53:27 +000011544 // Accumulate all the aliases to this node.
11545 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011546
Dan Gohman4298df62011-05-17 22:20:36 +000011547 // If no operands then chain to entry token.
11548 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011549 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011550
11551 // If a single operand then chain to it. We don't need to revisit it.
11552 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011553 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011554
Jim Laskey708d0db2006-10-04 16:53:27 +000011555 // Construct a custom tailored token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011556 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begeman879d8f12009-09-15 00:18:30 +000011557 &Aliases[0], Aliases.size());
Jim Laskeyd07be232006-09-25 16:29:54 +000011558}
11559
Nate Begeman21158fc2005-09-01 00:19:25 +000011560// SelectionDAG::Combine - This is the entry point for the file.
11561//
Bill Wendling084669a2009-04-29 00:15:41 +000011562void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011563 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011564 /// run - This is the main entry point to this class.
11565 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011566 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011567}