blob: 4f67da66542925431b81c9ae2c1f505322f7e7df [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);
232 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000234 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000236 SDValue visitCTPOP(SDNode *N);
237 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000238 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000239 SDValue visitSELECT_CC(SDNode *N);
240 SDValue visitSETCC(SDNode *N);
241 SDValue visitSIGN_EXTEND(SDNode *N);
242 SDValue visitZERO_EXTEND(SDNode *N);
243 SDValue visitANY_EXTEND(SDNode *N);
244 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000246 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000247 SDValue visitBUILD_PAIR(SDNode *N);
248 SDValue visitFADD(SDNode *N);
249 SDValue visitFSUB(SDNode *N);
250 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000251 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitFDIV(SDNode *N);
253 SDValue visitFREM(SDNode *N);
254 SDValue visitFCOPYSIGN(SDNode *N);
255 SDValue visitSINT_TO_FP(SDNode *N);
256 SDValue visitUINT_TO_FP(SDNode *N);
257 SDValue visitFP_TO_SINT(SDNode *N);
258 SDValue visitFP_TO_UINT(SDNode *N);
259 SDValue visitFP_ROUND(SDNode *N);
260 SDValue visitFP_ROUND_INREG(SDNode *N);
261 SDValue visitFP_EXTEND(SDNode *N);
262 SDValue visitFNEG(SDNode *N);
263 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000264 SDValue visitFCEIL(SDNode *N);
265 SDValue visitFTRUNC(SDNode *N);
266 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000267 SDValue visitBRCOND(SDNode *N);
268 SDValue visitBR_CC(SDNode *N);
269 SDValue visitLOAD(SDNode *N);
270 SDValue visitSTORE(SDNode *N);
271 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273 SDValue visitBUILD_VECTOR(SDNode *N);
274 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000276 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000277 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000278
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000279 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000281
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000282 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000283
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000288 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000289 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000291 SDLoc DL, bool foldBooleans = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000293 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000296 SDValue BuildSDIV(SDNode *N);
297 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299 bool DemandHighBits = true);
300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302 SDValue InnerPos, SDValue InnerNeg,
303 unsigned PosOpcode, unsigned NegOpcode,
304 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000306 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000307 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000308 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000311
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000312 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000313
Jim Laskey708d0db2006-10-04 16:53:27 +0000314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000316 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000317 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000318
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000319 /// isAlias - Return true if there is any possibility that the two addresses
320 /// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000321 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000322 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +0000323 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000324 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000325 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +0000326 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000327 unsigned SrcValueAlign2,
328 const MDNode *TBAAInfo2) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000329
Nadav Rotem307d7672012-11-29 00:00:08 +0000330 /// isAlias - Return true if there is any possibility that the two addresses
331 /// overlap.
332 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
333
Jim Laskey08edf332006-10-11 13:47:09 +0000334 /// FindAliasInfo - Extracts the relevant alias information from the memory
335 /// node. Returns true if the operand was a load.
336 bool FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000337 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Nate Begeman879d8f12009-09-15 00:18:30 +0000338 const Value *&SrcValue, int &SrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000339 unsigned &SrcValueAlignment,
340 const MDNode *&TBAAInfo) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000341
Jim Laskeyd07be232006-09-25 16:29:54 +0000342 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000343 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000344 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000345
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000346 /// Merge consecutive store operations into a wide store.
347 /// This optimization uses wide integers or vectors when possible.
348 /// \return True if some memory operations were changed.
349 bool MergeConsecutiveStores(StoreSDNode *N);
350
Chris Lattner4041ab62010-04-15 04:48:01 +0000351 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000352 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000353 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
354 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
355 AttributeSet FnAttrs =
356 DAG.getMachineFunction().getFunction()->getAttributes();
357 ForCodeSize =
358 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
359 Attribute::OptimizeForSize) ||
360 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
361 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000362
Nate Begeman21158fc2005-09-01 00:19:25 +0000363 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000364 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000365
Chris Lattner4041ab62010-04-15 04:48:01 +0000366 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000367
Chris Lattner4041ab62010-04-15 04:48:01 +0000368 /// getShiftAmountTy - Returns a type large enough to hold any valid
369 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000370 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000371 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
372 if (LHSTy.isVector())
373 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000374 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
375 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000376 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000377
Chris Lattner4041ab62010-04-15 04:48:01 +0000378 /// isTypeLegal - This method returns true if we are running before type
379 /// legalization or if the specified VT is legal.
380 bool isTypeLegal(const EVT &VT) {
381 if (!LegalTypes) return true;
382 return TLI.isTypeLegal(VT);
383 }
Matt Arsenault758659232013-05-18 00:21:46 +0000384
385 /// getSetCCResultType - Convenience wrapper around
386 /// TargetLowering::getSetCCResultType
387 EVT getSetCCResultType(EVT VT) const {
388 return TLI.getSetCCResultType(*DAG.getContext(), VT);
389 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000390 };
391}
392
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000393
394namespace {
395/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
396/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000397class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000398 DAGCombiner &DC;
399public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000400 explicit WorkListRemover(DAGCombiner &dc)
401 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000402
Duncan Sandsbf170802008-06-11 11:42:12 +0000403 virtual void NodeDeleted(SDNode *N, SDNode *E) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000404 DC.removeFromWorkList(N);
405 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000406};
407}
408
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000409//===----------------------------------------------------------------------===//
410// TargetLowering::DAGCombinerInfo implementation
411//===----------------------------------------------------------------------===//
412
413void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
414 ((DAGCombiner*)DC)->AddToWorkList(N);
415}
416
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000417void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
418 ((DAGCombiner*)DC)->removeFromWorkList(N);
419}
420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000421SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000422CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
423 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000424}
425
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000426SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000427CombineTo(SDNode *N, SDValue Res, bool AddTo) {
428 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000429}
430
431
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000432SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000433CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
434 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000435}
436
Dan Gohmane58ab792009-01-29 01:59:02 +0000437void TargetLowering::DAGCombinerInfo::
438CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
439 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
440}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000441
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000442//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000443// Helper Functions
444//===----------------------------------------------------------------------===//
445
446/// isNegatibleForFree - Return 1 if we can compute the negated form of the
447/// specified expression for the same cost as the expression itself, or 2 if we
448/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000449static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000450 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000451 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000452 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000453 // fneg is removable even if it has multiple uses.
454 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000455
Chris Lattnere49c9742007-05-14 22:04:50 +0000456 // Don't allow anything with multiple uses.
457 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000458
Chris Lattner46980832007-05-25 02:19:06 +0000459 // Don't recurse exponentially.
460 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000461
Chris Lattnere49c9742007-05-14 22:04:50 +0000462 switch (Op.getOpcode()) {
463 default: return false;
464 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000465 // Don't invert constant FP values after legalize. The negated constant
466 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000467 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000468 case ISD::FADD:
469 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000470 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000471
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000472 // After operation legalization, it might not be legal to create new FSUBs.
473 if (LegalOperations &&
474 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
475 return 0;
476
Craig Topper03f39772012-09-09 22:58:45 +0000477 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000478 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
479 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000480 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000481 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000482 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000483 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000484 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000485 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000486 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000487
Bill Wendling6fbf5492009-01-30 23:10:18 +0000488 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000489 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000490
Chris Lattnere49c9742007-05-14 22:04:50 +0000491 case ISD::FMUL:
492 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000493 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000494
Bill Wendling6fbf5492009-01-30 23:10:18 +0000495 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000496 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
497 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000498 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000499
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000500 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000501 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000502
Chris Lattnere49c9742007-05-14 22:04:50 +0000503 case ISD::FP_EXTEND:
504 case ISD::FP_ROUND:
505 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000506 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000507 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000508 }
509}
510
511/// GetNegatedExpression - If isNegatibleForFree returns true, this function
512/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000513static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000514 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000515 // fneg is removable even if it has multiple uses.
516 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000517
Chris Lattnere49c9742007-05-14 22:04:50 +0000518 // Don't allow anything with multiple uses.
519 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000520
Chris Lattner46980832007-05-25 02:19:06 +0000521 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000523 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000524 case ISD::ConstantFP: {
525 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
526 V.changeSign();
527 return DAG.getConstantFP(V, Op.getValueType());
528 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000529 case ISD::FADD:
530 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000531 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000532
Bill Wendling6fbf5492009-01-30 23:10:18 +0000533 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000534 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000535 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000536 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000537 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000538 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000539 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000540 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000541 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000542 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000543 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000544 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000545 Op.getOperand(0));
546 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000547 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000548 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000549
Bill Wendling6fbf5492009-01-30 23:10:18 +0000550 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000551 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000552 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000553 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000554
Bill Wendling6fbf5492009-01-30 23:10:18 +0000555 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000556 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000557 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000558
Chris Lattnere49c9742007-05-14 22:04:50 +0000559 case ISD::FMUL:
560 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000561 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562
Bill Wendling6fbf5492009-01-30 23:10:18 +0000563 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000564 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000565 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000566 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000567 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000568 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000569 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000570 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000571
Bill Wendling6fbf5492009-01-30 23:10:18 +0000572 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000573 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000574 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000575 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000576 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000577
Chris Lattnere49c9742007-05-14 22:04:50 +0000578 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000579 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000580 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000581 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000582 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000583 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000584 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000585 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000586 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000587 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000588 }
589}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000590
591
Nate Begeman2504fe22005-09-01 23:24:04 +0000592// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
593// that selects between the values 1 and 0, making it equivalent to a setcc.
Scott Michelcf0da6c2009-02-17 22:15:04 +0000594// Also, set the incoming LHS, RHS, and CC references to the appropriate
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000595// nodes based on the type of node we are checking. This simplifies life a
596// bit for the callers.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000597static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
598 SDValue &CC) {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000599 if (N.getOpcode() == ISD::SETCC) {
600 LHS = N.getOperand(0);
601 RHS = N.getOperand(1);
602 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000603 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000604 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000605 if (N.getOpcode() == ISD::SELECT_CC &&
Nate Begeman21158fc2005-09-01 00:19:25 +0000606 N.getOperand(2).getOpcode() == ISD::Constant &&
607 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohmanb72127a2008-03-13 22:13:53 +0000608 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000609 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
610 LHS = N.getOperand(0);
611 RHS = N.getOperand(1);
612 CC = N.getOperand(4);
Nate Begeman21158fc2005-09-01 00:19:25 +0000613 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000614 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000615 return false;
616}
617
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000618// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
619// one use. If this is true, it allows the users to invert the operation for
620// free when it is profitable to do so.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000621static bool isOneUseSetCC(SDValue N) {
622 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000623 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000624 return true;
625 return false;
626}
627
Juergen Ributzka68402822014-01-13 21:49:25 +0000628// \brief Returns the SDNode if it is a constant BuildVector or constant int.
629static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
630 if (isa<ConstantSDNode>(N))
631 return N.getNode();
632 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
633 if(BV && BV->isConstant())
634 return BV;
635 return NULL;
636}
637
Andrew Trickef9de2a2013-05-25 02:42:55 +0000638SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000639 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000640 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000641 if (N0.getOpcode() == Opc) {
642 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
643 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
644 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
645 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
646 if (!OpNode.getNode())
647 return SDValue();
648 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000649 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000650 if (N0.hasOneUse()) {
651 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
652 // use
653 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
654 if (!OpNode.getNode())
655 return SDValue();
656 AddToWorkList(OpNode.getNode());
657 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000658 }
659 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000660 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000661
Juergen Ributzka68402822014-01-13 21:49:25 +0000662 if (N1.getOpcode() == Opc) {
663 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
664 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
665 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
666 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
667 if (!OpNode.getNode())
668 return SDValue();
669 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
670 }
671 if (N1.hasOneUse()) {
672 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
673 // use
674 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
675 if (!OpNode.getNode())
676 return SDValue();
677 AddToWorkList(OpNode.getNode());
678 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
679 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000680 }
681 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000682
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000683 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000684}
685
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000686SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
687 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000688 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
689 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000690 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000691 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000692 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000693 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000694 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000695 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000696 assert((!To[i].getNode() ||
697 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000698 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000699 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000700 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000701 if (AddTo) {
702 // Push the new nodes and any users onto the worklist
703 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000704 if (To[i].getNode()) {
705 AddToWorkList(To[i].getNode());
706 AddUsersToWorkList(To[i].getNode());
707 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000708 }
709 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000710
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000711 // Finally, if the node is now dead, remove it from the graph. The node
712 // may not be dead if the replacement process recursively simplified to
713 // something else needing this node.
714 if (N->use_empty()) {
715 // Nodes can be reintroduced into the worklist. Make sure we do not
716 // process a node that has been replaced.
717 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000718
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000719 // Finally, since the node is now dead, remove it from the graph.
720 DAG.DeleteNode(N);
721 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000722 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000723}
724
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000725void DAGCombiner::
726CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000727 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000728 // are deleted, make sure to remove them from our worklist.
729 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000730 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000731
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000732 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000733 AddToWorkList(TLO.New.getNode());
734 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000735
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000736 // Finally, if the node is now dead, remove it from the graph. The node
737 // may not be dead if the replacement process recursively simplified to
738 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000739 if (TLO.Old.getNode()->use_empty()) {
740 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000741
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000742 // If the operands of this node are only used by the node, they will now
743 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000744 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
745 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
746 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000747
Gabor Greiff304a7a2008-08-28 21:40:38 +0000748 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000749 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000750}
751
752/// SimplifyDemandedBits - Check the specified integer node value to see if
753/// it can be simplified or if things it uses can be simplified by bit
754/// propagation. If so, return true.
755bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000756 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000757 APInt KnownZero, KnownOne;
758 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
759 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000760
Dan Gohmane58ab792009-01-29 01:59:02 +0000761 // Revisit the node.
762 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000763
Dan Gohmane58ab792009-01-29 01:59:02 +0000764 // Replace the old value with the new one.
765 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000766 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000767 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000768 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000769 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000770 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000771
Dan Gohmane58ab792009-01-29 01:59:02 +0000772 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000773 return true;
774}
775
Evan Cheng0abb54d2010-04-24 04:43:44 +0000776void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000777 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000778 EVT VT = Load->getValueType(0);
779 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000780
Evan Cheng0abb54d2010-04-24 04:43:44 +0000781 DEBUG(dbgs() << "\nReplacing.9 ";
782 Load->dump(&DAG);
783 dbgs() << "\nWith: ";
784 Trunc.getNode()->dump(&DAG);
785 dbgs() << '\n');
786 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000787 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
788 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000789 removeFromWorkList(Load);
790 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000791 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000792}
793
794SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
795 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000796 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000797 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000798 EVT MemVT = LD->getMemoryVT();
799 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000800 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000801 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000802 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000803 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000804 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000805 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000806 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000807 }
808
Evan Chenge19aa5c2010-04-19 19:29:22 +0000809 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000810 switch (Opc) {
811 default: break;
812 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000813 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000814 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000815 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000816 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000817 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000818 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000819 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000820 case ISD::Constant: {
821 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000822 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000823 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000824 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000825 }
826
827 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000828 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000829 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000830}
831
Evan Cheng0abb54d2010-04-24 04:43:44 +0000832SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000833 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
834 return SDValue();
835 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000836 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000837 bool Replace = false;
838 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
839 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000840 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000841 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000842
843 if (Replace)
844 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
845 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000846 DAG.getValueType(OldVT));
847}
848
Evan Cheng0abb54d2010-04-24 04:43:44 +0000849SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000850 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000851 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000852 bool Replace = false;
853 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
854 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000855 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000856 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000857
858 if (Replace)
859 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
860 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000861}
862
Evan Chengaf56fac2010-04-16 06:14:10 +0000863/// PromoteIntBinOp - Promote the specified integer binary operation if the
864/// target indicates it is beneficial. e.g. On x86, it's usually better to
865/// promote i16 operations to i32 since i16 instructions are longer.
866SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
867 if (!LegalOperations)
868 return SDValue();
869
870 EVT VT = Op.getValueType();
871 if (VT.isVector() || !VT.isInteger())
872 return SDValue();
873
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000874 // If operation type is 'undesirable', e.g. i16 on x86, consider
875 // promoting it.
876 unsigned Opc = Op.getOpcode();
877 if (TLI.isTypeDesirableForOp(Opc, VT))
878 return SDValue();
879
Evan Chengaf56fac2010-04-16 06:14:10 +0000880 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000881 // Consult target whether it is a good idea to promote this operation and
882 // what's the right type to promote it to.
883 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000884 assert(PVT != VT && "Don't know what type to promote to!");
885
Evan Cheng0abb54d2010-04-24 04:43:44 +0000886 bool Replace0 = false;
887 SDValue N0 = Op.getOperand(0);
888 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
889 if (NN0.getNode() == 0)
Evan Chengf1223bd2010-04-22 20:19:46 +0000890 return SDValue();
891
Evan Cheng0abb54d2010-04-24 04:43:44 +0000892 bool Replace1 = false;
893 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000894 SDValue NN1;
895 if (N0 == N1)
896 NN1 = NN0;
897 else {
898 NN1 = PromoteOperand(N1, PVT, Replace1);
899 if (NN1.getNode() == 0)
900 return SDValue();
901 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000902
Evan Cheng0abb54d2010-04-24 04:43:44 +0000903 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000904 if (NN1.getNode())
905 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000906
907 if (Replace0)
908 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
909 if (Replace1)
910 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000911
Evan Chenge8136902010-04-27 19:48:13 +0000912 DEBUG(dbgs() << "\nPromoting ";
913 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000914 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000915 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000916 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000917 }
918 return SDValue();
919}
920
921/// PromoteIntShiftOp - Promote the specified integer shift operation if the
922/// target indicates it is beneficial. e.g. On x86, it's usually better to
923/// promote i16 operations to i32 since i16 instructions are longer.
924SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
925 if (!LegalOperations)
926 return SDValue();
927
928 EVT VT = Op.getValueType();
929 if (VT.isVector() || !VT.isInteger())
930 return SDValue();
931
932 // If operation type is 'undesirable', e.g. i16 on x86, consider
933 // promoting it.
934 unsigned Opc = Op.getOpcode();
935 if (TLI.isTypeDesirableForOp(Opc, VT))
936 return SDValue();
937
938 EVT PVT = VT;
939 // Consult target whether it is a good idea to promote this operation and
940 // what's the right type to promote it to.
941 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
942 assert(PVT != VT && "Don't know what type to promote to!");
943
Evan Cheng0abb54d2010-04-24 04:43:44 +0000944 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000945 SDValue N0 = Op.getOperand(0);
946 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000947 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000948 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000949 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000950 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000951 N0 = PromoteOperand(N0, PVT, Replace);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000952 if (N0.getNode() == 0)
953 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000954
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000955 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000956 if (Replace)
957 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000958
Evan Chenge8136902010-04-27 19:48:13 +0000959 DEBUG(dbgs() << "\nPromoting ";
960 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000961 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000962 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000963 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000964 }
965 return SDValue();
966}
967
Evan Chenge19aa5c2010-04-19 19:29:22 +0000968SDValue DAGCombiner::PromoteExtend(SDValue Op) {
969 if (!LegalOperations)
970 return SDValue();
971
972 EVT VT = Op.getValueType();
973 if (VT.isVector() || !VT.isInteger())
974 return SDValue();
975
976 // If operation type is 'undesirable', e.g. i16 on x86, consider
977 // promoting it.
978 unsigned Opc = Op.getOpcode();
979 if (TLI.isTypeDesirableForOp(Opc, VT))
980 return SDValue();
981
982 EVT PVT = VT;
983 // Consult target whether it is a good idea to promote this operation and
984 // what's the right type to promote it to.
985 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
986 assert(PVT != VT && "Don't know what type to promote to!");
987 // fold (aext (aext x)) -> (aext x)
988 // fold (aext (zext x)) -> (zext x)
989 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +0000990 DEBUG(dbgs() << "\nPromoting ";
991 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000992 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000993 }
994 return SDValue();
995}
996
997bool DAGCombiner::PromoteLoad(SDValue Op) {
998 if (!LegalOperations)
999 return false;
1000
1001 EVT VT = Op.getValueType();
1002 if (VT.isVector() || !VT.isInteger())
1003 return false;
1004
1005 // If operation type is 'undesirable', e.g. i16 on x86, consider
1006 // promoting it.
1007 unsigned Opc = Op.getOpcode();
1008 if (TLI.isTypeDesirableForOp(Opc, VT))
1009 return false;
1010
1011 EVT PVT = VT;
1012 // Consult target whether it is a good idea to promote this operation and
1013 // what's the right type to promote it to.
1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015 assert(PVT != VT && "Don't know what type to promote to!");
1016
Andrew Trickef9de2a2013-05-25 02:42:55 +00001017 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001018 SDNode *N = Op.getNode();
1019 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001020 EVT MemVT = LD->getMemoryVT();
1021 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001022 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001023 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001024 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001025 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001026 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001027 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001028 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1029
Evan Cheng0abb54d2010-04-24 04:43:44 +00001030 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001031 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001032 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001033 Result.getNode()->dump(&DAG);
1034 dbgs() << '\n');
1035 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001036 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1037 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001038 removeFromWorkList(N);
1039 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001040 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001041 return true;
1042 }
1043 return false;
1044}
1045
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001046
Chris Lattnere49c9742007-05-14 22:04:50 +00001047//===----------------------------------------------------------------------===//
1048// Main DAG Combiner implementation
1049//===----------------------------------------------------------------------===//
1050
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001051void DAGCombiner::Run(CombineLevel AtLevel) {
1052 // set the instance variables, so that the various visit routines may use it.
1053 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001054 LegalOperations = Level >= AfterLegalizeVectorOps;
1055 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001056
Evan Cheng5e7658c2008-08-29 22:21:44 +00001057 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001058 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1059 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001060 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001061
Evan Cheng5e7658c2008-08-29 22:21:44 +00001062 // Create a dummy node (which is not added to allnodes), that adds a reference
1063 // to the root node, preventing it from being deleted, and tracking any
1064 // changes of the root.
1065 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001066
Jim Laskeye7d2c242006-10-17 19:33:52 +00001067 // The root of the dag may dangle to deleted nodes until the dag combiner is
1068 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001069 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001070
James Molloy67b6b112012-02-16 09:17:04 +00001071 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001072 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001073 while (!WorkListContents.empty()) {
1074 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001075 // The WorkListOrder holds the SDNodes in order, but it may contain
1076 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001077 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1078 // worklist *should* contain, and check the node we want to visit is should
1079 // actually be visited.
1080 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001081 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001082 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001083
Evan Cheng5e7658c2008-08-29 22:21:44 +00001084 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1085 // N is deleted from the DAG, since they too may now be dead or may have a
1086 // reduced number of uses, allowing other xforms.
1087 if (N->use_empty() && N != &Dummy) {
1088 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1089 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001090
Evan Cheng5e7658c2008-08-29 22:21:44 +00001091 DAG.DeleteNode(N);
1092 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001093 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001094
Evan Cheng5e7658c2008-08-29 22:21:44 +00001095 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001096
Evan Cheng5e7658c2008-08-29 22:21:44 +00001097 if (RV.getNode() == 0)
1098 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001099
Evan Cheng5e7658c2008-08-29 22:21:44 +00001100 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001101
Evan Cheng5e7658c2008-08-29 22:21:44 +00001102 // If we get back the same node we passed in, rather than a new node or
1103 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001104 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001105 // mechanics for us, we have no work to do in this case.
1106 if (RV.getNode() == N)
1107 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001108
Evan Cheng5e7658c2008-08-29 22:21:44 +00001109 assert(N->getOpcode() != ISD::DELETED_NODE &&
1110 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1111 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001112
Wesley Peck527da1b2010-11-23 03:31:01 +00001113 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001114 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001115 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001116 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001117 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001118
Devang Patelefec7712011-05-23 22:04:42 +00001119 // Transfer debug value.
1120 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001121 WorkListRemover DeadNodes(*this);
1122 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001123 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001124 else {
1125 assert(N->getValueType(0) == RV.getValueType() &&
1126 N->getNumValues() == 1 && "Type mismatch");
1127 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001128 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001129 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001130
Evan Cheng5e7658c2008-08-29 22:21:44 +00001131 // Push the new node and any users onto the worklist
1132 AddToWorkList(RV.getNode());
1133 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001134
Evan Cheng5e7658c2008-08-29 22:21:44 +00001135 // Add any uses of the old node to the worklist in case this node is the
1136 // last one that uses them. They may become dead after this node is
1137 // deleted.
1138 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1139 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001140
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001141 // Finally, if the node is now dead, remove it from the graph. The node
1142 // may not be dead if the replacement process recursively simplified to
1143 // something else needing this node.
1144 if (N->use_empty()) {
1145 // Nodes can be reintroduced into the worklist. Make sure we do not
1146 // process a node that has been replaced.
1147 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001148
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001149 // Finally, since the node is now dead, remove it from the graph.
1150 DAG.DeleteNode(N);
1151 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001152 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001153
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001154 // If the root changed (e.g. it was a dead load, update the root).
1155 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001156 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001157}
1158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001159SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001160 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001161 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001162 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001163 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001164 case ISD::ADD: return visitADD(N);
1165 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001166 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001167 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001168 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001169 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001170 case ISD::MUL: return visitMUL(N);
1171 case ISD::SDIV: return visitSDIV(N);
1172 case ISD::UDIV: return visitUDIV(N);
1173 case ISD::SREM: return visitSREM(N);
1174 case ISD::UREM: return visitUREM(N);
1175 case ISD::MULHU: return visitMULHU(N);
1176 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001177 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1178 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001179 case ISD::SMULO: return visitSMULO(N);
1180 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001181 case ISD::SDIVREM: return visitSDIVREM(N);
1182 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001183 case ISD::AND: return visitAND(N);
1184 case ISD::OR: return visitOR(N);
1185 case ISD::XOR: return visitXOR(N);
1186 case ISD::SHL: return visitSHL(N);
1187 case ISD::SRA: return visitSRA(N);
1188 case ISD::SRL: return visitSRL(N);
1189 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001190 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001191 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001192 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001193 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001194 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001195 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001196 case ISD::SELECT_CC: return visitSELECT_CC(N);
1197 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001198 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1199 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001200 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001201 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1202 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001203 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001204 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001205 case ISD::FADD: return visitFADD(N);
1206 case ISD::FSUB: return visitFSUB(N);
1207 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001208 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001209 case ISD::FDIV: return visitFDIV(N);
1210 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001211 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001212 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1213 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1214 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1215 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1216 case ISD::FP_ROUND: return visitFP_ROUND(N);
1217 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1218 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1219 case ISD::FNEG: return visitFNEG(N);
1220 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001221 case ISD::FFLOOR: return visitFFLOOR(N);
1222 case ISD::FCEIL: return visitFCEIL(N);
1223 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001224 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001225 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001226 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001227 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001228 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001229 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001230 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1231 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001232 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001233 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001234 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001235 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001236 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001237}
1238
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001239SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001240 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001241
1242 // If nothing happened, try a target-specific DAG combine.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001243 if (RV.getNode() == 0) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001244 assert(N->getOpcode() != ISD::DELETED_NODE &&
1245 "Node was deleted but visit returned NULL!");
1246
1247 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1248 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1249
1250 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001251 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001252 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001253
1254 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1255 }
1256 }
1257
Evan Chengf1005572010-04-28 07:10:39 +00001258 // If nothing happened still, try promoting the operation.
1259 if (RV.getNode() == 0) {
1260 switch (N->getOpcode()) {
1261 default: break;
1262 case ISD::ADD:
1263 case ISD::SUB:
1264 case ISD::MUL:
1265 case ISD::AND:
1266 case ISD::OR:
1267 case ISD::XOR:
1268 RV = PromoteIntBinOp(SDValue(N, 0));
1269 break;
1270 case ISD::SHL:
1271 case ISD::SRA:
1272 case ISD::SRL:
1273 RV = PromoteIntShiftOp(SDValue(N, 0));
1274 break;
1275 case ISD::SIGN_EXTEND:
1276 case ISD::ZERO_EXTEND:
1277 case ISD::ANY_EXTEND:
1278 RV = PromoteExtend(SDValue(N, 0));
1279 break;
1280 case ISD::LOAD:
1281 if (PromoteLoad(SDValue(N, 0)))
1282 RV = SDValue(N, 0);
1283 break;
1284 }
1285 }
1286
Scott Michelcf0da6c2009-02-17 22:15:04 +00001287 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001288 // sdisel CSE.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001289 if (RV.getNode() == 0 &&
Evan Cheng31604a62008-03-22 01:55:50 +00001290 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1291 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001292 SDValue N0 = N->getOperand(0);
1293 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001294
Evan Cheng31604a62008-03-22 01:55:50 +00001295 // Constant operands are canonicalized to RHS.
1296 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001297 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001298 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1299 Ops, 2);
Evan Chengfe7610f2008-03-24 23:55:16 +00001300 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001301 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001302 }
1303 }
1304
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001305 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001306}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001307
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001308/// getInputChainForNode - Given a node, return its input chain if it has one,
1309/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001310static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001311 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001312 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001313 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001314 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001315 return N->getOperand(NumOps-1);
1316 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001317 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001318 return N->getOperand(i);
1319 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001320 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001321}
1322
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001323SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001324 // If N has two operands, where one has an input chain equal to the other,
1325 // the 'other' chain is redundant.
1326 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001327 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001328 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001329 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001330 return N->getOperand(1);
1331 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001332
Chris Lattner48fb92f2007-05-16 06:37:59 +00001333 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001334 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001335 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001336 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001337
Jim Laskey708d0db2006-10-04 16:53:27 +00001338 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001339 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001340
Jim Laskey0463e082006-10-07 23:37:56 +00001341 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001342 // encountered.
1343 for (unsigned i = 0; i < TFs.size(); ++i) {
1344 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001345
Jim Laskey708d0db2006-10-04 16:53:27 +00001346 // Check each of the operands.
1347 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001348 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001349
Jim Laskey708d0db2006-10-04 16:53:27 +00001350 switch (Op.getOpcode()) {
1351 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001352 // Entry tokens don't need to be added to the list. They are
1353 // rededundant.
1354 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001355 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001356
Jim Laskey708d0db2006-10-04 16:53:27 +00001357 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001358 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001359 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001360 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001361 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001362 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001363 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001364 Changed = true;
1365 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001366 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001367 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001368
Jim Laskey708d0db2006-10-04 16:53:27 +00001369 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001370 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001371 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001372 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001373 else
1374 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001375 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001376 }
1377 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001378 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001379
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001380 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001381
1382 // If we've change things around then replace token factor.
1383 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001384 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001385 // The entry token is the only possible outcome.
1386 Result = DAG.getEntryNode();
1387 } else {
1388 // New and improved token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001389 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00001390 MVT::Other, &Ops[0], Ops.size());
Nate Begeman02b23c62005-10-13 03:11:28 +00001391 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001392
Jim Laskeydcf983c2006-10-13 23:32:28 +00001393 // Don't add users to work list.
1394 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001395 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001396
Jim Laskey708d0db2006-10-04 16:53:27 +00001397 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001398}
1399
Chris Lattneree322b42008-02-13 07:25:05 +00001400/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001401SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001402 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001403 // Replacing results may cause a different MERGE_VALUES to suddenly
1404 // be CSE'd with N, and carry its uses with it. Iterate until no
1405 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001406 // First add the users of this node to the work list so that they
1407 // can be tried again once they have new operands.
1408 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001409 do {
1410 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001411 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001412 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001413 removeFromWorkList(N);
1414 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001415 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001416}
1417
Evan Cheng92011002007-01-19 17:51:44 +00001418static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001419SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001420 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001421 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001422 SDValue N00 = N0.getOperand(0);
1423 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001424 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001425
Gabor Greiff304a7a2008-08-28 21:40:38 +00001426 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001427 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001428 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001429 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1430 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001431 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001432 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001433 N00.getOperand(1), N01));
1434 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001435 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001436
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001437 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001438}
1439
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001440SDValue DAGCombiner::visitADD(SDNode *N) {
1441 SDValue N0 = N->getOperand(0);
1442 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001443 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1444 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001445 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001446
1447 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001448 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001449 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001450 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001451
1452 // fold (add x, 0) -> x, vector edition
1453 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1454 return N0;
1455 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1456 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001457 }
Bill Wendling0864a752008-12-10 22:36:00 +00001458
Dan Gohman06563a82007-07-03 14:03:57 +00001459 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001460 if (N0.getOpcode() == ISD::UNDEF)
1461 return N0;
1462 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001463 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001464 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001465 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001466 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001467 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001468 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001469 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001470 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001471 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001472 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001473 // fold (add Sym, c) -> Sym+c
1474 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001475 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001476 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001477 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001478 GA->getOffset() +
1479 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001480 // fold ((c1-A)+c2) -> (c1+c2)-A
1481 if (N1C && N0.getOpcode() == ISD::SUB)
1482 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001483 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001484 DAG.getConstant(N1C->getAPIntValue()+
1485 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001486 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001487 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001488 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001489 if (RADD.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001490 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001491 // fold ((0-A) + B) -> B-A
1492 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1493 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001494 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001495 // fold (A + (0-B)) -> A-B
1496 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1497 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001498 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001499 // fold (A+(B-A)) -> B
1500 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001501 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001502 // fold ((B-A)+A) -> B
1503 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1504 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001505 // fold (A+(B-(A+C))) to (B-C)
1506 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001507 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001508 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001509 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001510 // fold (A+(B-(C+A))) to (B-C)
1511 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001512 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001513 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001514 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001515 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001516 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1517 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001518 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001519 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001520 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001521
Dale Johannesen8c766702008-12-02 01:30:54 +00001522 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1523 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1524 SDValue N00 = N0.getOperand(0);
1525 SDValue N01 = N0.getOperand(1);
1526 SDValue N10 = N1.getOperand(0);
1527 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001528
1529 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001530 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1531 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1532 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001533 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001534
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001535 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1536 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001537
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001538 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001539 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001540 APInt LHSZero, LHSOne;
1541 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001542 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001543
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001544 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001545 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001546
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001547 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1548 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001549 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1550 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1551 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1552 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001553 }
1554 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001555
Evan Cheng92011002007-01-19 17:51:44 +00001556 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001557 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001558 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001559 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001560 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001561 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001562 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001563 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001564 }
1565
Dan Gohman954f4902010-01-19 23:30:49 +00001566 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1567 if (N1.getOpcode() == ISD::SHL &&
1568 N1.getOperand(0).getOpcode() == ISD::SUB)
1569 if (ConstantSDNode *C =
1570 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1571 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001572 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1573 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001574 N1.getOperand(0).getOperand(1),
1575 N1.getOperand(1)));
1576 if (N0.getOpcode() == ISD::SHL &&
1577 N0.getOperand(0).getOpcode() == ISD::SUB)
1578 if (ConstantSDNode *C =
1579 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1580 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001581 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1582 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001583 N0.getOperand(0).getOperand(1),
1584 N0.getOperand(1)));
1585
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001586 if (N1.getOpcode() == ISD::AND) {
1587 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001588 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001589 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1590 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001591
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001592 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1593 // and similar xforms where the inner op is either ~0 or 0.
1594 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001595 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001596 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1597 }
1598 }
1599
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001600 // add (sext i1), X -> sub X, (zext i1)
1601 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1602 N0.getOperand(0).getValueType() == MVT::i1 &&
1603 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001604 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001605 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1606 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1607 }
1608
Evan Chengf1005572010-04-28 07:10:39 +00001609 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001610}
1611
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001612SDValue DAGCombiner::visitADDC(SDNode *N) {
1613 SDValue N0 = N->getOperand(0);
1614 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001615 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1616 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001617 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001618
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001619 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001620 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001621 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001622 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001623 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001624
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001625 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001626 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001627 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001628
Chris Lattner47206662007-03-04 20:40:38 +00001629 // fold (addc x, 0) -> x + no carry out
1630 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001631 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001632 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001633
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001634 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001635 APInt LHSZero, LHSOne;
1636 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001637 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001638
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001639 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001640 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001641
Chris Lattner47206662007-03-04 20:40:38 +00001642 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1643 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001644 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001645 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001646 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001647 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001648 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001649
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001650 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001651}
1652
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001653SDValue DAGCombiner::visitADDE(SDNode *N) {
1654 SDValue N0 = N->getOperand(0);
1655 SDValue N1 = N->getOperand(1);
1656 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001657 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1658 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001659
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001660 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001661 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001662 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001663 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001664
Chris Lattner47206662007-03-04 20:40:38 +00001665 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001666 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001667 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001668
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001669 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001670}
1671
Eric Christophere5ca1e02011-02-16 04:50:12 +00001672// Since it may not be valid to emit a fold to zero for vector initializers
1673// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001674static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001675 SelectionDAG &DAG,
1676 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001677 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001678 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001679 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1680 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001681 return SDValue();
1682}
1683
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001684SDValue DAGCombiner::visitSUB(SDNode *N) {
1685 SDValue N0 = N->getOperand(0);
1686 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001687 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1688 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001689 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1690 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001691 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001692
Dan Gohmana8665142007-06-25 16:23:39 +00001693 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001694 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001695 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001696 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001697
1698 // fold (sub x, 0) -> x, vector edition
1699 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1700 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001701 }
Bill Wendling0864a752008-12-10 22:36:00 +00001702
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001703 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001704 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001705 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001706 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001707 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001708 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001709 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001710 // fold (sub x, c) -> (add x, -c)
1711 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001712 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001713 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001714 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1715 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001716 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001717 // fold A-(A-B) -> B
1718 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1719 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001720 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001721 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001722 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001723 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001724 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001725 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001726 // fold C2-(A+C1) -> (C2-C1)-A
1727 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001728 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1729 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001730 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001731 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001732 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001733 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001734 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001735 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1736 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001737 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001738 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001739 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001740 // fold ((A+(C+B))-B) -> A+C
1741 if (N0.getOpcode() == ISD::ADD &&
1742 N0.getOperand(1).getOpcode() == ISD::ADD &&
1743 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001744 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001745 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001746 // fold ((A-(B-C))-C) -> A-B
1747 if (N0.getOpcode() == ISD::SUB &&
1748 N0.getOperand(1).getOpcode() == ISD::SUB &&
1749 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001750 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001751 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001752
Dan Gohman06563a82007-07-03 14:03:57 +00001753 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001754 if (N0.getOpcode() == ISD::UNDEF)
1755 return N0;
1756 if (N1.getOpcode() == ISD::UNDEF)
1757 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001758
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001759 // If the relocation model supports it, consider symbol offsets.
1760 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001761 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001762 // fold (sub Sym, c) -> Sym-c
1763 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001764 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001765 GA->getOffset() -
1766 (uint64_t)N1C->getSExtValue());
1767 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1768 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1769 if (GA->getGlobal() == GB->getGlobal())
1770 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1771 VT);
1772 }
1773
Evan Chengf1005572010-04-28 07:10:39 +00001774 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001775}
1776
Craig Topper43a1bd62012-01-07 09:06:39 +00001777SDValue DAGCombiner::visitSUBC(SDNode *N) {
1778 SDValue N0 = N->getOperand(0);
1779 SDValue N1 = N->getOperand(1);
1780 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1781 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1782 EVT VT = N0.getValueType();
1783
1784 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001785 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001786 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1787 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001788 MVT::Glue));
1789
1790 // fold (subc x, x) -> 0 + no borrow
1791 if (N0 == N1)
1792 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001793 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001794 MVT::Glue));
1795
1796 // fold (subc x, 0) -> x + no borrow
1797 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001798 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001799 MVT::Glue));
1800
1801 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1802 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001803 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1804 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001805 MVT::Glue));
1806
1807 return SDValue();
1808}
1809
1810SDValue DAGCombiner::visitSUBE(SDNode *N) {
1811 SDValue N0 = N->getOperand(0);
1812 SDValue N1 = N->getOperand(1);
1813 SDValue CarryIn = N->getOperand(2);
1814
1815 // fold (sube x, y, false) -> (subc x, y)
1816 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001817 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001818
1819 return SDValue();
1820}
1821
Jack Carterd4e96152013-10-17 01:34:33 +00001822/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1823/// elements are all the same constant or undefined.
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001824static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1825 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1826 if (!C)
1827 return false;
1828
1829 APInt SplatUndef;
1830 unsigned SplatBitSize;
1831 bool HasAnyUndefs;
1832 EVT EltVT = N->getValueType(0).getVectorElementType();
1833 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1834 HasAnyUndefs) &&
1835 EltVT.getSizeInBits() >= SplatBitSize);
1836}
1837
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001838SDValue DAGCombiner::visitMUL(SDNode *N) {
1839 SDValue N0 = N->getOperand(0);
1840 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001841 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001842
Dan Gohman06563a82007-07-03 14:03:57 +00001843 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001844 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001845 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001846
1847 bool N0IsConst = false;
1848 bool N1IsConst = false;
1849 APInt ConstValue0, ConstValue1;
1850 // fold vector ops
1851 if (VT.isVector()) {
1852 SDValue FoldedVOp = SimplifyVBinOp(N);
1853 if (FoldedVOp.getNode()) return FoldedVOp;
1854
1855 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1856 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1857 } else {
1858 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001859 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1860 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001861 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001862 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1863 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001864 }
1865
Nate Begeman21158fc2005-09-01 00:19:25 +00001866 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001867 if (N0IsConst && N1IsConst)
1868 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1869
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001870 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001871 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001872 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001873 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001874 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001875 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001876 // We require a splat of the entire scalar bit width for non-contiguous
1877 // bit patterns.
1878 bool IsFullSplat =
1879 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001880 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001881 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001882 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001883 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001884 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001885 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001886 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001887 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001888 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001889 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001890 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001891 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001892 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001893 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001894 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001895 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001896 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001897 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001898 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001899 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001900 DAG.getConstant(Log2Val,
1901 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001902 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001903
1904 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001905 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001906 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001907 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1908 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001909 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001910 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001911 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001912 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001913 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001914 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001915
Chris Lattner324871e2006-03-01 03:44:24 +00001916 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1917 // use.
1918 {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001919 SDValue Sh(0,0), Y(0,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001920 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001921 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001922 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1923 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001924 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001925 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001926 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001927 isa<ConstantSDNode>(N1.getOperand(1)) &&
1928 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001929 Sh = N1; Y = N0;
1930 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001931
Gabor Greiff304a7a2008-08-28 21:40:38 +00001932 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001933 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001934 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001935 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001936 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001937 }
1938 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001939
Chris Lattnerf29f5202006-03-04 23:33:26 +00001940 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001941 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1942 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001944 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1945 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001946 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001947 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001948 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001949
Nate Begeman22e251a2006-02-03 06:46:56 +00001950 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001951 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001952 if (RMUL.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001953 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001954
Evan Chengf1005572010-04-28 07:10:39 +00001955 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001956}
1957
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001958SDValue DAGCombiner::visitSDIV(SDNode *N) {
1959 SDValue N0 = N->getOperand(0);
1960 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001961 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1962 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001963 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001964
Dan Gohmana8665142007-06-25 16:23:39 +00001965 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001966 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001967 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001968 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001969 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001970
Nate Begeman21158fc2005-09-01 00:19:25 +00001971 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001972 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001973 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001974 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001975 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001976 return N0;
1977 // fold (sdiv X, -1) -> 0-X
1978 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001979 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00001980 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00001981 // If we know the sign bits of both operands are zero, strength reduce to a
1982 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00001983 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00001984 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001985 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00001986 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00001987 }
Nate Begeman57b35672006-02-17 07:26:20 +00001988 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedmanf9081a82011-12-07 03:55:52 +00001989 if (N1C && !N1C->isNullValue() &&
Eli Friedmane9e356a2011-10-27 02:06:39 +00001990 (N1C->getAPIntValue().isPowerOf2() ||
1991 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00001992 // If dividing by powers of two is cheap, then don't perform the following
1993 // fold.
1994 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001995 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00001996
Eli Friedmane9e356a2011-10-27 02:06:39 +00001997 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00001998
Chris Lattner471627c2006-02-16 08:02:36 +00001999 // Splat the sign bit into the register
Andrew Trickef9de2a2013-05-25 02:42:55 +00002000 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling5b663e72009-01-30 02:52:17 +00002001 DAG.getConstant(VT.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002002 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002003 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002004
Chris Lattner471627c2006-02-16 08:02:36 +00002005 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002006 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling5b663e72009-01-30 02:52:17 +00002007 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002008 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002009 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002010 AddToWorkList(SRL.getNode());
2011 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002012 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002013 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002014
Nate Begeman4dd38312005-10-21 00:02:42 +00002015 // If we're dividing by a positive value, we're done. Otherwise, we must
2016 // negate the result.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002017 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002018 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002019
Gabor Greiff304a7a2008-08-28 21:40:38 +00002020 AddToWorkList(SRA.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002021 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002022 DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002023 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002024
Nate Begemanc6f067a2005-10-20 02:15:44 +00002025 // if integer divide is expensive and we satisfy the requirements, emit an
2026 // alternate sequence.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002027 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002028 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002029 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002030 }
Dan Gohmana8665142007-06-25 16:23:39 +00002031
Dan Gohman06563a82007-07-03 14:03:57 +00002032 // undef / X -> 0
2033 if (N0.getOpcode() == ISD::UNDEF)
2034 return DAG.getConstant(0, VT);
2035 // X / undef -> undef
2036 if (N1.getOpcode() == ISD::UNDEF)
2037 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002038
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002039 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002040}
2041
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002042SDValue DAGCombiner::visitUDIV(SDNode *N) {
2043 SDValue N0 = N->getOperand(0);
2044 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002045 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2046 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00002047 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002048
Dan Gohmana8665142007-06-25 16:23:39 +00002049 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002050 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002051 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002052 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002053 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002054
Nate Begeman21158fc2005-09-01 00:19:25 +00002055 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002056 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002057 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002058 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002059 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002060 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002061 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002062 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002063 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002064 if (N1.getOpcode() == ISD::SHL) {
2065 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002066 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002067 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002068 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002069 N1.getOperand(1),
2070 DAG.getConstant(SHC->getAPIntValue()
2071 .logBase2(),
2072 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002073 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002074 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002075 }
2076 }
2077 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002078 // fold (udiv x, c) -> alternate
Dan Gohmanb72127a2008-03-13 22:13:53 +00002079 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002080 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002081 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002082 }
Dan Gohmana8665142007-06-25 16:23:39 +00002083
Dan Gohman06563a82007-07-03 14:03:57 +00002084 // undef / X -> 0
2085 if (N0.getOpcode() == ISD::UNDEF)
2086 return DAG.getConstant(0, VT);
2087 // X / undef -> undef
2088 if (N1.getOpcode() == ISD::UNDEF)
2089 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002090
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002091 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002092}
2093
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002094SDValue DAGCombiner::visitSREM(SDNode *N) {
2095 SDValue N0 = N->getOperand(0);
2096 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2098 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002099 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002100
Nate Begeman21158fc2005-09-01 00:19:25 +00002101 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002102 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002103 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002104 // If we know the sign bits of both operands are zero, strength reduce to a
2105 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002106 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002107 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002108 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002109 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002110
Dan Gohman9a693412007-11-26 23:46:11 +00002111 // If X/C can be simplified by the division-by-constant logic, lower
2112 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002113 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002114 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002115 AddToWorkList(Div.getNode());
2116 SDValue OptimizedDiv = combine(Div.getNode());
2117 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002118 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002119 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002120 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002121 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002122 return Sub;
2123 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002124 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002125
Dan Gohman06563a82007-07-03 14:03:57 +00002126 // undef % X -> 0
2127 if (N0.getOpcode() == ISD::UNDEF)
2128 return DAG.getConstant(0, VT);
2129 // X % undef -> undef
2130 if (N1.getOpcode() == ISD::UNDEF)
2131 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002132
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002133 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002134}
2135
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002136SDValue DAGCombiner::visitUREM(SDNode *N) {
2137 SDValue N0 = N->getOperand(0);
2138 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002139 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2140 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002141 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002142
Nate Begeman21158fc2005-09-01 00:19:25 +00002143 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002144 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002145 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002146 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002147 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002148 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002149 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002150 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2151 if (N1.getOpcode() == ISD::SHL) {
2152 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002153 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002154 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002155 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002156 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002157 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002158 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002159 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002160 }
2161 }
2162 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002163
Dan Gohman9a693412007-11-26 23:46:11 +00002164 // If X/C can be simplified by the division-by-constant logic, lower
2165 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002166 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002167 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002168 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002169 SDValue OptimizedDiv = combine(Div.getNode());
2170 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002171 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002172 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002173 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002174 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002175 return Sub;
2176 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002177 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002178
Dan Gohman06563a82007-07-03 14:03:57 +00002179 // undef % X -> 0
2180 if (N0.getOpcode() == ISD::UNDEF)
2181 return DAG.getConstant(0, VT);
2182 // X % undef -> undef
2183 if (N1.getOpcode() == ISD::UNDEF)
2184 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002185
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002186 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002187}
2188
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002189SDValue DAGCombiner::visitMULHS(SDNode *N) {
2190 SDValue N0 = N->getOperand(0);
2191 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002193 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002194 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002195
Nate Begeman21158fc2005-09-01 00:19:25 +00002196 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002197 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002198 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002199 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002200 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002201 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002202 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002203 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002204 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002205 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002206 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002207
Chris Lattner10bd29f2010-12-13 08:39:01 +00002208 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2209 // plus a shift.
2210 if (VT.isSimple() && !VT.isVector()) {
2211 MVT Simple = VT.getSimpleVT();
2212 unsigned SimpleSize = Simple.getSizeInBits();
2213 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2214 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2215 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2216 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2217 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002218 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002219 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002220 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2221 }
2222 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002223
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002224 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002225}
2226
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002227SDValue DAGCombiner::visitMULHU(SDNode *N) {
2228 SDValue N0 = N->getOperand(0);
2229 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002231 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002232 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002233
Nate Begeman21158fc2005-09-01 00:19:25 +00002234 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002235 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002236 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002237 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002238 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002239 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002240 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002241 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002242 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002243
Chris Lattner10bd29f2010-12-13 08:39:01 +00002244 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2245 // plus a shift.
2246 if (VT.isSimple() && !VT.isVector()) {
2247 MVT Simple = VT.getSimpleVT();
2248 unsigned SimpleSize = Simple.getSizeInBits();
2249 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2250 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2251 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2252 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2253 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2254 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002255 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002256 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2257 }
2258 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002259
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002260 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002261}
2262
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002263/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2264/// compute two values. LoOp and HiOp give the opcodes for the two computations
2265/// that are being performed. Return true if a simplification was made.
2266///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002267SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002268 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002269 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002270 bool HiExists = N->hasAnyUseOfValue(1);
2271 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002272 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002273 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002274 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002275 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002276 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002277 }
2278
2279 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002280 bool LoExists = N->hasAnyUseOfValue(0);
2281 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002282 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002283 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002284 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002285 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002286 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002287 }
2288
Evan Chengece4c682007-11-08 09:25:29 +00002289 // If both halves are used, return as it is.
2290 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002291 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002292
2293 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002294 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002295 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002296 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002297 AddToWorkList(Lo.getNode());
2298 SDValue LoOpt = combine(Lo.getNode());
2299 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002300 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002301 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002302 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002303 }
2304
Evan Chengece4c682007-11-08 09:25:29 +00002305 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002306 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002307 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002308 AddToWorkList(Hi.getNode());
2309 SDValue HiOpt = combine(Hi.getNode());
2310 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002311 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002312 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002313 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002314 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002315
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002316 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002317}
2318
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002319SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2320 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002321 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002322
Chris Lattner15090e12010-12-15 06:04:19 +00002323 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002324 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002325
2326 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2327 // plus a shift.
2328 if (VT.isSimple() && !VT.isVector()) {
2329 MVT Simple = VT.getSimpleVT();
2330 unsigned SimpleSize = Simple.getSizeInBits();
2331 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2332 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2333 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2334 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2335 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2336 // Compute the high part as N1.
2337 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002338 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002339 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2340 // Compute the low part as N0.
2341 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2342 return CombineTo(N, Lo, Hi);
2343 }
2344 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002345
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002346 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002347}
2348
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002349SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2350 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002351 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002352
Chris Lattner15090e12010-12-15 06:04:19 +00002353 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002354 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002355
Chris Lattner15090e12010-12-15 06:04:19 +00002356 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2357 // plus a shift.
2358 if (VT.isSimple() && !VT.isVector()) {
2359 MVT Simple = VT.getSimpleVT();
2360 unsigned SimpleSize = Simple.getSizeInBits();
2361 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2362 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2363 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2364 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2365 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2366 // Compute the high part as N1.
2367 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002368 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002369 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2370 // Compute the low part as N0.
2371 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2372 return CombineTo(N, Lo, Hi);
2373 }
2374 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002375
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002376 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002377}
2378
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002379SDValue DAGCombiner::visitSMULO(SDNode *N) {
2380 // (smulo x, 2) -> (saddo x, x)
2381 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2382 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002383 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002384 N->getOperand(0), N->getOperand(0));
2385
2386 return SDValue();
2387}
2388
2389SDValue DAGCombiner::visitUMULO(SDNode *N) {
2390 // (umulo x, 2) -> (uaddo x, x)
2391 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002393 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002394 N->getOperand(0), N->getOperand(0));
2395
2396 return SDValue();
2397}
2398
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002399SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2400 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002401 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002402
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002403 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002404}
2405
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002406SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2407 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002408 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002409
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002410 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002411}
2412
Chris Lattner8d6fc202006-05-05 05:51:50 +00002413/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2414/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002415SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2416 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002417 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002418 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002419
Dan Gohmandd5286d2010-01-14 03:08:49 +00002420 // Bail early if none of these transforms apply.
2421 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2422
Chris Lattner002ee912006-05-05 06:31:05 +00002423 // For each of OP in AND/OR/XOR:
2424 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2425 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2426 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002427 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002428 //
2429 // do not sink logical op inside of a vector extend, since it may combine
2430 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002431 EVT Op0VT = N0.getOperand(0).getValueType();
2432 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002433 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002434 // Avoid infinite looping with PromoteIntBinOp.
2435 (N0.getOpcode() == ISD::ANY_EXTEND &&
2436 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002437 (N0.getOpcode() == ISD::TRUNCATE &&
2438 (!TLI.isZExtFree(VT, Op0VT) ||
2439 !TLI.isTruncateFree(Op0VT, VT)) &&
2440 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002441 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002442 Op0VT == N1.getOperand(0).getValueType() &&
2443 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002444 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002445 N0.getOperand(0).getValueType(),
2446 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002447 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002448 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002450
Chris Lattner5ac42932006-05-05 06:10:43 +00002451 // For each of OP in SHL/SRL/SRA/AND...
2452 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2453 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2454 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002455 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002456 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002457 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002458 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002459 N0.getOperand(0).getValueType(),
2460 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002461 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002462 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002463 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002464 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002465
Nadav Rotemb0783502012-04-01 19:31:22 +00002466 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2467 // Only perform this optimization after type legalization and before
2468 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2469 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2470 // we don't want to undo this promotion.
2471 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2472 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002473 if ((N0.getOpcode() == ISD::BITCAST ||
2474 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2475 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002476 SDValue In0 = N0.getOperand(0);
2477 SDValue In1 = N1.getOperand(0);
2478 EVT In0Ty = In0.getValueType();
2479 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002480 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002481 // If both incoming values are integers, and the original types are the
2482 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002483 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002484 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2485 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002486 AddToWorkList(Op.getNode());
2487 return BC;
2488 }
2489 }
2490
2491 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2492 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2493 // If both shuffles use the same mask, and both shuffle within a single
2494 // vector, then it is worthwhile to move the swizzle after the operation.
2495 // The type-legalizer generates this pattern when loading illegal
2496 // vector types from memory. In many cases this allows additional shuffle
2497 // optimizations.
Craig Topper9c3da312012-04-09 07:19:09 +00002498 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2499 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2500 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002501 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2502 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002503
2504 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2505 "Inputs to shuffles are not the same type");
Nadav Rotemb0783502012-04-01 19:31:22 +00002506
2507 unsigned NumElts = VT.getVectorNumElements();
Nadav Rotemb0783502012-04-01 19:31:22 +00002508
2509 // Check that both shuffles use the same mask. The masks are known to be of
2510 // the same length because the result vector type is the same.
2511 bool SameMask = true;
2512 for (unsigned i = 0; i != NumElts; ++i) {
2513 int Idx0 = SVN0->getMaskElt(i);
2514 int Idx1 = SVN1->getMaskElt(i);
2515 if (Idx0 != Idx1) {
2516 SameMask = false;
2517 break;
2518 }
2519 }
2520
Craig Topper9c3da312012-04-09 07:19:09 +00002521 if (SameMask) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002522 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
Craig Topper9c3da312012-04-09 07:19:09 +00002523 N0.getOperand(0), N1.getOperand(0));
Nadav Rotemb0783502012-04-01 19:31:22 +00002524 AddToWorkList(Op.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002525 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
Craig Topper9c3da312012-04-09 07:19:09 +00002526 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
Nadav Rotemb0783502012-04-01 19:31:22 +00002527 }
2528 }
Craig Topper9c3da312012-04-09 07:19:09 +00002529
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002530 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002531}
2532
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002533SDValue DAGCombiner::visitAND(SDNode *N) {
2534 SDValue N0 = N->getOperand(0);
2535 SDValue N1 = N->getOperand(1);
2536 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002537 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2538 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002539 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002540 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002541
Dan Gohmana8665142007-06-25 16:23:39 +00002542 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002543 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002544 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002545 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002546
2547 // fold (and x, 0) -> 0, vector edition
2548 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2549 return N0;
2550 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2551 return N1;
2552
2553 // fold (and x, -1) -> x, vector edition
2554 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2555 return N1;
2556 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2557 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002558 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002559
Dan Gohman06563a82007-07-03 14:03:57 +00002560 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002561 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002562 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002563 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002564 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002565 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002566 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002567 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002568 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002569 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002570 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002571 return N0;
2572 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002573 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002574 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002575 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002576 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002577 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002578 if (RAND.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00002579 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002580 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002581 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002582 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002583 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002584 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002585 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2586 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002587 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002588 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002589 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002590 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002591 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002592 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002593
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002594 // Replace uses of the AND with uses of the Zero extend node.
2595 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002596
Chris Lattner49beaf42006-02-02 07:17:31 +00002597 // We actually want to replace all uses of the any_extend with the
2598 // zero_extend, to avoid duplicating things. This will later cause this
2599 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002600 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002601 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002602 }
2603 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002604 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002605 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2606 // already be zero by virtue of the width of the base type of the load.
2607 //
2608 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2609 // more cases.
2610 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2611 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2612 N0.getOpcode() == ISD::LOAD) {
2613 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2614 N0 : N0.getOperand(0) );
2615
2616 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2617 // This can be a pure constant or a vector splat, in which case we treat the
2618 // vector as a scalar and use the splat value.
2619 APInt Constant = APInt::getNullValue(1);
2620 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2621 Constant = C->getAPIntValue();
2622 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2623 APInt SplatValue, SplatUndef;
2624 unsigned SplatBitSize;
2625 bool HasAnyUndefs;
2626 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2627 SplatBitSize, HasAnyUndefs);
2628 if (IsSplat) {
2629 // Undef bits can contribute to a possible optimisation if set, so
2630 // set them.
2631 SplatValue |= SplatUndef;
2632
2633 // The splat value may be something like "0x00FFFFFF", which means 0 for
2634 // the first vector value and FF for the rest, repeating. We need a mask
2635 // that will apply equally to all members of the vector, so AND all the
2636 // lanes of the constant together.
2637 EVT VT = Vector->getValueType(0);
2638 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002639
2640 // If the splat value has been compressed to a bitlength lower
2641 // than the size of the vector lane, we need to re-expand it to
2642 // the lane size.
2643 if (BitWidth > SplatBitSize)
2644 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2645 SplatBitSize < BitWidth;
2646 SplatBitSize = SplatBitSize * 2)
2647 SplatValue |= SplatValue.shl(SplatBitSize);
2648
James Molloy862fe492012-02-20 12:02:38 +00002649 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002650 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002651 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2652 }
2653 }
2654
2655 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2656 // actually legal and isn't going to get expanded, else this is a false
2657 // optimisation.
2658 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2659 Load->getMemoryVT());
2660
2661 // Resize the constant to the same size as the original memory access before
2662 // extension. If it is still the AllOnesValue then this AND is completely
2663 // unneeded.
2664 Constant =
2665 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2666
2667 bool B;
2668 switch (Load->getExtensionType()) {
2669 default: B = false; break;
2670 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2671 case ISD::ZEXTLOAD:
2672 case ISD::NON_EXTLOAD: B = true; break;
2673 }
2674
2675 if (B && Constant.isAllOnesValue()) {
2676 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2677 // preserve semantics once we get rid of the AND.
2678 SDValue NewLoad(Load, 0);
2679 if (Load->getExtensionType() == ISD::EXTLOAD) {
2680 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002681 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002682 Load->getChain(), Load->getBasePtr(),
2683 Load->getOffset(), Load->getMemoryVT(),
2684 Load->getMemOperand());
2685 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002686 if (Load->getNumValues() == 3) {
2687 // PRE/POST_INC loads have 3 values.
2688 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2689 NewLoad.getValue(2) };
2690 CombineTo(Load, To, 3, true);
2691 } else {
2692 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2693 }
James Molloy862fe492012-02-20 12:02:38 +00002694 }
2695
2696 // Fold the AND away, taking care not to fold to the old load node if we
2697 // replaced it.
2698 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2699
2700 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2701 }
2702 }
Nate Begeman049b7482005-09-09 19:49:52 +00002703 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2704 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2705 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2706 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002707
Nate Begeman049b7482005-09-09 19:49:52 +00002708 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002709 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002710 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002711 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002712 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002713 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002714 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002715 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002716 }
Bill Wendling86171912009-01-30 20:43:18 +00002717 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002718 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002719 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002720 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002721 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002722 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002723 }
Bill Wendling86171912009-01-30 20:43:18 +00002724 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002725 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002726 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002727 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002728 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002729 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002730 }
2731 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002732 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2733 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2734 Op0 == Op1 && LL.getValueType().isInteger() &&
2735 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2736 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2737 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2738 cast<ConstantSDNode>(RR)->isNullValue()))) {
2739 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2740 LL, DAG.getConstant(1, LL.getValueType()));
2741 AddToWorkList(ADDNode.getNode());
2742 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2743 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2744 }
Nate Begeman049b7482005-09-09 19:49:52 +00002745 // canonicalize equivalent to ll == rl
2746 if (LL == RR && LR == RL) {
2747 Op1 = ISD::getSetCCSwappedOperands(Op1);
2748 std::swap(RL, RR);
2749 }
2750 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002751 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002752 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002753 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002754 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002755 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2756 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002757 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002758 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002759 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002760 }
2761 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002762
Bill Wendling86171912009-01-30 20:43:18 +00002763 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002764 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002765 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002766 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002767 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002768
Nate Begemandc7bba92006-02-03 22:24:05 +00002769 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2770 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002771 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002772 SimplifyDemandedBits(SDValue(N, 0)))
2773 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002774
Nate Begeman02b23c62005-10-13 03:11:28 +00002775 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002776 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002777 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002778 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002779 // If we zero all the possible extended bits, then we can turn this into
2780 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002781 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002782 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002783 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002784 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002785 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002786 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002787 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002788 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002789 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002790 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002791 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002792 }
2793 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002794 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002795 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002796 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002797 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002798 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002799 // If we zero all the possible extended bits, then we can turn this into
2800 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002801 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002802 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002803 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002804 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002805 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002806 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002807 LN0->getChain(), LN0->getBasePtr(),
2808 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002809 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002810 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002811 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002812 }
2813 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002814
Chris Lattnerf0032b32006-02-28 06:49:37 +00002815 // fold (and (load x), 255) -> (zextload x, i8)
2816 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002817 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2818 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2819 (N0.getOpcode() == ISD::ANY_EXTEND &&
2820 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2821 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2822 LoadSDNode *LN0 = HasAnyExt
2823 ? cast<LoadSDNode>(N0.getOperand(0))
2824 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002825 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002826 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002827 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002828 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2829 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2830 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002831
Evan Cheng166a4e62010-01-06 19:38:29 +00002832 if (ExtVT == LoadedVT &&
2833 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002834 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002835
2836 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002837 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002838 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2839 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002840 AddToWorkList(N);
2841 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2842 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2843 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002844
Chris Lattner88de3842010-01-07 21:53:27 +00002845 // Do not change the width of a volatile load.
2846 // Do not generate loads of non-round integer types since these can
2847 // be expensive (and would be wrong if the type is not byte sized).
2848 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2849 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2850 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002851
Chris Lattner88de3842010-01-07 21:53:27 +00002852 unsigned Alignment = LN0->getAlignment();
2853 SDValue NewPtr = LN0->getBasePtr();
2854
2855 // For big endian targets, we need to add an offset to the pointer
2856 // to load the correct bytes. For little endian systems, we merely
2857 // need to read fewer bytes from the same pointer.
2858 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002859 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2860 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2861 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002862 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002863 NewPtr, DAG.getConstant(PtrOff, PtrType));
2864 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002865 }
Chris Lattner88de3842010-01-07 21:53:27 +00002866
2867 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002868
Chris Lattner88de3842010-01-07 21:53:27 +00002869 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2870 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002871 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002872 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002873 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002874 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002875 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002876 AddToWorkList(N);
2877 CombineTo(LN0, Load, Load.getValue(1));
2878 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002879 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002880 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002881 }
2882 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002883
Evan Chenge6a3b032012-07-17 18:54:11 +00002884 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2885 VT.getSizeInBits() <= 64) {
2886 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2887 APInt ADDC = ADDI->getAPIntValue();
2888 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2889 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2890 // immediate for an add, but it is legal if its top c2 bits are set,
2891 // transform the ADD so the immediate doesn't need to be materialized
2892 // in a register.
2893 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2894 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2895 SRLI->getZExtValue());
2896 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2897 ADDC |= Mask;
2898 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2899 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002900 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002901 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2902 CombineTo(N0.getNode(), NewAdd);
2903 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2904 }
2905 }
2906 }
2907 }
2908 }
2909 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002910
Tim Northover819bfb52013-08-27 13:46:45 +00002911 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2912 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2913 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2914 N0.getOperand(1), false);
2915 if (BSwap.getNode())
2916 return BSwap;
2917 }
2918
Evan Chengf1005572010-04-28 07:10:39 +00002919 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002920}
2921
Evan Cheng4c0bd962011-06-21 06:01:08 +00002922/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2923///
2924SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2925 bool DemandHighBits) {
2926 if (!LegalOperations)
2927 return SDValue();
2928
2929 EVT VT = N->getValueType(0);
2930 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2931 return SDValue();
2932 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2933 return SDValue();
2934
2935 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2936 bool LookPassAnd0 = false;
2937 bool LookPassAnd1 = false;
2938 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2939 std::swap(N0, N1);
2940 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2941 std::swap(N0, N1);
2942 if (N0.getOpcode() == ISD::AND) {
2943 if (!N0.getNode()->hasOneUse())
2944 return SDValue();
2945 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2946 if (!N01C || N01C->getZExtValue() != 0xFF00)
2947 return SDValue();
2948 N0 = N0.getOperand(0);
2949 LookPassAnd0 = true;
2950 }
2951
2952 if (N1.getOpcode() == ISD::AND) {
2953 if (!N1.getNode()->hasOneUse())
2954 return SDValue();
2955 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2956 if (!N11C || N11C->getZExtValue() != 0xFF)
2957 return SDValue();
2958 N1 = N1.getOperand(0);
2959 LookPassAnd1 = true;
2960 }
2961
2962 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2963 std::swap(N0, N1);
2964 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2965 return SDValue();
2966 if (!N0.getNode()->hasOneUse() ||
2967 !N1.getNode()->hasOneUse())
2968 return SDValue();
2969
2970 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2971 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2972 if (!N01C || !N11C)
2973 return SDValue();
2974 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2975 return SDValue();
2976
2977 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2978 SDValue N00 = N0->getOperand(0);
2979 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2980 if (!N00.getNode()->hasOneUse())
2981 return SDValue();
2982 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2983 if (!N001C || N001C->getZExtValue() != 0xFF)
2984 return SDValue();
2985 N00 = N00.getOperand(0);
2986 LookPassAnd0 = true;
2987 }
2988
2989 SDValue N10 = N1->getOperand(0);
2990 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2991 if (!N10.getNode()->hasOneUse())
2992 return SDValue();
2993 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2994 if (!N101C || N101C->getZExtValue() != 0xFF00)
2995 return SDValue();
2996 N10 = N10.getOperand(0);
2997 LookPassAnd1 = true;
2998 }
2999
3000 if (N00 != N10)
3001 return SDValue();
3002
Tim Northover819bfb52013-08-27 13:46:45 +00003003 // Make sure everything beyond the low halfword gets set to zero since the SRL
3004 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003005 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003006 if (DemandHighBits && OpSizeInBits > 16) {
3007 // If the left-shift isn't masked out then the only way this is a bswap is
3008 // if all bits beyond the low 8 are 0. In that case the entire pattern
3009 // reduces to a left shift anyway: leave it for other parts of the combiner.
3010 if (!LookPassAnd0)
3011 return SDValue();
3012
3013 // However, if the right shift isn't masked out then it might be because
3014 // it's not needed. See if we can spot that too.
3015 if (!LookPassAnd1 &&
3016 !DAG.MaskedValueIsZero(
3017 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3018 return SDValue();
3019 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003020
Andrew Trickef9de2a2013-05-25 02:42:55 +00003021 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003022 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003023 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003024 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3025 return Res;
3026}
3027
3028/// isBSwapHWordElement - Return true if the specified node is an element
3029/// that makes up a 32-bit packed halfword byteswap. i.e.
3030/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003031static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003032 if (!N.getNode()->hasOneUse())
3033 return false;
3034
3035 unsigned Opc = N.getOpcode();
3036 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3037 return false;
3038
3039 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3040 if (!N1C)
3041 return false;
3042
3043 unsigned Num;
3044 switch (N1C->getZExtValue()) {
3045 default:
3046 return false;
3047 case 0xFF: Num = 0; break;
3048 case 0xFF00: Num = 1; break;
3049 case 0xFF0000: Num = 2; break;
3050 case 0xFF000000: Num = 3; break;
3051 }
3052
3053 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3054 SDValue N0 = N.getOperand(0);
3055 if (Opc == ISD::AND) {
3056 if (Num == 0 || Num == 2) {
3057 // (x >> 8) & 0xff
3058 // (x >> 8) & 0xff0000
3059 if (N0.getOpcode() != ISD::SRL)
3060 return false;
3061 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3062 if (!C || C->getZExtValue() != 8)
3063 return false;
3064 } else {
3065 // (x << 8) & 0xff00
3066 // (x << 8) & 0xff000000
3067 if (N0.getOpcode() != ISD::SHL)
3068 return false;
3069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3070 if (!C || C->getZExtValue() != 8)
3071 return false;
3072 }
3073 } else if (Opc == ISD::SHL) {
3074 // (x & 0xff) << 8
3075 // (x & 0xff0000) << 8
3076 if (Num != 0 && Num != 2)
3077 return false;
3078 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3079 if (!C || C->getZExtValue() != 8)
3080 return false;
3081 } else { // Opc == ISD::SRL
3082 // (x & 0xff00) >> 8
3083 // (x & 0xff000000) >> 8
3084 if (Num != 1 && Num != 3)
3085 return false;
3086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3087 if (!C || C->getZExtValue() != 8)
3088 return false;
3089 }
3090
3091 if (Parts[Num])
3092 return false;
3093
3094 Parts[Num] = N0.getOperand(0).getNode();
3095 return true;
3096}
3097
3098/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3099/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3100/// => (rotl (bswap x), 16)
3101SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3102 if (!LegalOperations)
3103 return SDValue();
3104
3105 EVT VT = N->getValueType(0);
3106 if (VT != MVT::i32)
3107 return SDValue();
3108 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3109 return SDValue();
3110
3111 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3112 // Look for either
3113 // (or (or (and), (and)), (or (and), (and)))
3114 // (or (or (or (and), (and)), (and)), (and))
3115 if (N0.getOpcode() != ISD::OR)
3116 return SDValue();
3117 SDValue N00 = N0.getOperand(0);
3118 SDValue N01 = N0.getOperand(1);
3119
Evan Chengbf0baa92012-12-13 01:34:32 +00003120 if (N1.getOpcode() == ISD::OR &&
3121 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003122 // (or (or (and), (and)), (or (and), (and)))
3123 SDValue N000 = N00.getOperand(0);
3124 if (!isBSwapHWordElement(N000, Parts))
3125 return SDValue();
3126
3127 SDValue N001 = N00.getOperand(1);
3128 if (!isBSwapHWordElement(N001, Parts))
3129 return SDValue();
3130 SDValue N010 = N01.getOperand(0);
3131 if (!isBSwapHWordElement(N010, Parts))
3132 return SDValue();
3133 SDValue N011 = N01.getOperand(1);
3134 if (!isBSwapHWordElement(N011, Parts))
3135 return SDValue();
3136 } else {
3137 // (or (or (or (and), (and)), (and)), (and))
3138 if (!isBSwapHWordElement(N1, Parts))
3139 return SDValue();
3140 if (!isBSwapHWordElement(N01, Parts))
3141 return SDValue();
3142 if (N00.getOpcode() != ISD::OR)
3143 return SDValue();
3144 SDValue N000 = N00.getOperand(0);
3145 if (!isBSwapHWordElement(N000, Parts))
3146 return SDValue();
3147 SDValue N001 = N00.getOperand(1);
3148 if (!isBSwapHWordElement(N001, Parts))
3149 return SDValue();
3150 }
3151
3152 // Make sure the parts are all coming from the same node.
3153 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3154 return SDValue();
3155
Andrew Trickef9de2a2013-05-25 02:42:55 +00003156 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003157 SDValue(Parts[0],0));
3158
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003159 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003160 // do (x << 16) | (x >> 16).
3161 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3162 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003163 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003164 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003165 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3166 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3167 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3168 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003169}
3170
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003171SDValue DAGCombiner::visitOR(SDNode *N) {
3172 SDValue N0 = N->getOperand(0);
3173 SDValue N1 = N->getOperand(1);
3174 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003175 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3176 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003177 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003178
Dan Gohmana8665142007-06-25 16:23:39 +00003179 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003180 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003181 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003182 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003183
3184 // fold (or x, 0) -> x, vector edition
3185 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3186 return N1;
3187 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3188 return N0;
3189
3190 // fold (or x, -1) -> -1, vector edition
3191 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3192 return N0;
3193 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3194 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00003195 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003196
Dan Gohman06563a82007-07-03 14:03:57 +00003197 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003198 if (!LegalOperations &&
3199 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003200 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3201 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3202 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003203 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003204 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003205 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003206 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003207 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003208 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003209 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003210 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003211 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003212 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003213 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003214 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003215 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003216 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003217 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003218
3219 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3220 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3221 if (BSwap.getNode() != 0)
3222 return BSwap;
3223 BSwap = MatchBSwapHWordLow(N, N0, N1);
3224 if (BSwap.getNode() != 0)
3225 return BSwap;
3226
Nate Begeman22e251a2006-02-03 06:46:56 +00003227 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003228 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003229 if (ROR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003230 return ROR;
3231 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003232 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003233 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003234 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003235 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003236 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3237 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3238 if (!COR.getNode())
3239 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003240 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3241 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003242 N0.getOperand(0), N1), COR);
3243 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003244 }
Nate Begeman049b7482005-09-09 19:49:52 +00003245 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3246 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3247 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3248 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003249
Nate Begeman049b7482005-09-09 19:49:52 +00003250 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003251 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003252 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3253 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003254 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003255 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003256 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003257 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003258 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003259 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003260 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003261 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3262 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003263 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003264 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003265 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003266 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003267 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003268 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003269 }
3270 }
3271 // canonicalize equivalent to ll == rl
3272 if (LL == RR && LR == RL) {
3273 Op1 = ISD::getSetCCSwappedOperands(Op1);
3274 std::swap(RL, RR);
3275 }
3276 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003277 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003278 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003279 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003280 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003281 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3282 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003283 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003284 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003285 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003286 }
3287 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003288
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003289 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003290 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003291 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003292 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003293 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003294
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003295 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003296 if (N0.getOpcode() == ISD::AND &&
3297 N1.getOpcode() == ISD::AND &&
3298 N0.getOperand(1).getOpcode() == ISD::Constant &&
3299 N1.getOperand(1).getOpcode() == ISD::Constant &&
3300 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003301 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003302 // We can only do this xform if we know that bits from X that are set in C2
3303 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003304 const APInt &LHSMask =
3305 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3306 const APInt &RHSMask =
3307 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003308
Dan Gohman309d3d52007-06-22 14:59:07 +00003309 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3310 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003311 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003312 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003313 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003314 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003315 }
3316 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003317
Chris Lattner97614c82006-09-14 20:50:57 +00003318 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003319 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003320 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003321
Dan Gohman600f62b2010-06-24 14:30:44 +00003322 // Simplify the operands using demanded-bits information.
3323 if (!VT.isVector() &&
3324 SimplifyDemandedBits(SDValue(N, 0)))
3325 return SDValue(N, 0);
3326
Evan Chengf1005572010-04-28 07:10:39 +00003327 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003328}
3329
Chris Lattner97614c82006-09-14 20:50:57 +00003330/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003331static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003332 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003333 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003334 Mask = Op.getOperand(1);
3335 Op = Op.getOperand(0);
3336 } else {
3337 return false;
3338 }
3339 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003340
Chris Lattner97614c82006-09-14 20:50:57 +00003341 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3342 Shift = Op;
3343 return true;
3344 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003345
Scott Michelcf0da6c2009-02-17 22:15:04 +00003346 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003347}
3348
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003349// Return true if we can prove that, whenever Neg and Pos are both in the
3350// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003351// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3352//
3353// (or (shift1 X, Neg), (shift2 X, Pos))
3354//
3355// reduces to a rotate in direction shift2 by Pos and a rotate in direction
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003356// shift1 by Neg. The range [0, OpSize) means that we only need to consider
3357// shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003358static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003359 // If OpSize is a power of 2 then:
3360 //
3361 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3362 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3363 //
3364 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3365 // for the stronger condition:
3366 //
3367 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3368 //
3369 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3370 // we can just replace Neg with Neg' for the rest of the function.
3371 //
3372 // In other cases we check for the even stronger condition:
3373 //
3374 // Neg == OpSize - Pos [B]
3375 //
3376 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3377 // behavior if Pos == 0 (and consequently Neg == OpSize).
3378 //
3379 // We could actually use [A] whenever OpSize is a power of 2, but the
3380 // only extra cases that it would match are those uninteresting ones
3381 // where Neg and Pos are never in range at the same time. E.g. for
3382 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3383 // as well as (sub 32, Pos), but:
3384 //
3385 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3386 //
3387 // always invokes undefined behavior for 32-bit X.
3388 //
3389 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3390 unsigned LoBits = 0;
3391 if (Neg.getOpcode() == ISD::AND &&
3392 isPowerOf2_64(OpSize) &&
3393 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3394 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3395 Neg = Neg.getOperand(0);
3396 LoBits = Log2_64(OpSize);
3397 }
3398
Richard Sandiford0f264db2014-01-09 10:49:40 +00003399 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3400 if (Neg.getOpcode() != ISD::SUB)
3401 return 0;
3402 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3403 if (!NegC)
3404 return 0;
3405 SDValue NegOp1 = Neg.getOperand(1);
3406
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003407 // The condition we need is now:
3408 //
3409 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3410 //
3411 // If NegOp1 == Pos then we need:
3412 //
3413 // OpSize & Mask == NegC & Mask
3414 //
3415 // (because "x & Mask" is a truncation and distributes through subtraction).
3416 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003417 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003418 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003419 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3420 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003421 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003422 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3423 //
3424 // which, again because "x & Mask" is a truncation, becomes:
3425 //
3426 // NegC & Mask == (OpSize - PosC) & Mask
3427 // OpSize & Mask == (NegC + PosC) & Mask
3428 else if (Pos.getOpcode() == ISD::ADD &&
3429 Pos.getOperand(0) == NegOp1 &&
3430 Pos.getOperand(1).getOpcode() == ISD::Constant)
3431 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3432 NegC->getAPIntValue());
3433 else
3434 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003435
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003436 // Now we just need to check that OpSize & Mask == Width & Mask.
3437 if (LoBits)
3438 return Width.getLoBits(LoBits) == 0;
3439 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003440}
3441
Richard Sandiford95c864d2014-01-08 15:40:47 +00003442// A subroutine of MatchRotate used once we have found an OR of two opposite
3443// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3444// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3445// former being preferred if supported. InnerPos and InnerNeg are Pos and
3446// Neg with outer conversions stripped away.
3447SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3448 SDValue Neg, SDValue InnerPos,
3449 SDValue InnerNeg, unsigned PosOpcode,
3450 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003451 // fold (or (shl x, (*ext y)),
3452 // (srl x, (*ext (sub 32, y)))) ->
3453 // (rotl x, y) or (rotr x, (sub 32, y))
3454 //
3455 // fold (or (shl x, (*ext (sub 32, y))),
3456 // (srl x, (*ext y))) ->
3457 // (rotr x, y) or (rotl x, (sub 32, y))
3458 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003459 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003460 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3461 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3462 HasPos ? Pos : Neg).getNode();
3463 }
3464
3465 // fold (or (shl (*ext x), (*ext y)),
3466 // (srl (*ext x), (*ext (sub 32, y)))) ->
3467 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3468 //
3469 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3470 // (srl (*ext x), (*ext y))) ->
3471 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3472 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3473 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3474 SDValue InnerShifted = Shifted.getOperand(0);
3475 EVT InnerVT = InnerShifted.getValueType();
3476 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3477 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
Richard Sandiford0f264db2014-01-09 10:49:40 +00003478 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003479 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3480 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3481 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3482 }
3483 }
3484 }
3485
3486 return 0;
3487}
3488
Chris Lattner97614c82006-09-14 20:50:57 +00003489// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3490// idioms for rotate, and if the target supports rotation instructions, generate
3491// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003492SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003493 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003494 EVT VT = LHS.getValueType();
Chris Lattner97614c82006-09-14 20:50:57 +00003495 if (!TLI.isTypeLegal(VT)) return 0;
3496
3497 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003498 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3499 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Chris Lattner97614c82006-09-14 20:50:57 +00003500 if (!HasROTL && !HasROTR) return 0;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003501
Chris Lattner97614c82006-09-14 20:50:57 +00003502 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003503 SDValue LHSShift; // The shift.
3504 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003505 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3506 return 0; // Not part of a rotate.
3507
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003508 SDValue RHSShift; // The shift.
3509 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003510 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3511 return 0; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003512
Chris Lattner97614c82006-09-14 20:50:57 +00003513 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3514 return 0; // Not shifting the same value.
3515
3516 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3517 return 0; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003518
Chris Lattner97614c82006-09-14 20:50:57 +00003519 // Canonicalize shl to left side in a shl/srl pair.
3520 if (RHSShift.getOpcode() == ISD::SHL) {
3521 std::swap(LHS, RHS);
3522 std::swap(LHSShift, RHSShift);
3523 std::swap(LHSMask , RHSMask );
3524 }
3525
Duncan Sands13237ac2008-06-06 12:08:01 +00003526 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003527 SDValue LHSShiftArg = LHSShift.getOperand(0);
3528 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003529 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003530 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003531
3532 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3533 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003534 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3535 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003536 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3537 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003538 if ((LShVal + RShVal) != OpSizeInBits)
3539 return 0;
3540
Craig Topper65161fa2012-09-29 06:54:22 +00003541 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3542 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003543
Chris Lattner97614c82006-09-14 20:50:57 +00003544 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003545 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003546 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003547
Gabor Greiff304a7a2008-08-28 21:40:38 +00003548 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003549 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3550 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003551 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003552 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003553 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3554 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003555 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003556
Bill Wendling35972a92009-01-30 21:14:50 +00003557 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003558 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003559
Gabor Greiff304a7a2008-08-28 21:40:38 +00003560 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003561 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003562
Chris Lattner97614c82006-09-14 20:50:57 +00003563 // If there is a mask here, and we have a variable shift, we can't be sure
3564 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003565 if (LHSMask.getNode() || RHSMask.getNode())
Chris Lattner97614c82006-09-14 20:50:57 +00003566 return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003567
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003568 // If the shift amount is sign/zext/any-extended just peel it off.
3569 SDValue LExtOp0 = LHSShiftAmt;
3570 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003571 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3572 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3573 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3574 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3575 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3576 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3577 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3578 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003579 LExtOp0 = LHSShiftAmt.getOperand(0);
3580 RExtOp0 = RHSShiftAmt.getOperand(0);
3581 }
3582
Richard Sandiford95c864d2014-01-08 15:40:47 +00003583 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3584 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3585 if (TryL)
3586 return TryL;
3587
3588 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3589 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3590 if (TryR)
3591 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003592
Chris Lattner97614c82006-09-14 20:50:57 +00003593 return 0;
3594}
3595
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003596SDValue DAGCombiner::visitXOR(SDNode *N) {
3597 SDValue N0 = N->getOperand(0);
3598 SDValue N1 = N->getOperand(1);
3599 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003600 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3601 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003602 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003603
Dan Gohmana8665142007-06-25 16:23:39 +00003604 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003605 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003606 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003607 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003608
3609 // fold (xor x, 0) -> x, vector edition
3610 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3611 return N1;
3612 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3613 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003614 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003615
Evan Chengdf1690d2008-03-25 20:08:07 +00003616 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3617 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3618 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003619 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003620 if (N0.getOpcode() == ISD::UNDEF)
3621 return N0;
3622 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003623 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003624 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003625 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003626 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003627 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003628 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003629 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003630 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003631 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003632 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003633 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003634 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003635 if (RXOR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003636 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003637
Nate Begeman21158fc2005-09-01 00:19:25 +00003638 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003639 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003640 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003641 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3642 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003643
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003644 if (!LegalOperations ||
3645 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003646 switch (N0.getOpcode()) {
3647 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003648 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003649 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003650 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003651 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003652 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003653 N0.getOperand(3), NotCC);
3654 }
3655 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003656 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003657
Chris Lattner58c227b2007-09-10 21:39:07 +00003658 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003659 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003660 N0.getNode()->hasOneUse() &&
3661 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003662 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003663 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003664 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003665 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003666 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003667 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003668
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003669 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003670 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003671 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003672 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003673 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3674 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003675 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3676 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003677 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003678 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003679 }
3680 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003681 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003682 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003683 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003684 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003685 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3686 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003687 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3688 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003689 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003690 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003691 }
3692 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003693 // fold (xor (and x, y), y) -> (and (not x), y)
3694 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003695 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003696 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003697 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003698 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003699 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003700 }
Bill Wendling35972a92009-01-30 21:14:50 +00003701 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003702 if (N1C && N0.getOpcode() == ISD::XOR) {
3703 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3704 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3705 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003706 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003707 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003708 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003709 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003710 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003711 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003712 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003713 }
3714 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003715 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003716 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003717
Chris Lattner8d6fc202006-05-05 05:51:50 +00003718 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3719 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003720 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003721 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003722 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003723
Chris Lattner098c01e2006-04-08 04:15:24 +00003724 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003725 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003726 SimplifyDemandedBits(SDValue(N, 0)))
3727 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003728
Evan Chengf1005572010-04-28 07:10:39 +00003729 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003730}
3731
Chris Lattner7c709a52007-12-06 07:33:36 +00003732/// visitShiftByConstant - Handle transforms common to the three shifts, when
3733/// the shift amount is a constant.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003734SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003735 assert(isa<ConstantSDNode>(N->getOperand(1)) &&
3736 "Expected an ConstantSDNode operand.");
3737 // We can't and shouldn't fold opaque constants.
3738 if (cast<ConstantSDNode>(N->getOperand(1))->isOpaque())
3739 return SDValue();
3740
Gabor Greiff304a7a2008-08-28 21:40:38 +00003741 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003742 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003743
Chris Lattner7c709a52007-12-06 07:33:36 +00003744 // We want to pull some binops through shifts, so that we have (and (shift))
3745 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3746 // thing happens with address calculations, so it's important to canonicalize
3747 // it.
3748 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003749
Chris Lattner7c709a52007-12-06 07:33:36 +00003750 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003751 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003752 case ISD::OR:
3753 case ISD::XOR:
3754 HighBitSet = false; // We can only transform sra if the high bit is clear.
3755 break;
3756 case ISD::AND:
3757 HighBitSet = true; // We can only transform sra if the high bit is set.
3758 break;
3759 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003760 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003761 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003762 HighBitSet = false; // We can only transform sra if the high bit is clear.
3763 break;
3764 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003765
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003766 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003767 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003768 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003769
3770 // FIXME: disable this unless the input to the binop is a shift by a constant.
3771 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003772 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003773 // void foo(int *X, int i) { X[i & 1235] = 1; }
3774 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003775 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003776 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003777 BinOpLHSVal->getOpcode() != ISD::SRA &&
3778 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3779 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003780 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003781
Owen Anderson53aa7a92009-08-10 22:56:29 +00003782 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003783
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003784 // If this is a signed shift right, and the high bit is modified by the
3785 // logical operation, do not perform the transformation. The highBitSet
3786 // boolean indicates the value of the high bit of the constant which would
3787 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003788 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003789 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3790 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003791 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003792 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003793
Chris Lattner7c709a52007-12-06 07:33:36 +00003794 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003795 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003796 N->getValueType(0),
3797 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003798 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003799
3800 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003801 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003802 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003803 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003804
3805 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003806 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003807}
3808
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003809SDValue DAGCombiner::visitSHL(SDNode *N) {
3810 SDValue N0 = N->getOperand(0);
3811 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003812 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3813 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003814 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00003815 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003816
Daniel Sandersa1840d22013-11-11 17:23:41 +00003817 // fold vector ops
3818 if (VT.isVector()) {
3819 SDValue FoldedVOp = SimplifyVBinOp(N);
3820 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003821
3822 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3823 // If setcc produces all-one true value then:
3824 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3825 if (N1CV && N1CV->isConstant() &&
3826 TLI.getBooleanContents(true) ==
3827 TargetLowering::ZeroOrNegativeOneBooleanContent &&
3828 N0.getOpcode() == ISD::AND) {
3829 SDValue N00 = N0->getOperand(0);
3830 SDValue N01 = N0->getOperand(1);
3831 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3832
3833 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3834 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3835 if (C.getNode())
3836 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3837 }
3838 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003839 }
3840
Nate Begeman21158fc2005-09-01 00:19:25 +00003841 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003842 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003843 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003844 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003845 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003846 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003847 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003848 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003849 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003850 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003851 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003852 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003853 // fold (shl undef, x) -> 0
3854 if (N0.getOpcode() == ISD::UNDEF)
3855 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003856 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003857 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003858 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003859 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003860 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003861 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng13beeeb12008-09-22 18:19:24 +00003862 N1.getOperand(0).getOpcode() == ISD::AND &&
3863 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003864 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng13beeeb12008-09-22 18:19:24 +00003865 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00003866 EVT TruncVT = N1.getValueType();
Evan Cheng13beeeb12008-09-22 18:19:24 +00003867 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sands3ed76882009-02-01 18:06:53 +00003868 APInt TruncC = N101C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00003869 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003870 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3871 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00003872 DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003873 SDLoc(N),
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00003874 TruncVT, N100),
Dan Gohmanfb58faf2009-01-27 20:39:34 +00003875 DAG.getConstant(TruncC, TruncVT)));
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003876 }
3877 }
3878
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003879 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3880 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003881
3882 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Scott Michelcf0da6c2009-02-17 22:15:04 +00003883 if (N1C && N0.getOpcode() == ISD::SHL &&
Nate Begeman21158fc2005-09-01 00:19:25 +00003884 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003885 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3886 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00003887 if (c1 + c2 >= OpSizeInBits)
Nate Begemand23739d2005-09-06 04:43:02 +00003888 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003889 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Nate Begemand23739d2005-09-06 04:43:02 +00003890 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman21158fc2005-09-01 00:19:25 +00003891 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00003892
3893 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3894 // For this to be valid, the second form must not preserve any of the bits
3895 // that are shifted out by the inner shift in the first form. This means
3896 // the outer shift size must be >= the number of bits added by the ext.
3897 // As a corollary, we don't care what kind of ext it is.
3898 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3899 N0.getOpcode() == ISD::ANY_EXTEND ||
3900 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3901 N0.getOperand(0).getOpcode() == ISD::SHL &&
3902 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00003903 uint64_t c1 =
Dale Johannesena94e36b2010-12-21 21:55:50 +00003904 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3905 uint64_t c2 = N1C->getZExtValue();
3906 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3907 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3908 if (c2 >= OpSizeInBits - InnerShiftSize) {
3909 if (c1 + c2 >= OpSizeInBits)
3910 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003911 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3912 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
Dale Johannesena94e36b2010-12-21 21:55:50 +00003913 N0.getOperand(0)->getOperand(0)),
3914 DAG.getConstant(c1 + c2, N1.getValueType()));
3915 }
3916 }
3917
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00003918 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3919 // Only fold this if the inner zext has no other uses to avoid increasing
3920 // the total number of instructions.
3921 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3922 N0.getOperand(0).getOpcode() == ISD::SRL &&
3923 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3924 uint64_t c1 =
3925 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3926 if (c1 < VT.getSizeInBits()) {
3927 uint64_t c2 = N1C->getZExtValue();
3928 if (c1 == c2) {
3929 SDValue NewOp0 = N0.getOperand(0);
3930 EVT CountVT = NewOp0.getOperand(1).getValueType();
3931 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3932 NewOp0, DAG.getConstant(c2, CountVT));
Andrea Di Biagio561badf2013-10-17 11:02:58 +00003933 AddToWorkList(NewSHL.getNode());
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00003934 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3935 }
3936 }
3937 }
3938
Eli Friedman1877ac92011-06-09 22:14:44 +00003939 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3940 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00003941 // Only fold this if the inner shift has no other uses -- if it does, folding
3942 // this will increase the total number of instructions.
3943 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
Nate Begeman21158fc2005-09-01 00:19:25 +00003944 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003945 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
Evan Chenga7bb55e2009-07-21 05:40:15 +00003946 if (c1 < VT.getSizeInBits()) {
3947 uint64_t c2 = N1C->getZExtValue();
Eli Friedman1877ac92011-06-09 22:14:44 +00003948 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3949 VT.getSizeInBits() - c1);
3950 SDValue Shift;
3951 if (c2 > c1) {
3952 Mask = Mask.shl(c2-c1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003953 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman1877ac92011-06-09 22:14:44 +00003954 DAG.getConstant(c2-c1, N1.getValueType()));
3955 } else {
3956 Mask = Mask.lshr(c1-c2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003957 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman1877ac92011-06-09 22:14:44 +00003958 DAG.getConstant(c1-c2, N1.getValueType()));
3959 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003960 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
Eli Friedman1877ac92011-06-09 22:14:44 +00003961 DAG.getConstant(Mask, VT));
Evan Chenga7bb55e2009-07-21 05:40:15 +00003962 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003963 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003964 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00003965 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3966 SDValue HiBitsMask =
3967 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3968 VT.getSizeInBits() -
3969 N1C->getZExtValue()),
3970 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003971 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00003972 HiBitsMask);
3973 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003974
Evan Chengf1bd5fc2010-04-17 06:13:15 +00003975 if (N1C) {
3976 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3977 if (NewSHL.getNode())
3978 return NewSHL;
3979 }
3980
Evan Chengf1005572010-04-28 07:10:39 +00003981 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003982}
3983
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003984SDValue DAGCombiner::visitSRA(SDNode *N) {
3985 SDValue N0 = N->getOperand(0);
3986 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003987 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3988 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003989 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00003990 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003991
Daniel Sandersa1840d22013-11-11 17:23:41 +00003992 // fold vector ops
3993 if (VT.isVector()) {
3994 SDValue FoldedVOp = SimplifyVBinOp(N);
3995 if (FoldedVOp.getNode()) return FoldedVOp;
3996 }
3997
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003998 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003999 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004000 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004001 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004002 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004003 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004004 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004005 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004006 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004007 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004008 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004009 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004010 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004011 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004012 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004013 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4014 // sext_inreg.
4015 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004016 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004017 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4018 if (VT.isVector())
4019 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4020 ExtVT, VT.getVectorNumElements());
4021 if ((!LegalOperations ||
4022 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004023 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004024 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004025 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004026
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004027 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004028 if (N1C && N0.getOpcode() == ISD::SRA) {
4029 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004030 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Dan Gohman1d459e42009-12-11 21:31:27 +00004031 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004032 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0f8a7272006-02-28 06:23:04 +00004033 DAG.getConstant(Sum, N1C->getValueType(0)));
4034 }
4035 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004036
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004037 // fold (sra (shl X, m), (sub result_size, n))
4038 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004039 // result_size - n != m.
4040 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004041 // code.
Christopher Lamb8fe91092008-03-19 08:30:06 +00004042 if (N0.getOpcode() == ISD::SHL) {
4043 // Get the two constanst of the shifts, CN0 = m, CN = n.
4044 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4045 if (N01C && N1C) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004046 // Determine what the truncate's result bitsize and type would be.
Owen Anderson53aa7a92009-08-10 22:56:29 +00004047 EVT TruncVT =
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004048 EVT::getIntegerVT(*DAG.getContext(),
4049 OpSizeInBits - N1C->getZExtValue());
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004050 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004051 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004052
Scott Michelcf0da6c2009-02-17 22:15:04 +00004053 // If the shift is not a no-op (in which case this should be just a sign
4054 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004055 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004056 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004057 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004058 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4059 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004060 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004061
Owen Andersonb2c80da2011-02-25 21:41:48 +00004062 SDValue Amt = DAG.getConstant(ShiftAmt,
4063 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004064 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004065 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004066 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004067 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004068 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004069 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004070 }
4071 }
4072 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004073
Duncan Sands3ed76882009-02-01 18:06:53 +00004074 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004075 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng13beeeb12008-09-22 18:19:24 +00004076 N1.getOperand(0).getOpcode() == ISD::AND &&
4077 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004078 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng13beeeb12008-09-22 18:19:24 +00004079 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00004080 EVT TruncVT = N1.getValueType();
Evan Cheng13beeeb12008-09-22 18:19:24 +00004081 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sands3ed76882009-02-01 18:06:53 +00004082 APInt TruncC = N101C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00004083 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004084 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4085 DAG.getNode(ISD::AND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004086 TruncVT,
Bill Wendling3b585af2009-01-31 03:12:48 +00004087 DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004088 SDLoc(N),
Bill Wendling3b585af2009-01-31 03:12:48 +00004089 TruncVT, N100),
Dan Gohmanfb58faf2009-01-27 20:39:34 +00004090 DAG.getConstant(TruncC, TruncVT)));
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004091 }
4092 }
4093
Benjamin Kramer946e1522011-01-30 16:38:43 +00004094 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4095 // if c1 is equal to the number of bits the trunc removes
4096 if (N0.getOpcode() == ISD::TRUNCATE &&
4097 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4098 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4099 N0.getOperand(0).hasOneUse() &&
4100 N0.getOperand(0).getOperand(1).hasOneUse() &&
4101 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4102 EVT LargeVT = N0.getOperand(0).getValueType();
4103 ConstantSDNode *LargeShiftAmt =
4104 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4105
4106 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4107 LargeShiftAmt->getZExtValue()) {
4108 SDValue Amt =
4109 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00004110 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004111 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
Benjamin Kramer946e1522011-01-30 16:38:43 +00004112 N0.getOperand(0).getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004113 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
Benjamin Kramer946e1522011-01-30 16:38:43 +00004114 }
4115 }
4116
Scott Michelcf0da6c2009-02-17 22:15:04 +00004117 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004118 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4119 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004120
4121
Nate Begeman21158fc2005-09-01 00:19:25 +00004122 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004123 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004124 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004125
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004126 if (N1C) {
4127 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4128 if (NewSRA.getNode())
4129 return NewSRA;
4130 }
4131
Evan Chengf1005572010-04-28 07:10:39 +00004132 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004133}
4134
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004135SDValue DAGCombiner::visitSRL(SDNode *N) {
4136 SDValue N0 = N->getOperand(0);
4137 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004138 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4139 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004140 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004141 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004142
Daniel Sandersa1840d22013-11-11 17:23:41 +00004143 // fold vector ops
4144 if (VT.isVector()) {
4145 SDValue FoldedVOp = SimplifyVBinOp(N);
4146 if (FoldedVOp.getNode()) return FoldedVOp;
4147 }
4148
Nate Begeman21158fc2005-09-01 00:19:25 +00004149 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004150 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004151 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004152 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004153 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004154 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004155 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004156 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004157 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004158 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004159 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004160 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004161 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004162 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004163 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004164 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004165
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004166 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Scott Michelcf0da6c2009-02-17 22:15:04 +00004167 if (N1C && N0.getOpcode() == ISD::SRL &&
Nate Begeman21158fc2005-09-01 00:19:25 +00004168 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004169 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4170 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004171 if (c1 + c2 >= OpSizeInBits)
Nate Begemand23739d2005-09-06 04:43:02 +00004172 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004173 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Nate Begemand23739d2005-09-06 04:43:02 +00004174 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman21158fc2005-09-01 00:19:25 +00004175 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004176
Dale Johannesencd538af2010-12-17 21:45:49 +00004177 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004178 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4179 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004180 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004181 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004182 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4183 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004184 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4185 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004186 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004187 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004188 if (c1 + OpSizeInBits == InnerShiftSize) {
4189 if (c1 + c2 >= InnerShiftSize)
4190 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004191 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4192 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004193 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004194 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004195 }
4196 }
4197
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004198 // fold (srl (shl x, c), c) -> (and x, cst2)
4199 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4200 N0.getValueSizeInBits() <= 64) {
4201 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004202 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004203 DAG.getConstant(~0ULL >> ShAmt, VT));
4204 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004205
Michael Liao62ebfd82013-06-21 18:45:27 +00004206 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004207 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4208 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004209 EVT SmallVT = N0.getOperand(0).getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +00004210 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
Dale Johannesen84935752009-02-06 23:05:02 +00004211 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004212
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004213 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004214 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004215 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004216 N0.getOperand(0),
4217 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004218 AddToWorkList(SmallShift.getNode());
Michael Liao62ebfd82013-06-21 18:45:27 +00004219 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4220 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4221 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4222 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004223 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004224 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004225
Chris Lattner2e33fb42006-10-12 20:23:19 +00004226 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4227 // bit, which is unmodified by sra.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004228 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004229 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004230 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004231 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004232
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004233 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004234 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Duncan Sands13237ac2008-06-06 12:08:01 +00004235 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004236 APInt KnownZero, KnownOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004237 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004238
Chris Lattner49932492006-04-02 06:11:11 +00004239 // If any of the input bits are KnownOne, then the input couldn't be all
4240 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004241 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004242
Chris Lattner49932492006-04-02 06:11:11 +00004243 // If all of the bits input the to ctlz node are known to be zero, then
4244 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004245 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004246 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004247
Chris Lattner49932492006-04-02 06:11:11 +00004248 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004249 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004250 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004251 // could be set on input to the CTLZ node. If this bit is set, the SRL
4252 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4253 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004254 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004255 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004256
Chris Lattner49932492006-04-02 06:11:11 +00004257 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004258 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004259 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004260 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004261 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004262
Andrew Trickef9de2a2013-05-25 02:42:55 +00004263 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004264 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004265 }
4266 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004267
Duncan Sands3ed76882009-02-01 18:06:53 +00004268 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004269 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng13beeeb12008-09-22 18:19:24 +00004270 N1.getOperand(0).getOpcode() == ISD::AND &&
4271 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004272 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng13beeeb12008-09-22 18:19:24 +00004273 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00004274 EVT TruncVT = N1.getValueType();
Evan Cheng13beeeb12008-09-22 18:19:24 +00004275 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sands3ed76882009-02-01 18:06:53 +00004276 APInt TruncC = N101C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00004277 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004278 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4279 DAG.getNode(ISD::AND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004280 TruncVT,
Bill Wendling3b585af2009-01-31 03:12:48 +00004281 DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004282 SDLoc(N),
Bill Wendling3b585af2009-01-31 03:12:48 +00004283 TruncVT, N100),
Dan Gohmanfb58faf2009-01-27 20:39:34 +00004284 DAG.getConstant(TruncC, TruncVT)));
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004285 }
4286 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004287
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004288 // fold operands of srl based on knowledge that the low bits are not
4289 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004290 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4291 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004292
Evan Chengb175de62009-12-18 21:31:31 +00004293 if (N1C) {
4294 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4295 if (NewSRL.getNode())
4296 return NewSRL;
4297 }
4298
Dan Gohman600f62b2010-06-24 14:30:44 +00004299 // Attempt to convert a srl of a load into a narrower zero-extending load.
4300 SDValue NarrowLoad = ReduceLoadWidth(N);
4301 if (NarrowLoad.getNode())
4302 return NarrowLoad;
4303
Evan Chengb175de62009-12-18 21:31:31 +00004304 // Here is a common situation. We want to optimize:
4305 //
4306 // %a = ...
4307 // %b = and i32 %a, 2
4308 // %c = srl i32 %b, 1
4309 // brcond i32 %c ...
4310 //
4311 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004312 //
Evan Chengb175de62009-12-18 21:31:31 +00004313 // %a = ...
4314 // %b = and %a, 2
4315 // %c = setcc eq %b, 0
4316 // brcond %c ...
4317 //
4318 // However when after the source operand of SRL is optimized into AND, the SRL
4319 // itself may not be optimized further. Look for it and add the BRCOND into
4320 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004321 if (N->hasOneUse()) {
4322 SDNode *Use = *N->use_begin();
4323 if (Use->getOpcode() == ISD::BRCOND)
4324 AddToWorkList(Use);
4325 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4326 // Also look pass the truncate.
4327 Use = *Use->use_begin();
4328 if (Use->getOpcode() == ISD::BRCOND)
4329 AddToWorkList(Use);
4330 }
4331 }
Evan Chengb175de62009-12-18 21:31:31 +00004332
Evan Chengf1005572010-04-28 07:10:39 +00004333 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004334}
4335
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004336SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4337 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004338 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004339
4340 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004341 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004342 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004343 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004344}
4345
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004346SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4347 SDValue N0 = N->getOperand(0);
4348 EVT VT = N->getValueType(0);
4349
4350 // fold (ctlz_zero_undef c1) -> c2
4351 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004352 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004353 return SDValue();
4354}
4355
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004356SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4357 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004358 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004359
Nate Begeman21158fc2005-09-01 00:19:25 +00004360 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004361 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004362 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004363 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004364}
4365
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004366SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4367 SDValue N0 = N->getOperand(0);
4368 EVT VT = N->getValueType(0);
4369
4370 // fold (cttz_zero_undef c1) -> c2
4371 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004372 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004373 return SDValue();
4374}
4375
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004376SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4377 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004378 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004379
Nate Begeman21158fc2005-09-01 00:19:25 +00004380 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004381 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004382 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004383 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004384}
4385
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004386SDValue DAGCombiner::visitSELECT(SDNode *N) {
4387 SDValue N0 = N->getOperand(0);
4388 SDValue N1 = N->getOperand(1);
4389 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004390 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4391 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4392 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004393 EVT VT = N->getValueType(0);
4394 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004395
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004396 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004397 if (N1 == N2)
4398 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004399 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004400 if (N0C && !N0C->isNullValue())
4401 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004402 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004403 if (N0C && N0C->isNullValue())
4404 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004405 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004406 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004407 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004408 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004409 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004410 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004411 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004412 TLI.getBooleanContents(false) ==
4413 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004414 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004415 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004416 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004417 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004418 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004419 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004420 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004421 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004422 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004423 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4424 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004425 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004426 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004427 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004428 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004429 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004430 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004431 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004432 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004433 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004434 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004435 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004436 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004437 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004438 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004439 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004440 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004441 // fold (select X, X, Y) -> (or X, Y)
4442 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004443 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004444 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004445 // fold (select X, Y, X) -> (and X, Y)
4446 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004447 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004448 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004449
Chris Lattner6c14c352005-10-18 06:04:22 +00004450 // If we can fold this based on the true/false value, do so.
4451 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004452 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004453
Nate Begemanc760f802005-09-19 22:34:01 +00004454 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004455 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004456 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004457 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004458 // having to say they don't support SELECT_CC on every type the DAG knows
4459 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004460 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004461 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004462 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004463 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004464 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004465 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004466 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004467
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004468 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004469}
4470
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004471static
4472std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4473 SDLoc DL(N);
4474 EVT LoVT, HiVT;
4475 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4476
4477 // Split the inputs.
4478 SDValue Lo, Hi, LL, LH, RL, RH;
4479 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4480 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4481
4482 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4483 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4484
4485 return std::make_pair(Lo, Hi);
4486}
4487
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004488SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4489 SDValue N0 = N->getOperand(0);
4490 SDValue N1 = N->getOperand(1);
4491 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004492 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004493
4494 // Canonicalize integer abs.
4495 // vselect (setg[te] X, 0), X, -X ->
4496 // vselect (setgt X, -1), X, -X ->
4497 // vselect (setl[te] X, 0), -X, X ->
4498 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4499 if (N0.getOpcode() == ISD::SETCC) {
4500 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4501 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4502 bool isAbs = false;
4503 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4504
4505 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4506 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4507 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4508 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4509 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4510 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4511 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4512
4513 if (isAbs) {
4514 EVT VT = LHS.getValueType();
4515 SDValue Shift = DAG.getNode(
4516 ISD::SRA, DL, VT, LHS,
4517 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4518 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4519 AddToWorkList(Shift.getNode());
4520 AddToWorkList(Add.getNode());
4521 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4522 }
4523 }
4524
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004525 // If the VSELECT result requires splitting and the mask is provided by a
4526 // SETCC, then split both nodes and its operands before legalization. This
4527 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4528 // and enables future optimizations (e.g. min/max pattern matching on X86).
4529 if (N0.getOpcode() == ISD::SETCC) {
4530 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004531
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004532 // Check if any splitting is required.
4533 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4534 TargetLowering::TypeSplitVector)
4535 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004536
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004537 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4538 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4539 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4540 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004541
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004542 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4543 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004544
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004545 // Add the new VSELECT nodes to the work list in case they need to be split
4546 // again.
4547 AddToWorkList(Lo.getNode());
4548 AddToWorkList(Hi.getNode());
4549
4550 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004551 }
4552
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004553 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4554 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4555 return N1;
4556 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4557 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4558 return N2;
4559
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004560 return SDValue();
4561}
4562
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004563SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4564 SDValue N0 = N->getOperand(0);
4565 SDValue N1 = N->getOperand(1);
4566 SDValue N2 = N->getOperand(2);
4567 SDValue N3 = N->getOperand(3);
4568 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004569 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004570
Nate Begemanc760f802005-09-19 22:34:01 +00004571 // fold select_cc lhs, rhs, x, x, cc -> x
4572 if (N2 == N3)
4573 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004574
Chris Lattner8b68dec2006-09-20 06:19:26 +00004575 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004576 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004577 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004578 if (SCC.getNode()) {
4579 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004580
Stephen Lin605207f2013-06-15 04:03:33 +00004581 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4582 if (!SCCC->isNullValue())
4583 return N2; // cond always true -> true val
4584 else
4585 return N3; // cond always false -> false val
4586 }
4587
4588 // Fold to a simpler select_cc
4589 if (SCC.getOpcode() == ISD::SETCC)
4590 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4591 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4592 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004593 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004594
Chris Lattner6c14c352005-10-18 06:04:22 +00004595 // If we can fold this based on the true/false value, do so.
4596 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004597 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004598
Nate Begemanc760f802005-09-19 22:34:01 +00004599 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004600 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004601}
4602
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004603SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004604 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004605 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004606 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004607}
4608
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004609// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4610// dag node into a ConstantSDNode or a build_vector of constants.
4611// This function is called by the DAGCombiner when visiting sext/zext/aext
4612// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4613// Vector extends are not folded if operations are legal; this is to
4614// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004615static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4616 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004617 bool LegalOperations) {
4618 unsigned Opcode = N->getOpcode();
4619 SDValue N0 = N->getOperand(0);
4620 EVT VT = N->getValueType(0);
4621
4622 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4623 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4624
4625 // fold (sext c1) -> c1
4626 // fold (zext c1) -> c1
4627 // fold (aext c1) -> c1
4628 if (isa<ConstantSDNode>(N0))
4629 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4630
4631 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4632 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4633 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004634 EVT SVT = VT.getScalarType();
4635 if (!(VT.isVector() &&
4636 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004637 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4638 return 0;
4639
4640 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004641 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004642 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4643 unsigned ShAmt = VTBits - EVTBits;
4644 SmallVector<SDValue, 8> Elts;
4645 unsigned NumElts = N0->getNumOperands();
4646 SDLoc DL(N);
4647
4648 for (unsigned i=0; i != NumElts; ++i) {
4649 SDValue Op = N0->getOperand(i);
4650 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004651 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004652 continue;
4653 }
4654
4655 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4656 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4657 if (Opcode == ISD::SIGN_EXTEND)
4658 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004659 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004660 else
4661 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004662 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004663 }
4664
4665 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4666}
4667
Evan Chenge106e2f2007-10-29 19:58:20 +00004668// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004669// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004670// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004671// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004672static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004673 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004674 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004675 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004676 bool HasCopyToRegUses = false;
4677 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004678 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4679 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004680 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004681 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004682 if (User == N)
4683 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004684 if (UI.getUse().getResNo() != N0.getResNo())
4685 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004686 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004687 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004688 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4689 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4690 // Sign bits will be lost after a zext.
4691 return false;
4692 bool Add = false;
4693 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004694 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004695 if (UseOp == N0)
4696 continue;
4697 if (!isa<ConstantSDNode>(UseOp))
4698 return false;
4699 Add = true;
4700 }
4701 if (Add)
4702 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004703 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004704 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004705 // If truncates aren't free and there are users we can't
4706 // extend, it isn't worthwhile.
4707 if (!isTruncFree)
4708 return false;
4709 // Remember if this value is live-out.
4710 if (User->getOpcode() == ISD::CopyToReg)
4711 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004712 }
4713
4714 if (HasCopyToRegUses) {
4715 bool BothLiveOut = false;
4716 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4717 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004718 SDUse &Use = UI.getUse();
4719 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4720 BothLiveOut = true;
4721 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004722 }
4723 }
4724 if (BothLiveOut)
4725 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004726 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004727 return ExtendNodes.size();
4728 }
4729 return true;
4730}
4731
Craig Toppere0b71182013-07-13 07:43:40 +00004732void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004733 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004734 ISD::NodeType ExtType) {
4735 // Extend SetCC uses if necessary.
4736 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4737 SDNode *SetCC = SetCCs[i];
4738 SmallVector<SDValue, 4> Ops;
4739
4740 for (unsigned j = 0; j != 2; ++j) {
4741 SDValue SOp = SetCC->getOperand(j);
4742 if (SOp == Trunc)
4743 Ops.push_back(ExtLoad);
4744 else
4745 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4746 }
4747
4748 Ops.push_back(SetCC->getOperand(2));
4749 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4750 &Ops[0], Ops.size()));
4751 }
4752}
4753
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004754SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4755 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004756 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004757
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004758 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4759 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004760 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004761
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004762 // fold (sext (sext x)) -> (sext x)
4763 // fold (sext (aext x)) -> (sext x)
4764 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004765 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004766 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004767
Chris Lattnerfce448f2007-02-26 03:13:59 +00004768 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004769 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4770 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004771 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4772 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004773 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4774 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004775 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004776 // CombineTo deleted the truncate, if needed, but not what's under it.
4777 AddToWorkList(oye);
4778 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004779 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004780 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004781
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004782 // See if the value being truncated is already sign extended. If so, just
4783 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004784 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004785 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4786 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4787 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004788 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004789
Chris Lattnerfce448f2007-02-26 03:13:59 +00004790 if (OpBits == DestBits) {
4791 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4792 // bits, it is already ready.
4793 if (NumSignBits > DestBits-MidBits)
4794 return Op;
4795 } else if (OpBits < DestBits) {
4796 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4797 // bits, just sext from i32.
4798 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004799 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004800 } else {
4801 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4802 // bits, just truncate to i32.
4803 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004804 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004805 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004806
Chris Lattnerfce448f2007-02-26 03:13:59 +00004807 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004808 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4809 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004810 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004811 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004812 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004813 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4814 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004815 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004816 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004817 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004818
Evan Chengbce7c472005-12-14 02:19:23 +00004819 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004820 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004821 // on vectors in one instruction. We only perform this transformation on
4822 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004823 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004824 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004825 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004826 bool DoXform = true;
4827 SmallVector<SDNode*, 4> SetCCs;
4828 if (!N0.hasOneUse())
4829 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4830 if (DoXform) {
4831 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004832 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004833 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004834 LN0->getBasePtr(), N0.getValueType(),
4835 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004836 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004837 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004838 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004839 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004840 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004841 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004842 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004843 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004844 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004845
4846 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4847 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004848 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4849 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004850 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004851 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004852 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004853 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004854 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004855 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004856 LN0->getBasePtr(), MemVT,
4857 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004858 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004859 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004860 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004861 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004862 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004863 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004864 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004865 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004866
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004867 // fold (sext (and/or/xor (load x), cst)) ->
4868 // (and/or/xor (sextload x), (sext cst))
4869 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4870 N0.getOpcode() == ISD::XOR) &&
4871 isa<LoadSDNode>(N0.getOperand(0)) &&
4872 N0.getOperand(1).getOpcode() == ISD::Constant &&
4873 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4874 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4875 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4876 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4877 bool DoXform = true;
4878 SmallVector<SDNode*, 4> SetCCs;
4879 if (!N0.hasOneUse())
4880 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4881 SetCCs, TLI);
4882 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004883 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004884 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004885 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004886 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004887 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4888 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004889 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004890 ExtLoad, DAG.getConstant(Mask, VT));
4891 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004892 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004893 N0.getOperand(0).getValueType(), ExtLoad);
4894 CombineTo(N, And);
4895 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004896 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004897 ISD::SIGN_EXTEND);
4898 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4899 }
4900 }
4901 }
4902
Chris Lattner65786b02007-04-11 05:32:27 +00004903 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00004904 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00004905 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00004906 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00004907 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00004908 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00004909 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00004910 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4911 // of the same size as the compared operands. Only optimize sext(setcc())
4912 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00004913 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00004914
4915 // We know that the # elements of the results is the same as the
4916 // # elements of the compare (and the # elements of the compare result
4917 // for that matter). Check to see that they are the same size. If so,
4918 // we know that the element size of the sext'd result matches the
4919 // element size of the compare operands.
4920 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004921 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00004922 N0.getOperand(1),
4923 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00004924
Dan Gohmane82c25e2010-04-30 17:19:19 +00004925 // If the desired elements are smaller or larger than the source
4926 // elements we can use a matching integer vector type and then
4927 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00004928 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00004929 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004930 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00004931 N0.getOperand(0), N0.getOperand(1),
4932 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004933 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00004934 }
Chris Lattner4ac60732009-07-08 00:31:33 +00004935 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00004936
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00004937 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00004938 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004939 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00004940 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004941 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00004942 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004943 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00004944 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004945 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00004946
4947 if (!VT.isVector()) {
4948 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
4949 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
4950 SDLoc DL(N);
4951 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4952 SDValue SetCC = DAG.getSetCC(DL,
4953 SetCCVT,
4954 N0.getOperand(0), N0.getOperand(1), CC);
4955 EVT SelectVT = getSetCCResultType(VT);
4956 return DAG.getSelect(DL, VT,
4957 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
4958 NegOne, DAG.getConstant(0, VT));
4959
4960 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00004961 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004962 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004963
Dan Gohman3eb10f72008-04-28 16:58:24 +00004964 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004965 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00004966 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004967 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004968
Evan Chengf1005572010-04-28 07:10:39 +00004969 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004970}
4971
Rafael Espindola8f62b322012-04-09 16:06:03 +00004972// isTruncateOf - If N is a truncate of some other value, return true, record
4973// the value being truncated in Op and which of Op's bits are zero in KnownZero.
4974// This function computes KnownZero to avoid a duplicated call to
4975// ComputeMaskedBits in the caller.
4976static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4977 APInt &KnownZero) {
4978 APInt KnownOne;
4979 if (N->getOpcode() == ISD::TRUNCATE) {
4980 Op = N->getOperand(0);
4981 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4982 return true;
4983 }
4984
4985 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4986 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4987 return false;
4988
4989 SDValue Op0 = N->getOperand(0);
4990 SDValue Op1 = N->getOperand(1);
4991 assert(Op0.getValueType() == Op1.getValueType());
4992
4993 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4994 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00004995 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00004996 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00004997 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00004998 Op = Op0;
4999 else
5000 return false;
5001
5002 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5003
5004 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5005 return false;
5006
5007 return true;
5008}
5009
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005010SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5011 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005012 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005013
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005014 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5015 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005016 return SDValue(Res, 0);
5017
Nate Begeman21158fc2005-09-01 00:19:25 +00005018 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005019 // fold (zext (aext x)) -> (zext x)
5020 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005021 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005022 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005023
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005024 // fold (zext (truncate x)) -> (zext x) or
5025 // (zext (truncate x)) -> (truncate x)
5026 // This is valid when the truncated bits of x are already zero.
5027 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005028 SDValue Op;
5029 APInt KnownZero;
5030 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5031 APInt TruncatedBits =
5032 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5033 APInt(Op.getValueSizeInBits(), 0) :
5034 APInt::getBitsSet(Op.getValueSizeInBits(),
5035 N0.getValueSizeInBits(),
5036 std::min(Op.getValueSizeInBits(),
5037 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005038 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005039 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005040 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005041 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005042 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005043
5044 return Op;
5045 }
5046 }
5047
Evan Cheng464dc9b2007-03-22 01:54:19 +00005048 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5049 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005050 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005051 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5052 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005053 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5054 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005055 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005056 // CombineTo deleted the truncate, if needed, but not what's under it.
5057 AddToWorkList(oye);
5058 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005059 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005060 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005061 }
5062
Chris Lattnera31f0a62006-09-21 06:00:20 +00005063 // fold (zext (truncate x)) -> (and x, mask)
5064 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005065 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005066
5067 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5068 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5069 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5070 if (NarrowLoad.getNode()) {
5071 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5072 if (NarrowLoad.getNode() != N0.getNode()) {
5073 CombineTo(N0.getNode(), NarrowLoad);
5074 // CombineTo deleted the truncate, if needed, but not what's under it.
5075 AddToWorkList(oye);
5076 }
5077 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5078 }
5079
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005080 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005081 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005082 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005083 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005084 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005085 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005086 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005087 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005088 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005089 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005090 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005091
Dan Gohmanad3e5492009-04-08 00:15:30 +00005092 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5093 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005094 if (N0.getOpcode() == ISD::AND &&
5095 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005096 N0.getOperand(1).getOpcode() == ISD::Constant &&
5097 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5098 N0.getValueType()) ||
5099 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005100 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005101 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005102 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005103 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005104 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005105 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005106 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005107 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005108 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005109 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005110 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005111
Evan Chengbce7c472005-12-14 02:19:23 +00005112 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005113 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005114 // on vectors in one instruction. We only perform this transformation on
5115 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005116 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005117 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005118 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005119 bool DoXform = true;
5120 SmallVector<SDNode*, 4> SetCCs;
5121 if (!N0.hasOneUse())
5122 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5123 if (DoXform) {
5124 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005125 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005126 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005127 LN0->getBasePtr(), N0.getValueType(),
5128 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005129 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005130 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005131 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005132 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005133
Andrew Trickef9de2a2013-05-25 02:42:55 +00005134 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005135 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005136 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005137 }
Evan Chengbce7c472005-12-14 02:19:23 +00005138 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005139
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005140 // fold (zext (and/or/xor (load x), cst)) ->
5141 // (and/or/xor (zextload x), (zext cst))
5142 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5143 N0.getOpcode() == ISD::XOR) &&
5144 isa<LoadSDNode>(N0.getOperand(0)) &&
5145 N0.getOperand(1).getOpcode() == ISD::Constant &&
5146 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5147 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5148 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5149 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5150 bool DoXform = true;
5151 SmallVector<SDNode*, 4> SetCCs;
5152 if (!N0.hasOneUse())
5153 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5154 SetCCs, TLI);
5155 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005156 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005157 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005158 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005159 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005160 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5161 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005162 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005163 ExtLoad, DAG.getConstant(Mask, VT));
5164 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005165 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005166 N0.getOperand(0).getValueType(), ExtLoad);
5167 CombineTo(N, And);
5168 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005169 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005170 ISD::ZERO_EXTEND);
5171 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5172 }
5173 }
5174 }
5175
Chris Lattner7dac1082005-12-14 19:05:06 +00005176 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5177 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005178 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5179 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005180 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005181 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005182 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005183 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005184 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005185 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005186 LN0->getBasePtr(), MemVT,
5187 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005188 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005189 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005190 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005191 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005192 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005193 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005194 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005195 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005196
Chris Lattner65786b02007-04-11 05:32:27 +00005197 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005198 if (!LegalOperations && VT.isVector() &&
5199 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005200 EVT N0VT = N0.getOperand(0).getValueType();
5201 if (getSetCCResultType(N0VT) == N0.getValueType())
5202 return SDValue();
5203
Evan Chengabd0ad52010-05-19 01:08:17 +00005204 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5205 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005206 EVT EltVT = VT.getVectorElementType();
5207 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5208 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005209 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005210 // We know that the # elements of the results is the same as the
5211 // # elements of the compare (and the # elements of the compare result
5212 // for that matter). Check to see that they are the same size. If so,
5213 // we know that the element size of the sext'd result matches the
5214 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005215 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5216 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005217 N0.getOperand(1),
5218 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005219 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Chengabd0ad52010-05-19 01:08:17 +00005220 &OneOps[0], OneOps.size()));
Dan Gohman4298df62011-05-17 22:20:36 +00005221
5222 // If the desired elements are smaller or larger than the source
5223 // elements we can use a matching integer vector type and then
5224 // truncate/sign extend
5225 EVT MatchingElementType =
5226 EVT::getIntegerVT(*DAG.getContext(),
5227 N0VT.getScalarType().getSizeInBits());
5228 EVT MatchingVectorType =
5229 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5230 N0VT.getVectorNumElements());
5231 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005232 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005233 N0.getOperand(1),
5234 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005235 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5236 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5237 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman4298df62011-05-17 22:20:36 +00005238 &OneOps[0], OneOps.size()));
Evan Chengabd0ad52010-05-19 01:08:17 +00005239 }
5240
5241 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005242 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005243 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005244 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005245 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005246 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005247 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005248
Evan Cheng852c4862009-12-15 03:00:32 +00005249 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005250 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005251 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005252 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5253 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005254 SDValue ShAmt = N0.getOperand(1);
5255 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005256 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005257 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005258 // If the original shl may be shifting out bits, do not perform this
5259 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005260 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5261 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5262 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005263 return SDValue();
5264 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005265
Andrew Trickef9de2a2013-05-25 02:42:55 +00005266 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005267
5268 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005269 if (VT.getSizeInBits() >= 256)
5270 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005271
Chris Lattnere95d1952011-02-13 19:09:16 +00005272 return DAG.getNode(N0.getOpcode(), DL, VT,
5273 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5274 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005275 }
5276
Evan Chengf1005572010-04-28 07:10:39 +00005277 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005278}
5279
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005280SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5281 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005282 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005283
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005284 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5285 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005286 return SDValue(Res, 0);
5287
Chris Lattner812646a2006-05-05 05:58:59 +00005288 // fold (aext (aext x)) -> (aext x)
5289 // fold (aext (zext x)) -> (zext x)
5290 // fold (aext (sext x)) -> (sext x)
5291 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5292 N0.getOpcode() == ISD::ZERO_EXTEND ||
5293 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005294 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005295
Evan Cheng464dc9b2007-03-22 01:54:19 +00005296 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5297 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5298 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005299 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5300 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005301 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5302 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005303 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005304 // CombineTo deleted the truncate, if needed, but not what's under it.
5305 AddToWorkList(oye);
5306 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005307 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005308 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005309 }
5310
Chris Lattner8746e2c2006-09-20 06:29:17 +00005311 // fold (aext (truncate x))
5312 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005313 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005314 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005315 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005316 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005317 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5318 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005319 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005320
Dan Gohmanad3e5492009-04-08 00:15:30 +00005321 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5322 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005323 if (N0.getOpcode() == ISD::AND &&
5324 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005325 N0.getOperand(1).getOpcode() == ISD::Constant &&
5326 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5327 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005328 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005329 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005330 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005331 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005332 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005333 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005334 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005335 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005336 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005337 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005338 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005339
Chris Lattner812646a2006-05-05 05:58:59 +00005340 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005341 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005342 // on vectors in one instruction. We only perform this transformation on
5343 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005344 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005345 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005346 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005347 bool DoXform = true;
5348 SmallVector<SDNode*, 4> SetCCs;
5349 if (!N0.hasOneUse())
5350 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5351 if (DoXform) {
5352 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005353 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005354 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005355 LN0->getBasePtr(), N0.getValueType(),
5356 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005357 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005358 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005359 N0.getValueType(), ExtLoad);
5360 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005361 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005362 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005363 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5364 }
Chris Lattner812646a2006-05-05 05:58:59 +00005365 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005366
Chris Lattner812646a2006-05-05 05:58:59 +00005367 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5368 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5369 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005370 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005371 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005372 N0.hasOneUse()) {
5373 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005374 EVT MemVT = LN0->getMemoryVT();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005375 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
Stuart Hastings81c43062011-02-16 16:23:55 +00005376 VT, LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005377 MemVT, LN0->getMemOperand());
Chris Lattner812646a2006-05-05 05:58:59 +00005378 CombineTo(N, ExtLoad);
Evan Cheng894be332008-08-29 23:20:46 +00005379 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005380 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005381 N0.getValueType(), ExtLoad),
Chris Lattner812646a2006-05-05 05:58:59 +00005382 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005383 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner812646a2006-05-05 05:58:59 +00005384 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005385
Chris Lattner65786b02007-04-11 05:32:27 +00005386 if (N0.getOpcode() == ISD::SETCC) {
Evan Chengabd0ad52010-05-19 01:08:17 +00005387 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5388 // Only do this before legalize for now.
5389 if (VT.isVector() && !LegalOperations) {
5390 EVT N0VT = N0.getOperand(0).getValueType();
5391 // We know that the # elements of the results is the same as the
5392 // # elements of the compare (and the # elements of the compare result
5393 // for that matter). Check to see that they are the same size. If so,
5394 // we know that the element size of the sext'd result matches the
5395 // element size of the compare operands.
5396 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005397 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005398 N0.getOperand(1),
5399 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005400 // If the desired elements are smaller or larger than the source
5401 // elements we can use a matching integer vector type and then
5402 // truncate/sign extend
5403 else {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005404 EVT MatchingElementType =
5405 EVT::getIntegerVT(*DAG.getContext(),
5406 N0VT.getScalarType().getSizeInBits());
5407 EVT MatchingVectorType =
5408 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5409 N0VT.getVectorNumElements());
5410 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005411 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005412 N0.getOperand(1),
5413 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005414 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005415 }
5416 }
5417
5418 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005419 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005420 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005421 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005422 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005423 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005424 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005425 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005426
Evan Chengf1005572010-04-28 07:10:39 +00005427 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005428}
5429
Chris Lattner5e6fe052007-10-13 06:35:54 +00005430/// GetDemandedBits - See if the specified operand can be simplified with the
5431/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005432/// simpler operand, otherwise return a null SDValue.
5433SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005434 switch (V.getOpcode()) {
5435 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005436 case ISD::Constant: {
5437 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5438 assert(CV != 0 && "Const value should be ConstSDNode.");
5439 const APInt &CVal = CV->getAPIntValue();
5440 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005441 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005442 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005443 break;
5444 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005445 case ISD::OR:
5446 case ISD::XOR:
5447 // If the LHS or RHS don't contribute bits to the or, drop them.
5448 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5449 return V.getOperand(1);
5450 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5451 return V.getOperand(0);
5452 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005453 case ISD::SRL:
5454 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005455 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005456 break;
5457 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5458 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005459 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005460
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005461 // Watch out for shift count overflow though.
5462 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005463 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005464 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005465 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005466 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005467 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005468 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005469 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005470 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005471}
5472
Evan Cheng464dc9b2007-03-22 01:54:19 +00005473/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5474/// bits and then truncated to a narrower type and where N is a multiple
5475/// of number of bits of the narrower type, transform it to a narrower load
5476/// from address + N / num of bits of new type. If the result is to be
5477/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005478SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005479 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005480
Evan Cheng464dc9b2007-03-22 01:54:19 +00005481 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005482 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005483 EVT VT = N->getValueType(0);
5484 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005485
Dan Gohman550c9af2008-08-14 20:04:46 +00005486 // This transformation isn't valid for vector loads.
5487 if (VT.isVector())
5488 return SDValue();
5489
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005490 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005491 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005492 if (Opc == ISD::SIGN_EXTEND_INREG) {
5493 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005494 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005495 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005496 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005497 ExtType = ISD::ZEXTLOAD;
5498 N0 = SDValue(N, 0);
5499 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5500 if (!N01) return SDValue();
5501 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5502 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005503 }
Richard Osborne272e0842011-01-31 17:41:44 +00005504 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5505 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005506
Owen Anderson53aa7a92009-08-10 22:56:29 +00005507 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005508
Chris Lattner9a499e92010-12-22 08:01:44 +00005509 // Do not generate loads of non-round integer types since these can
5510 // be expensive (and would be wrong if the type is not byte sized).
5511 if (!ExtVT.isRound())
5512 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005513
Evan Cheng464dc9b2007-03-22 01:54:19 +00005514 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005515 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005516 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005517 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005518 // Is the shift amount a multiple of size of VT?
5519 if ((ShAmt & (EVTBits-1)) == 0) {
5520 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005521 // Is the load width a multiple of size of VT?
5522 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005523 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005524 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005525
Chris Lattnercafc1e62010-12-22 08:02:57 +00005526 // At this point, we must have a load or else we can't do the transform.
5527 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005528
Chandler Carruthb27041c2012-12-11 00:36:57 +00005529 // Because a SRL must be assumed to *need* to zero-extend the high bits
5530 // (as opposed to anyext the high bits), we can't combine the zextload
5531 // lowering of SRL and an sextload.
5532 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5533 return SDValue();
5534
Chris Lattnera2050552010-10-01 05:36:09 +00005535 // If the shift amount is larger than the input type then we're not
5536 // accessing any of the loaded bytes. If the load was a zextload/extload
5537 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005538 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005539 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005540 }
5541 }
5542
Dan Gohman68fb0042010-11-03 01:47:46 +00005543 // If the load is shifted left (and the result isn't shifted back right),
5544 // we can fold the truncate through the shift.
5545 unsigned ShLeftAmt = 0;
5546 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005547 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005548 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5549 ShLeftAmt = N01->getZExtValue();
5550 N0 = N0.getOperand(0);
5551 }
5552 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005553
Chris Lattner222374d2010-12-22 07:36:50 +00005554 // If we haven't found a load, we can't narrow it. Don't transform one with
5555 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005556 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5557 return SDValue();
5558
5559 // Don't change the width of a volatile load.
5560 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5561 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005562 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005563
Chris Lattner9a499e92010-12-22 08:01:44 +00005564 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005565 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005566 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005567
Bill Schmidtd006c692013-01-14 22:04:38 +00005568 // For the transform to be legal, the load must produce only two values
5569 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005570 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005571 // transformation is not equivalent, and the downstream logic to replace
5572 // uses gets things wrong.
5573 if (LN0->getNumValues() > 2)
5574 return SDValue();
5575
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005576 // If the load that we're shrinking is an extload and we're not just
5577 // discarding the extension we can't simply shrink the load. Bail.
5578 // TODO: It would be possible to merge the extensions in some cases.
5579 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5580 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5581 return SDValue();
5582
Chris Lattner222374d2010-12-22 07:36:50 +00005583 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005584
Evan Cheng4c6f9172012-06-26 01:19:33 +00005585 if (PtrType == MVT::Untyped || PtrType.isExtended())
5586 // It's not possible to generate a constant of extended or untyped type.
5587 return SDValue();
5588
Chris Lattner222374d2010-12-22 07:36:50 +00005589 // For big endian targets, we need to adjust the offset to the pointer to
5590 // load the correct bytes.
5591 if (TLI.isBigEndian()) {
5592 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5593 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5594 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005595 }
5596
Chris Lattner222374d2010-12-22 07:36:50 +00005597 uint64_t PtrOff = ShAmt / 8;
5598 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005599 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005600 PtrType, LN0->getBasePtr(),
5601 DAG.getConstant(PtrOff, PtrType));
5602 AddToWorkList(NewPtr.getNode());
5603
Chris Lattner9a499e92010-12-22 08:01:44 +00005604 SDValue Load;
5605 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005606 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005607 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005608 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005609 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005610 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005611 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005612 LN0->getPointerInfo().getWithOffset(PtrOff),
5613 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005614 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005615
5616 // Replace the old load's chain with the new load's chain.
5617 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005618 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005619
5620 // Shift the result left, if we've swallowed a left shift.
5621 SDValue Result = Load;
5622 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005623 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005624 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5625 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005626 // If the shift amount is as large as the result size (but, presumably,
5627 // no larger than the source) then the useful bits of the result are
5628 // zero; we can't simply return the shortened shift, because the result
5629 // of that operation is undefined.
5630 if (ShLeftAmt >= VT.getSizeInBits())
5631 Result = DAG.getConstant(0, VT);
5632 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005633 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005634 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005635 }
5636
5637 // Return the new loaded value.
5638 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005639}
5640
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005641SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5642 SDValue N0 = N->getOperand(0);
5643 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005644 EVT VT = N->getValueType(0);
5645 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005646 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005647 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005648
Nate Begeman21158fc2005-09-01 00:19:25 +00005649 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005650 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005651 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005652
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005653 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005654 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005655 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005656
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005657 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5658 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005659 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005660 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005661 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005662
Dan Gohman345d63c2008-07-31 00:50:31 +00005663 // fold (sext_in_reg (sext x)) -> (sext x)
5664 // fold (sext_in_reg (aext x)) -> (sext x)
5665 // if x is small enough.
5666 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5667 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005668 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5669 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005670 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005671 }
5672
Chris Lattner9ad59152007-04-17 19:03:21 +00005673 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005674 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005675 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005676
Chris Lattner9ad59152007-04-17 19:03:21 +00005677 // fold operands of sext_in_reg based on knowledge that the top bits are not
5678 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005679 if (SimplifyDemandedBits(SDValue(N, 0)))
5680 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005681
Evan Cheng464dc9b2007-03-22 01:54:19 +00005682 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5683 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005684 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005685 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005686 return NarrowLoad;
5687
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005688 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005689 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005690 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5691 if (N0.getOpcode() == ISD::SRL) {
5692 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005693 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005694 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005695 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005696 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005697 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005698 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005699 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005700 }
5701 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005702
Nate Begeman02b23c62005-10-13 03:11:28 +00005703 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005704 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005705 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005706 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005707 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005708 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005709 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005710 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005711 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005712 LN0->getBasePtr(), EVT,
5713 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005714 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005715 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005716 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005717 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005718 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005719 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005720 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005721 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005722 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005723 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005724 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005725 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005726 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005727 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005728 LN0->getBasePtr(), EVT,
5729 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005730 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005731 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005732 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005733 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005734
5735 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5736 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5737 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5738 N0.getOperand(1), false);
5739 if (BSwap.getNode() != 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005740 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005741 BSwap, N1);
5742 }
5743
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005744 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5745 // into a build_vector.
5746 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5747 SmallVector<SDValue, 8> Elts;
5748 unsigned NumElts = N0->getNumOperands();
5749 unsigned ShAmt = VTBits - EVTBits;
5750
5751 for (unsigned i = 0; i != NumElts; ++i) {
5752 SDValue Op = N0->getOperand(i);
5753 if (Op->getOpcode() == ISD::UNDEF) {
5754 Elts.push_back(Op);
5755 continue;
5756 }
5757
5758 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005759 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5760 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005761 Op.getValueType()));
5762 }
5763
5764 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5765 }
5766
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005767 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005768}
5769
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005770SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5771 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005772 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005773 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005774
5775 // noop truncate
5776 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005777 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005778 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005779 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005780 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005781 // fold (truncate (truncate x)) -> (truncate x)
5782 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005783 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005784 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005785 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5786 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005787 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005788 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005789 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005790 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005791 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005792 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005793 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005794 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005795 // if the source and dest are the same type, we can drop both the extend
5796 // and the truncate.
5797 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005798 }
Evan Chengd63baea2007-03-21 20:14:05 +00005799
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005800 // Fold extract-and-trunc into a narrow extract. For example:
5801 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5802 // i32 y = TRUNCATE(i64 x)
5803 // -- becomes --
5804 // v16i8 b = BITCAST (v2i64 val)
5805 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5806 //
5807 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005808 // creates this pattern) and before operation legalization after which
5809 // we need to be more careful about the vector instructions that we generate.
5810 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005811 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005812
5813 EVT VecTy = N0.getOperand(0).getValueType();
5814 EVT ExTy = N0.getValueType();
5815 EVT TrTy = N->getValueType(0);
5816
5817 unsigned NumElem = VecTy.getVectorNumElements();
5818 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5819
5820 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5821 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5822
5823 SDValue EltNo = N0->getOperand(1);
5824 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5825 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005826 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005827 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5828
Andrew Trickef9de2a2013-05-25 02:42:55 +00005829 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005830 NVT, N0.getOperand(0));
5831
5832 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005833 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005834 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005835 }
5836 }
5837
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005838 // Fold a series of buildvector, bitcast, and truncate if possible.
5839 // For example fold
5840 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5841 // (2xi32 (buildvector x, y)).
5842 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5843 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5844 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5845 N0.getOperand(0).hasOneUse()) {
5846
5847 SDValue BuildVect = N0.getOperand(0);
5848 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5849 EVT TruncVecEltTy = VT.getVectorElementType();
5850
5851 // Check that the element types match.
5852 if (BuildVectEltTy == TruncVecEltTy) {
5853 // Now we only need to compute the offset of the truncated elements.
5854 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5855 unsigned TruncVecNumElts = VT.getVectorNumElements();
5856 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5857
5858 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5859 "Invalid number of elements");
5860
5861 SmallVector<SDValue, 8> Opnds;
5862 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5863 Opnds.push_back(BuildVect.getOperand(i));
5864
Andrew Trickef9de2a2013-05-25 02:42:55 +00005865 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005866 Opnds.size());
5867 }
5868 }
5869
Chris Lattner5e6fe052007-10-13 06:35:54 +00005870 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00005871 // only the low bits are being used.
5872 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00005873 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00005874 // may have different active low bits.
5875 if (!VT.isVector()) {
5876 SDValue Shorter =
5877 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5878 VT.getSizeInBits()));
5879 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005880 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00005881 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005882 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00005883 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00005884 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5885 SDValue Reduced = ReduceLoadWidth(N);
5886 if (Reduced.getNode())
5887 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00005888 // Handle the case where the load remains an extending load even
5889 // after truncation.
5890 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5891 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5892 if (!LN0->isVolatile() &&
5893 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5894 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5895 VT, LN0->getChain(), LN0->getBasePtr(),
5896 LN0->getMemoryVT(),
5897 LN0->getMemOperand());
5898 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5899 return NewLoad;
5900 }
5901 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005902 }
Michael Liao3ac82012012-10-17 23:45:54 +00005903 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5904 // where ... are all 'undef'.
5905 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5906 SmallVector<EVT, 8> VTs;
5907 SDValue V;
5908 unsigned Idx = 0;
5909 unsigned NumDefs = 0;
5910
5911 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5912 SDValue X = N0.getOperand(i);
5913 if (X.getOpcode() != ISD::UNDEF) {
5914 V = X;
5915 Idx = i;
5916 NumDefs++;
5917 }
5918 // Stop if more than one members are non-undef.
5919 if (NumDefs > 1)
5920 break;
5921 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5922 VT.getVectorElementType(),
5923 X.getValueType().getVectorNumElements()));
5924 }
5925
5926 if (NumDefs == 0)
5927 return DAG.getUNDEF(VT);
5928
5929 if (NumDefs == 1) {
5930 assert(V.getNode() && "The single defined operand is empty!");
5931 SmallVector<SDValue, 8> Opnds;
5932 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5933 if (i != Idx) {
5934 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5935 continue;
5936 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005937 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00005938 AddToWorkList(NV.getNode());
5939 Opnds.push_back(NV);
5940 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005941 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao3ac82012012-10-17 23:45:54 +00005942 &Opnds[0], Opnds.size());
5943 }
5944 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005945
5946 // Simplify the operands using demanded-bits information.
5947 if (!VT.isVector() &&
5948 SimplifyDemandedBits(SDValue(N, 0)))
5949 return SDValue(N, 0);
5950
Evan Chengf1bd5fc2010-04-17 06:13:15 +00005951 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005952}
5953
Evan Chengb980f6f2008-05-12 23:04:07 +00005954static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005955 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00005956 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00005957 return Elt.getNode();
5958 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00005959}
5960
5961/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00005962/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00005963SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00005964 assert(N->getOpcode() == ISD::BUILD_PAIR);
5965
Nate Begeman624690c2009-06-05 21:37:30 +00005966 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5967 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00005968 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00005969 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005970 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00005971 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00005972
Evan Chengb980f6f2008-05-12 23:04:07 +00005973 if (ISD::isNON_EXTLoad(LD2) &&
5974 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00005975 // If both are volatile this would reduce the number of volatile loads.
5976 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00005977 !LD1->isVolatile() &&
5978 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00005979 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00005980 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00005981 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00005982 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00005983
Duncan Sands8651e9c2008-06-13 19:07:40 +00005984 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005985 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005986 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00005987 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005988 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00005989 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00005990
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005991 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00005992}
5993
Wesley Peck527da1b2010-11-23 03:31:01 +00005994SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005995 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005996 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00005997
Dan Gohmana8665142007-06-25 16:23:39 +00005998 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5999 // Only do this before legalize, since afterward the target may be depending
6000 // on the bitconvert.
6001 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006002 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006003 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006004 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006005 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006006
Owen Anderson53aa7a92009-08-10 22:56:29 +00006007 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006008 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006009 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006010 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006011 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006012 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006013
Dan Gohman921ddd62008-09-05 01:58:21 +00006014 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006015 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006016 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006017 if (Res.getNode() != N) {
6018 if (!LegalOperations ||
6019 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6020 return Res;
6021
6022 // Folding it resulted in an illegal node, and it's too late to
6023 // do that. Clean up the old node and forego the transformation.
6024 // Ideally this won't happen very often, because instcombine
6025 // and the earlier dagcombine runs (where illegal nodes are
6026 // permitted) should have folded most of them already.
6027 DAG.DeleteNode(Res.getNode());
6028 }
Chris Lattnera1874602005-12-23 05:30:37 +00006029 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006030
Bill Wendling4e0a6152009-01-30 22:44:24 +00006031 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006032 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006033 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006034 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006035
Chris Lattner54560f62005-12-23 05:44:41 +00006036 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006037 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006038 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006039 // Do not change the width of a volatile load.
6040 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006041 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6042 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006043 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006044 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006045 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006046 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006047
Evan Chenga4cf58a2007-05-07 21:27:48 +00006048 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006049 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006050 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006051 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006052 LN0->isInvariant(), OrigAlign,
6053 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006054 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006055 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006056 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006057 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006058 Load.getValue(1));
6059 return Load;
6060 }
Chris Lattner54560f62005-12-23 05:44:41 +00006061 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006062
Bill Wendling4e0a6152009-01-30 22:44:24 +00006063 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6064 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006065 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006066 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6067 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006068 N0.getNode()->hasOneUse() && VT.isInteger() &&
6069 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006070 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006071 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006072 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006073
Duncan Sands13237ac2008-06-06 12:08:01 +00006074 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006075 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006076 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006077 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006078 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006079 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006080 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006081 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006082
Bill Wendling4e0a6152009-01-30 22:44:24 +00006083 // fold (bitconvert (fcopysign cst, x)) ->
6084 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6085 // Note that we don't handle (copysign x, cst) because this can always be
6086 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006087 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006088 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006089 VT.isInteger() && !VT.isVector()) {
6090 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006091 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006092 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006093 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006094 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006095 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006096
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006097 // If X has a different width than the result/lhs, sext it or truncate it.
6098 unsigned VTWidth = VT.getSizeInBits();
6099 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006100 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006101 AddToWorkList(X.getNode());
6102 } else if (OrigXWidth > VTWidth) {
6103 // To get the sign bit in the right place, we have to shift it right
6104 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006105 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006106 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006107 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6108 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006109 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006110 AddToWorkList(X.getNode());
6111 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006112
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006113 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006114 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006115 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006116 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006117
Andrew Trickef9de2a2013-05-25 02:42:55 +00006118 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006119 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006120 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006121 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006122 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006123
Andrew Trickef9de2a2013-05-25 02:42:55 +00006124 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006125 }
Chris Lattner888560d2008-01-27 17:42:27 +00006126 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006127
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006128 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006129 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006130 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6131 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006132 return CombineLD;
6133 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006134
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006135 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006136}
6137
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006138SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006139 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006140 return CombineConsecutiveLoads(N, VT);
6141}
6142
Wesley Peck527da1b2010-11-23 03:31:01 +00006143/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006144/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006145/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006146SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006147ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006148 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006149
Chris Lattnere4e64b62006-04-02 02:53:43 +00006150 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006151 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006152
Duncan Sands13237ac2008-06-06 12:08:01 +00006153 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6154 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006155
Chris Lattnere4e64b62006-04-02 02:53:43 +00006156 // If this is a conversion of N elements of one type to N elements of another
6157 // type, convert each element. This handles FP<->INT cases.
6158 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006159 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6160 BV->getValueType(0).getVectorNumElements());
6161
6162 // Due to the FP element handling below calling this routine recursively,
6163 // we can end up with a scalar-to-vector node here.
6164 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006165 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6166 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006167 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006168
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006169 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006170 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006171 SDValue Op = BV->getOperand(i);
6172 // If the vector element type is not legal, the BUILD_VECTOR operands
6173 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006174 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006175 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6176 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006177 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006178 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006179 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006180 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006181 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006182 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006183
Chris Lattnere4e64b62006-04-02 02:53:43 +00006184 // Otherwise, we're growing or shrinking the elements. To avoid having to
6185 // handle annoying details of growing/shrinking FP values, we convert them to
6186 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006187 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006188 // Convert the input float vector to a int vector where the elements are the
6189 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006190 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006191 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006192 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006193 SrcEltVT = IntVT;
6194 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006195
Chris Lattnere4e64b62006-04-02 02:53:43 +00006196 // Now we know the input is an integer vector. If the output is a FP type,
6197 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006198 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006199 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006200 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006201 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006202
Chris Lattnere4e64b62006-04-02 02:53:43 +00006203 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006204 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006205 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006206
Chris Lattnere4e64b62006-04-02 02:53:43 +00006207 // Okay, we know the src/dst types are both integers of differing types.
6208 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006209 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006210 if (SrcBitSize < DstBitSize) {
6211 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006212
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006213 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006214 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006215 i += NumInputsPerOutput) {
6216 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006217 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006218 bool EltIsUndef = true;
6219 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6220 // Shift the previously computed bits over.
6221 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006222 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006223 if (Op.getOpcode() == ISD::UNDEF) continue;
6224 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006225
Jay Foad583abbc2010-12-07 08:25:19 +00006226 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006227 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006228 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006229
Chris Lattnere4e64b62006-04-02 02:53:43 +00006230 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006231 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006232 else
6233 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6234 }
6235
Owen Anderson117c9e82009-08-12 00:36:31 +00006236 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006237 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006238 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006239 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006240
Chris Lattnere4e64b62006-04-02 02:53:43 +00006241 // Finally, this must be the case where we are shrinking elements: each input
6242 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006243 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006244 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006245 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6246 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006247 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006248
Dan Gohmana8665142007-06-25 16:23:39 +00006249 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006250 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6251 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006252 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006253 continue;
6254 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006255
Jay Foad583abbc2010-12-07 08:25:19 +00006256 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6257 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006258
Chris Lattnere4e64b62006-04-02 02:53:43 +00006259 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006260 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006261 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006262 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006263 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006264 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006265 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006266 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006267 }
6268
6269 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006270 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006271 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6272 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006273
Andrew Trickef9de2a2013-05-25 02:42:55 +00006274 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006275 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006276}
6277
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006278SDValue DAGCombiner::visitFADD(SDNode *N) {
6279 SDValue N0 = N->getOperand(0);
6280 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006281 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6282 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006283 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006284
Dan Gohmana8665142007-06-25 16:23:39 +00006285 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006286 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006287 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006288 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006289 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006290
Lang Hamesa33db652012-06-14 20:37:15 +00006291 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006292 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006293 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006294 // canonicalize constant to RHS
6295 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006296 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006297 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006298 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6299 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006300 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006301 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006302 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006303 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006304 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006305 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006306 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006307 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006308 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006309 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006310 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006311
Chris Lattner0199fd62007-01-08 23:04:05 +00006312 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006313 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6314 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6315 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006316 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6317 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006318 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006319
Shuxin Yang93b1f122013-03-25 22:52:29 +00006320 // No FP constant should be created after legalization as Instruction
6321 // Selection pass has hard time in dealing with FP constant.
6322 //
6323 // We don't need test this condition for transformation like following, as
6324 // the DAG being transformed implies it is legal to take FP constant as
6325 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006326 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006327 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006328 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006329 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6330
Owen Andersonb351c8d2012-11-01 02:00:53 +00006331 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006332 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006333 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006334 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006335
6336 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006337 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006338 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006339 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006340
Owen Andersoncc61f872012-08-30 23:35:16 +00006341 // In unsafe math mode, we can fold chains of FADD's of the same value
6342 // into multiplications. This transform is not safe in general because
6343 // we are reducing the number of rounding steps.
6344 if (DAG.getTarget().Options.UnsafeFPMath &&
6345 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6346 !N0CFP && !N1CFP) {
6347 if (N0.getOpcode() == ISD::FMUL) {
6348 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6349 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6350
Stephen Line31f2d22013-06-14 18:17:35 +00006351 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006352 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006353 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006354 SDValue(CFP00, 0),
6355 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006356 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006357 N1, NewCFP);
6358 }
6359
Stephen Line31f2d22013-06-14 18:17:35 +00006360 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006361 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006362 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006363 SDValue(CFP01, 0),
6364 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006365 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006366 N1, NewCFP);
6367 }
6368
Stephen Line31f2d22013-06-14 18:17:35 +00006369 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006370 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6371 N1.getOperand(0) == N1.getOperand(1) &&
6372 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006373 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006374 SDValue(CFP00, 0),
6375 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006376 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006377 N0.getOperand(1), NewCFP);
6378 }
6379
Stephen Line31f2d22013-06-14 18:17:35 +00006380 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006381 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6382 N1.getOperand(0) == N1.getOperand(1) &&
6383 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006384 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006385 SDValue(CFP01, 0),
6386 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006387 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006388 N0.getOperand(0), NewCFP);
6389 }
6390 }
6391
6392 if (N1.getOpcode() == ISD::FMUL) {
6393 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6394 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6395
Stephen Line31f2d22013-06-14 18:17:35 +00006396 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006397 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006398 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006399 SDValue(CFP10, 0),
6400 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006401 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006402 N0, NewCFP);
6403 }
6404
Stephen Line31f2d22013-06-14 18:17:35 +00006405 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006406 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006407 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006408 SDValue(CFP11, 0),
6409 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006410 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006411 N0, NewCFP);
6412 }
6413
Owen Andersoncc61f872012-08-30 23:35:16 +00006414
Stephen Line31f2d22013-06-14 18:17:35 +00006415 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6416 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6417 N0.getOperand(0) == N0.getOperand(1) &&
6418 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006419 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006420 SDValue(CFP10, 0),
6421 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006422 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006423 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006424 }
6425
Stephen Line31f2d22013-06-14 18:17:35 +00006426 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6427 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6428 N0.getOperand(0) == N0.getOperand(1) &&
6429 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006430 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006431 SDValue(CFP11, 0),
6432 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006433 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006434 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006435 }
6436 }
6437
Shuxin Yang93b1f122013-03-25 22:52:29 +00006438 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006439 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006440 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006441 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006442 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006443 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006444 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006445 }
6446
Shuxin Yang93b1f122013-03-25 22:52:29 +00006447 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006448 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006449 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006450 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006451 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006452 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006453 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006454 }
6455
Stephen Lin4e69d012013-06-14 21:33:58 +00006456 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006457 if (AllowNewFpConst &&
6458 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006459 N0.getOperand(0) == N0.getOperand(1) &&
6460 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006461 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006462 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006463 N0.getOperand(0),
6464 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006465 }
6466
Lang Hames39fb1d02012-06-19 22:51:23 +00006467 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006468 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006469 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006470 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6471 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006472
6473 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006474 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006475 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006476 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006477
Michael Liaoec3850122012-09-01 04:09:16 +00006478 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006479 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006480 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006481 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006482 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006483 }
6484
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006485 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006486}
6487
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006488SDValue DAGCombiner::visitFSUB(SDNode *N) {
6489 SDValue N0 = N->getOperand(0);
6490 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006491 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6492 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006493 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006494 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006495
Dan Gohmana8665142007-06-25 16:23:39 +00006496 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006497 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006498 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006499 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006500 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006501
Nate Begeman418c6e42005-10-18 00:28:13 +00006502 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006503 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006504 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006505 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006506 if (DAG.getTarget().Options.UnsafeFPMath &&
6507 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006508 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006509 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006510 if (DAG.getTarget().Options.UnsafeFPMath &&
6511 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006512 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006513 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006514 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006515 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006516 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006517 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006518 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006519 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006520 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006521
Bill Wendlingdf170db2012-03-15 05:12:00 +00006522 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006523 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006524 // (fsub x, (fadd x, y)) -> (fneg y) &
6525 // (fsub x, (fadd y, x)) -> (fneg y)
6526 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006527 if (N0 == N1)
6528 return DAG.getConstantFP(0.0f, VT);
6529
Bill Wendlingdf170db2012-03-15 05:12:00 +00006530 if (N1.getOpcode() == ISD::FADD) {
6531 SDValue N10 = N1->getOperand(0);
6532 SDValue N11 = N1->getOperand(1);
6533
6534 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6535 &DAG.getTarget().Options))
6536 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006537
Stephen Lin8e8424e2013-07-09 00:44:49 +00006538 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6539 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006540 return GetNegatedExpression(N10, DAG, LegalOperations);
6541 }
6542 }
6543
Lang Hames39fb1d02012-06-19 22:51:23 +00006544 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006545 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006546 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006547 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6548 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006549
6550 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006551 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006552 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006553 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006554 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006555
6556 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6557 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006558 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006559 return DAG.getNode(ISD::FMA, dl, VT,
6560 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006561 N1.getOperand(0)),
6562 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006563
Stephen Lin8e8424e2013-07-09 00:44:49 +00006564 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006565 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006566 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6567 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6568 SDValue N00 = N0.getOperand(0).getOperand(0);
6569 SDValue N01 = N0.getOperand(0).getOperand(1);
6570 return DAG.getNode(ISD::FMA, dl, VT,
6571 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6572 DAG.getNode(ISD::FNEG, dl, VT, N1));
6573 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006574 }
6575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006576 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006577}
6578
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006579SDValue DAGCombiner::visitFMUL(SDNode *N) {
6580 SDValue N0 = N->getOperand(0);
6581 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006582 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6583 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006584 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006585 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006586
Dan Gohmana8665142007-06-25 16:23:39 +00006587 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006588 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006589 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006590 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006591 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006592
Nate Begemanec48a1b2005-10-17 20:40:11 +00006593 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006594 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006595 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006596 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006597 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006598 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006599 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006600 if (DAG.getTarget().Options.UnsafeFPMath &&
6601 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006602 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006603 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006604 if (DAG.getTarget().Options.UnsafeFPMath &&
6605 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006606 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006607 // fold (fmul A, 1.0) -> A
6608 if (N1CFP && N1CFP->isExactlyValue(1.0))
6609 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006610 // fold (fmul X, 2.0) -> (fadd X, X)
6611 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006612 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006613 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006614 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006615 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006616 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006617
Bill Wendling3dc5d242009-01-30 22:57:07 +00006618 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006619 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006620 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006621 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006622 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006623 // Both can be negated for free, check to see if at least one is cheaper
6624 // negated.
6625 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006626 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006627 GetNegatedExpression(N0, DAG, LegalOperations),
6628 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006629 }
6630 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006631
Chris Lattner0199fd62007-01-08 23:04:05 +00006632 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006633 if (DAG.getTarget().Options.UnsafeFPMath &&
6634 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006635 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6637 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006638 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006639
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006640 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006641}
6642
Owen Anderson41b06652012-05-02 22:17:40 +00006643SDValue DAGCombiner::visitFMA(SDNode *N) {
6644 SDValue N0 = N->getOperand(0);
6645 SDValue N1 = N->getOperand(1);
6646 SDValue N2 = N->getOperand(2);
6647 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6648 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6649 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006650 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006651
Owen Andersonb351c8d2012-11-01 02:00:53 +00006652 if (DAG.getTarget().Options.UnsafeFPMath) {
6653 if (N0CFP && N0CFP->isZero())
6654 return N2;
6655 if (N1CFP && N1CFP->isZero())
6656 return N2;
6657 }
Owen Anderson41b06652012-05-02 22:17:40 +00006658 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006659 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006660 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006661 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006662
Owen Andersonc7aaf522012-05-30 18:50:39 +00006663 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006664 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006665 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006666
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006667 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6668 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6669 N2.getOpcode() == ISD::FMUL &&
6670 N0 == N2.getOperand(0) &&
6671 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6672 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6673 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6674 }
6675
6676
6677 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6678 if (DAG.getTarget().Options.UnsafeFPMath &&
6679 N0.getOpcode() == ISD::FMUL && N1CFP &&
6680 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6681 return DAG.getNode(ISD::FMA, dl, VT,
6682 N0.getOperand(0),
6683 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6684 N2);
6685 }
6686
6687 // (fma x, 1, y) -> (fadd x, y)
6688 // (fma x, -1, y) -> (fadd (fneg x), y)
6689 if (N1CFP) {
6690 if (N1CFP->isExactlyValue(1.0))
6691 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6692
6693 if (N1CFP->isExactlyValue(-1.0) &&
6694 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6695 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6696 AddToWorkList(RHSNeg.getNode());
6697 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6698 }
6699 }
6700
6701 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006702 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6703 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006704 DAG.getNode(ISD::FADD, dl, VT,
6705 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006706
6707 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6708 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006709 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6710 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006711 DAG.getNode(ISD::FADD, dl, VT,
6712 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006713
6714
Owen Anderson41b06652012-05-02 22:17:40 +00006715 return SDValue();
6716}
6717
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006718SDValue DAGCombiner::visitFDIV(SDNode *N) {
6719 SDValue N0 = N->getOperand(0);
6720 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006721 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6722 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006723 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006724 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006725
Dan Gohmana8665142007-06-25 16:23:39 +00006726 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006727 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006728 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006729 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006730 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006731
Nate Begeman569c4392006-01-18 22:35:16 +00006732 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006733 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006734 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006735
Duncan Sands2f1dc382012-04-08 18:08:12 +00006736 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006737 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006738 // Compute the reciprocal 1.0 / c2.
6739 APFloat N1APF = N1CFP->getValueAPF();
6740 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6741 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006742 // Only do the transform if the reciprocal is a legal fp immediate that
6743 // isn't too nasty (eg NaN, denormal, ...).
6744 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006745 (!LegalOperations ||
6746 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6747 // backend)... we should handle this gracefully after Legalize.
6748 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6749 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6750 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006751 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006752 DAG.getConstantFP(Recip, VT));
6753 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006754
Bill Wendling3dc5d242009-01-30 22:57:07 +00006755 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006756 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006757 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006758 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006759 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006760 // Both can be negated for free, check to see if at least one is cheaper
6761 // negated.
6762 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006763 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006764 GetNegatedExpression(N0, DAG, LegalOperations),
6765 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006766 }
6767 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006768
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006769 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006770}
6771
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006772SDValue DAGCombiner::visitFREM(SDNode *N) {
6773 SDValue N0 = N->getOperand(0);
6774 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006775 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6776 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006777 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006778
Nate Begeman569c4392006-01-18 22:35:16 +00006779 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006780 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006781 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006782
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006783 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006784}
6785
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006786SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6787 SDValue N0 = N->getOperand(0);
6788 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006789 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6790 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006791 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006792
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006793 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006794 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006795
Chris Lattner3bc40502006-03-05 05:30:57 +00006796 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006797 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006798 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6799 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006800 if (!V.isNegative()) {
6801 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006802 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006803 } else {
6804 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006805 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6806 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006807 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006808 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006809
Chris Lattner3bc40502006-03-05 05:30:57 +00006810 // copysign(fabs(x), y) -> copysign(x, y)
6811 // copysign(fneg(x), y) -> copysign(x, y)
6812 // copysign(copysign(x,z), y) -> copysign(x, y)
6813 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6814 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006815 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006816 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006817
6818 // copysign(x, abs(y)) -> abs(x)
6819 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006820 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006821
Chris Lattner3bc40502006-03-05 05:30:57 +00006822 // copysign(x, copysign(y,z)) -> copysign(x, z)
6823 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006824 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006825 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006826
Chris Lattner3bc40502006-03-05 05:30:57 +00006827 // copysign(x, fp_extend(y)) -> copysign(x, y)
6828 // copysign(x, fp_round(y)) -> copysign(x, y)
6829 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006830 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006831 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006832
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006833 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006834}
6835
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006836SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6837 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006838 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006839 EVT VT = N->getValueType(0);
6840 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006841
Nate Begeman21158fc2005-09-01 00:19:25 +00006842 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006843 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006844 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006845 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006846 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006847 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006848
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006849 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6850 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006851 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6852 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006853 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006854 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006855 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006856 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006857
Alp Tokercb402912014-01-24 17:20:08 +00006858 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006859 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6860 // having to say they don't support SELECT_CC on every type the DAG knows
6861 // about, since there is no way to mark an opcode illegal at all value types
6862 // (See also visitSELECT)
6863 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6864 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6865 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6866 !VT.isVector() &&
6867 (!LegalOperations ||
6868 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6869 SDValue Ops[] =
6870 { N0.getOperand(0), N0.getOperand(1),
6871 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6872 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006873 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006874 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006875
Nadav Rotem90560762012-07-23 07:59:50 +00006876 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6877 // (select_cc x, y, 1.0, 0.0,, cc)
6878 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6879 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6880 (!LegalOperations ||
6881 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6882 SDValue Ops[] =
6883 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6884 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6885 N0.getOperand(0).getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006886 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006887 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006888 }
6889
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006890 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006891}
6892
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006893SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6894 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006895 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006896 EVT VT = N->getValueType(0);
6897 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00006898
Nate Begeman21158fc2005-09-01 00:19:25 +00006899 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006900 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006901 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006902 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006903 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006904 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006905
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006906 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6907 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006908 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6909 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006910 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006911 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006912 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006913 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006914
Alp Tokercb402912014-01-24 17:20:08 +00006915 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006916 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6917 // having to say they don't support SELECT_CC on every type the DAG knows
6918 // about, since there is no way to mark an opcode illegal at all value types
6919 // (See also visitSELECT)
6920 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6921 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00006922
Nadav Rotem90560762012-07-23 07:59:50 +00006923 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6924 (!LegalOperations ||
6925 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6926 SDValue Ops[] =
6927 { N0.getOperand(0), N0.getOperand(1),
6928 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6929 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006930 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006931 }
6932 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006933
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006934 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006935}
6936
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006937SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6938 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006939 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006940 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006941
Nate Begeman21158fc2005-09-01 00:19:25 +00006942 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006943 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006944 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00006945
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006946 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006947}
6948
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006949SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6950 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006951 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006952 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006953
Nate Begeman21158fc2005-09-01 00:19:25 +00006954 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006955 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006956 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00006957
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006958 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006959}
6960
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006961SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6962 SDValue N0 = N->getOperand(0);
6963 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006964 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006965 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006966
Nate Begeman21158fc2005-09-01 00:19:25 +00006967 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006968 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006969 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006970
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006971 // fold (fp_round (fp_extend x)) -> x
6972 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6973 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006974
Chris Lattner0feb1b02008-01-24 06:45:35 +00006975 // fold (fp_round (fp_round x)) -> (fp_round x)
6976 if (N0.getOpcode() == ISD::FP_ROUND) {
6977 // This is a value preserving truncation if both round's are.
6978 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006979 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00006980 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00006981 DAG.getIntPtrConstant(IsTrunc));
6982 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006983
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006984 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006985 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006986 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006987 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006988 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006989 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006990 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006991 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006992
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006993 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006994}
6995
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006996SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6997 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006998 EVT VT = N->getValueType(0);
6999 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007000 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007001
Nate Begeman21158fc2005-09-01 00:19:25 +00007002 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007003 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007004 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007005 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007006 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007007
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007008 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007009}
7010
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007011SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7012 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007013 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007014 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007015
Chris Lattner5919b482007-12-29 06:55:23 +00007016 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007017 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007018 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007019 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007020
Nate Begeman21158fc2005-09-01 00:19:25 +00007021 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007022 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007023 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007024
7025 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7026 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007027 if (N0.getOpcode() == ISD::FP_ROUND
7028 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007029 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007030 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007031 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007032 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007033 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007034 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007035 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007036
Chris Lattner72733e52008-01-17 07:00:52 +00007037 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007038 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007039 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007040 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007041 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007042 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007043 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007044 LN0->getBasePtr(), N0.getValueType(),
7045 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007046 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007047 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007048 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007049 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007050 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007051 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007052 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007053
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007054 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007055}
7056
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007057SDValue DAGCombiner::visitFNEG(SDNode *N) {
7058 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007059 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007060
Craig Topper82384612012-09-11 01:45:21 +00007061 if (VT.isVector()) {
7062 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7063 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007064 }
7065
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007066 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7067 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007068 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007069
Chris Lattner888560d2008-01-27 17:42:27 +00007070 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7071 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007072 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007073 !VT.isVector() &&
7074 N0.getNode()->hasOneUse() &&
7075 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007076 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007077 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007078 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007079 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007080 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007081 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007082 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007083 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007084 }
7085 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007086
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007087 // (fneg (fmul c, x)) -> (fmul -c, x)
7088 if (N0.getOpcode() == ISD::FMUL) {
7089 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Lin8e8424e2013-07-09 00:44:49 +00007090 if (CFP1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007091 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007092 N0.getOperand(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007093 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007094 N0.getOperand(1)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007095 }
7096
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007097 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007098}
7099
Owen Andersona40319b2012-08-13 23:32:49 +00007100SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7101 SDValue N0 = N->getOperand(0);
7102 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7103 EVT VT = N->getValueType(0);
7104
7105 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007106 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007107 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007108
7109 return SDValue();
7110}
7111
7112SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7113 SDValue N0 = N->getOperand(0);
7114 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7115 EVT VT = N->getValueType(0);
7116
7117 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007118 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007119 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007120
7121 return SDValue();
7122}
7123
7124SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7125 SDValue N0 = N->getOperand(0);
7126 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7127 EVT VT = N->getValueType(0);
7128
7129 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007130 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007131 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007132
7133 return SDValue();
7134}
7135
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007136SDValue DAGCombiner::visitFABS(SDNode *N) {
7137 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007138 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007139 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007140
Craig Topper82384612012-09-11 01:45:21 +00007141 if (VT.isVector()) {
7142 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7143 if (FoldedVOp.getNode()) return FoldedVOp;
7144 }
7145
Nate Begeman21158fc2005-09-01 00:19:25 +00007146 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007147 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007148 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007149 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007150 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007151 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007152 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007153 // fold (fabs (fcopysign x, y)) -> (fabs x)
7154 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007155 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007156
Chris Lattner888560d2008-01-27 17:42:27 +00007157 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7158 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007159 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007160 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007161 N0.getOperand(0).getValueType().isInteger() &&
7162 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007163 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007164 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007165 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007166 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007167 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007168 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007169 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007170 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007171 }
7172 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007173
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007174 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007175}
7176
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007177SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7178 SDValue Chain = N->getOperand(0);
7179 SDValue N1 = N->getOperand(1);
7180 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007181
Dan Gohman82e80012009-11-17 00:47:23 +00007182 // If N is a constant we could fold this into a fallthrough or unconditional
7183 // branch. However that doesn't happen very often in normal code, because
7184 // Instcombine/SimplifyCFG should have handled the available opportunities.
7185 // If we did this folding here, it would be necessary to update the
7186 // MachineBasicBlock CFG, which is awkward.
7187
Nate Begeman7e7f4392006-02-01 07:19:44 +00007188 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7189 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007190 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007191 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7192 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007193 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007194 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007195 N1.getOperand(0), N1.getOperand(1), N2);
7196 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007197
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007198 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7199 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7200 (N1.getOperand(0).hasOneUse() &&
7201 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7202 SDNode *Trunc = 0;
7203 if (N1.getOpcode() == ISD::TRUNCATE) {
7204 // Look pass the truncate.
7205 Trunc = N1.getNode();
7206 N1 = N1.getOperand(0);
7207 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007208
Bill Wendlingaa28be62009-03-26 06:14:09 +00007209 // Match this pattern so that we can generate simpler code:
7210 //
7211 // %a = ...
7212 // %b = and i32 %a, 2
7213 // %c = srl i32 %b, 1
7214 // brcond i32 %c ...
7215 //
7216 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007217 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007218 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007219 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007220 // %c = setcc eq %b, 0
7221 // brcond %c ...
7222 //
7223 // This applies only when the AND constant value has one bit set and the
7224 // SRL constant is equal to the log2 of the AND constant. The back-end is
7225 // smart enough to convert the result into a TEST/JMP sequence.
7226 SDValue Op0 = N1.getOperand(0);
7227 SDValue Op1 = N1.getOperand(1);
7228
7229 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007230 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007231 SDValue AndOp1 = Op0.getOperand(1);
7232
7233 if (AndOp1.getOpcode() == ISD::Constant) {
7234 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7235
7236 if (AndConst.isPowerOf2() &&
7237 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7238 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007239 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007240 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007241 Op0, DAG.getConstant(0, Op0.getValueType()),
7242 ISD::SETNE);
7243
Andrew Trickef9de2a2013-05-25 02:42:55 +00007244 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007245 MVT::Other, Chain, SetCC, N2);
7246 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7247 // will convert it back to (X & C1) >> C2.
7248 CombineTo(N, NewBRCond, false);
7249 // Truncate is dead.
7250 if (Trunc) {
7251 removeFromWorkList(Trunc);
7252 DAG.DeleteNode(Trunc);
7253 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007254 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007255 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007256 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007257 removeFromWorkList(N1.getNode());
7258 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007259 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007260 }
7261 }
7262 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007263
7264 if (Trunc)
7265 // Restore N1 if the above transformation doesn't match.
7266 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007267 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007268
Evan Cheng228c31f2010-02-27 07:36:59 +00007269 // Transform br(xor(x, y)) -> br(x != y)
7270 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7271 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7272 SDNode *TheXor = N1.getNode();
7273 SDValue Op0 = TheXor->getOperand(0);
7274 SDValue Op1 = TheXor->getOperand(1);
7275 if (Op0.getOpcode() == Op1.getOpcode()) {
7276 // Avoid missing important xor optimizations.
7277 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007278 if (Tmp.getNode()) {
7279 if (Tmp.getNode() != TheXor) {
7280 DEBUG(dbgs() << "\nReplacing.8 ";
7281 TheXor->dump(&DAG);
7282 dbgs() << "\nWith: ";
7283 Tmp.getNode()->dump(&DAG);
7284 dbgs() << '\n');
7285 WorkListRemover DeadNodes(*this);
7286 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7287 removeFromWorkList(TheXor);
7288 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007289 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007290 MVT::Other, Chain, Tmp, N2);
7291 }
7292
Benjamin Kramer93354432013-03-30 21:28:18 +00007293 // visitXOR has changed XOR's operands or replaced the XOR completely,
7294 // bail out.
7295 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007296 }
7297 }
7298
7299 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7300 bool Equal = false;
7301 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7302 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7303 Op0.getOpcode() == ISD::XOR) {
7304 TheXor = Op0.getNode();
7305 Equal = true;
7306 }
7307
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007308 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007309 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007310 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007311 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007312 SetCCVT,
7313 Op0, Op1,
7314 Equal ? ISD::SETEQ : ISD::SETNE);
7315 // Replace the uses of XOR with SETCC
7316 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007317 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007318 removeFromWorkList(N1.getNode());
7319 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007320 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007321 MVT::Other, Chain, SetCC, N2);
7322 }
7323 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007324
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007325 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007326}
7327
Chris Lattnera49e16f2005-10-05 06:47:48 +00007328// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7329//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007330SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007331 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007332 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007333
Dan Gohman82e80012009-11-17 00:47:23 +00007334 // If N is a constant we could fold this into a fallthrough or unconditional
7335 // branch. However that doesn't happen very often in normal code, because
7336 // Instcombine/SimplifyCFG should have handled the available opportunities.
7337 // If we did this folding here, it would be necessary to update the
7338 // MachineBasicBlock CFG, which is awkward.
7339
Duncan Sands93b66092008-06-09 11:32:28 +00007340 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007341 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007342 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007343 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007344 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007345
Nate Begemanbd7df032005-10-05 21:43:42 +00007346 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007347 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007348 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007349 N->getOperand(0), Simp.getOperand(2),
7350 Simp.getOperand(0), Simp.getOperand(1),
7351 N->getOperand(4));
7352
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007353 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007354}
7355
Evan Chengfa832632012-01-13 01:37:24 +00007356/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7357/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007358/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007359static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7360 SelectionDAG &DAG,
7361 const TargetLowering &TLI) {
7362 EVT VT;
7363 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7364 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7365 return false;
7366 VT = Use->getValueType(0);
7367 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7368 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7369 return false;
7370 VT = ST->getValue().getValueType();
7371 } else
7372 return false;
7373
Chandler Carruth95f83e02013-01-07 15:14:13 +00007374 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007375 if (N->getOpcode() == ISD::ADD) {
7376 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7377 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007378 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007379 AM.BaseOffs = Offset->getSExtValue();
7380 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007381 // [reg +/- reg]
7382 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007383 } else if (N->getOpcode() == ISD::SUB) {
7384 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7385 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007386 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007387 AM.BaseOffs = -Offset->getSExtValue();
7388 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007389 // [reg +/- reg]
7390 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007391 } else
7392 return false;
7393
7394 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7395}
7396
Duncan Sands075293f2008-06-15 20:12:31 +00007397/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7398/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007399/// and it has other uses besides the load / store. After the
7400/// transformation, the new indexed load / store has effectively folded
7401/// the add / subtract in and all of its other uses are redirected to the
7402/// new load / store.
7403bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007404 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007405 return false;
7406
7407 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007408 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007409 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007410 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007411 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007412 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007413 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007414 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007415 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7416 return false;
7417 Ptr = LD->getBasePtr();
7418 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007419 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007420 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007421 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007422 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7423 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7424 return false;
7425 Ptr = ST->getBasePtr();
7426 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007427 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007428 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007429 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007430
Chris Lattnereabc15c2006-11-11 00:56:29 +00007431 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7432 // out. There is no reason to make this a preinc/predec.
7433 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007434 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007435 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007436
Chris Lattnereabc15c2006-11-11 00:56:29 +00007437 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007438 SDValue BasePtr;
7439 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007440 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7441 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7442 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007443
7444 // Backends without true r+i pre-indexed forms may need to pass a
7445 // constant base with a variable offset so that constant coercion
7446 // will work with the patterns in canonical form.
7447 bool Swapped = false;
7448 if (isa<ConstantSDNode>(BasePtr)) {
7449 std::swap(BasePtr, Offset);
7450 Swapped = true;
7451 }
7452
Evan Cheng044a0a82007-05-03 23:52:19 +00007453 // Don't create a indexed load / store with zero offset.
7454 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007455 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007456 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007457
Chris Lattnera0a80032006-11-11 01:00:15 +00007458 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007459 // 1) The new base ptr is a frame index.
7460 // 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 +00007461 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007462 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007463 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007464 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007465
Chris Lattnera0a80032006-11-11 01:00:15 +00007466 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7467 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007468 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007469 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007470
Chris Lattnera0a80032006-11-11 01:00:15 +00007471 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007472 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007473 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007474 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007475 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007476 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007477
Hal Finkel25819052013-02-08 21:35:47 +00007478 // If the offset is a constant, there may be other adds of constants that
7479 // can be folded with this one. We should do this to avoid having to keep
7480 // a copy of the original base pointer.
7481 SmallVector<SDNode *, 16> OtherUses;
7482 if (isa<ConstantSDNode>(Offset))
7483 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7484 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7485 SDNode *Use = *I;
7486 if (Use == Ptr.getNode())
7487 continue;
7488
7489 if (Use->isPredecessorOf(N))
7490 continue;
7491
7492 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7493 OtherUses.clear();
7494 break;
7495 }
7496
7497 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7498 if (Op1.getNode() == BasePtr.getNode())
7499 std::swap(Op0, Op1);
7500 assert(Op0.getNode() == BasePtr.getNode() &&
7501 "Use of ADD/SUB but not an operand");
7502
7503 if (!isa<ConstantSDNode>(Op1)) {
7504 OtherUses.clear();
7505 break;
7506 }
7507
7508 // FIXME: In some cases, we can be smarter about this.
7509 if (Op1.getValueType() != Offset.getValueType()) {
7510 OtherUses.clear();
7511 break;
7512 }
7513
7514 OtherUses.push_back(Use);
7515 }
7516
7517 if (Swapped)
7518 std::swap(BasePtr, Offset);
7519
Evan Chenga4d187b2007-05-24 02:35:39 +00007520 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007521 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007522
7523 // Caches for hasPredecessorHelper
7524 SmallPtrSet<const SDNode *, 32> Visited;
7525 SmallVector<const SDNode *, 16> Worklist;
7526
Gabor Greiff304a7a2008-08-28 21:40:38 +00007527 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7528 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007529 SDNode *Use = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007530 if (Use == N)
7531 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007532 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007533 return false;
7534
Evan Chengfa832632012-01-13 01:37:24 +00007535 // If Ptr may be folded in addressing mode of other use, then it's
7536 // not profitable to do this transformation.
7537 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007538 RealUse = true;
7539 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007540
Chris Lattnereabc15c2006-11-11 00:56:29 +00007541 if (!RealUse)
7542 return false;
7543
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007544 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007545 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007546 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007547 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007548 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007549 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007550 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007551 ++PreIndexedNodes;
7552 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007553 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007554 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007555 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007556 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007557 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007558 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007559 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007560 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7561 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007562 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007563 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007564 }
7565
Chris Lattnereabc15c2006-11-11 00:56:29 +00007566 // Finally, since the node is now dead, remove it from the graph.
7567 DAG.DeleteNode(N);
7568
Hal Finkel25819052013-02-08 21:35:47 +00007569 if (Swapped)
7570 std::swap(BasePtr, Offset);
7571
7572 // Replace other uses of BasePtr that can be updated to use Ptr
7573 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7574 unsigned OffsetIdx = 1;
7575 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7576 OffsetIdx = 0;
7577 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7578 BasePtr.getNode() && "Expected BasePtr operand");
7579
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007580 // We need to replace ptr0 in the following expression:
7581 // x0 * offset0 + y0 * ptr0 = t0
7582 // knowing that
7583 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007584 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007585 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7586 // indexed load/store and the expresion that needs to be re-written.
7587 //
7588 // Therefore, we have:
7589 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007590
7591 ConstantSDNode *CN =
7592 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007593 int X0, X1, Y0, Y1;
7594 APInt Offset0 = CN->getAPIntValue();
7595 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007596
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007597 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7598 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7599 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7600 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007601
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007602 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7603
7604 APInt CNV = Offset0;
7605 if (X0 < 0) CNV = -CNV;
7606 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7607 else CNV = CNV - Offset1;
7608
7609 // We can now generate the new expression.
7610 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7611 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7612
7613 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007614 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007615 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7616 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7617 removeFromWorkList(OtherUses[i]);
7618 DAG.DeleteNode(OtherUses[i]);
7619 }
7620
Chris Lattnereabc15c2006-11-11 00:56:29 +00007621 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007622 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007623 removeFromWorkList(Ptr.getNode());
7624 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007625
7626 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007627}
7628
Duncan Sands075293f2008-06-15 20:12:31 +00007629/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007630/// add / sub of the base pointer node into a post-indexed load / store.
7631/// The transformation folded the add / subtract into the new indexed
7632/// load / store effectively and all of its uses are redirected to the
7633/// new load / store.
7634bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007635 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007636 return false;
7637
7638 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007639 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007640 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007641 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007642 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007643 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007644 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007645 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7646 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7647 return false;
7648 Ptr = LD->getBasePtr();
7649 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007650 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007651 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007652 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007653 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7654 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7655 return false;
7656 Ptr = ST->getBasePtr();
7657 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007658 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007659 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007660 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007661
Gabor Greiff304a7a2008-08-28 21:40:38 +00007662 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007663 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007664
Gabor Greiff304a7a2008-08-28 21:40:38 +00007665 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7666 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007667 SDNode *Op = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007668 if (Op == N ||
7669 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7670 continue;
7671
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007672 SDValue BasePtr;
7673 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007674 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7675 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007676 // Don't create a indexed load / store with zero offset.
7677 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007678 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007679 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007680
Chris Lattnereabc15c2006-11-11 00:56:29 +00007681 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007682 // 1) All uses are load / store ops that use it as base ptr (and
7683 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007684 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7685 // nor a successor of N. Otherwise, if Op is folded that would
7686 // create a cycle.
7687
Evan Chengcfc05132009-05-06 18:25:01 +00007688 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7689 continue;
7690
Chris Lattnereabc15c2006-11-11 00:56:29 +00007691 // Check for #1.
7692 bool TryNext = false;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007693 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7694 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007695 SDNode *Use = *II;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007696 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007697 continue;
7698
Chris Lattnereabc15c2006-11-11 00:56:29 +00007699 // If all the uses are load / store addresses, then don't do the
7700 // transformation.
7701 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7702 bool RealUse = false;
7703 for (SDNode::use_iterator III = Use->use_begin(),
7704 EEE = Use->use_end(); III != EEE; ++III) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007705 SDNode *UseUse = *III;
Stephen Lincfe7f352013-07-08 00:37:03 +00007706 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007707 RealUse = true;
7708 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007709
Chris Lattnereabc15c2006-11-11 00:56:29 +00007710 if (!RealUse) {
7711 TryNext = true;
7712 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007713 }
7714 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007715 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007716
Chris Lattnereabc15c2006-11-11 00:56:29 +00007717 if (TryNext)
7718 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007719
Chris Lattnereabc15c2006-11-11 00:56:29 +00007720 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007721 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007722 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007723 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007724 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007725 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007726 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007727 ++PostIndexedNodes;
7728 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007729 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007730 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007731 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007732 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007733 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007734 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007735 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007736 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7737 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007738 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007739 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007740 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007741
Chris Lattnereabc15c2006-11-11 00:56:29 +00007742 // Finally, since the node is now dead, remove it from the graph.
7743 DAG.DeleteNode(N);
7744
7745 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007746 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007747 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007748 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007749 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007750 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007751 }
7752 }
7753 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007754
Chris Lattnerffad2162006-11-11 00:39:41 +00007755 return false;
7756}
7757
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007758SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007759 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007760 SDValue Chain = LD->getChain();
7761 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007762
Evan Chenga684cd22007-05-01 00:38:21 +00007763 // If load is not volatile and there are no uses of the loaded value (and
7764 // the updated indexed value in case of indexed loads), change uses of the
7765 // chain value into uses of the chain input (i.e. delete the dead load).
7766 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007767 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007768 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007769 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007770 // It's not safe to use the two value CombineTo variant here. e.g.
7771 // v1, chain2 = load chain1, loc
7772 // v2, chain3 = load chain2, loc
7773 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007774 // Now we replace use of chain2 with chain1. This makes the second load
7775 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007776 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007777 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007778 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007779 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007780 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007781 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007782 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007783
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007784 if (N->use_empty()) {
7785 removeFromWorkList(N);
7786 DAG.DeleteNode(N);
7787 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007788
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007789 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007790 }
Evan Chengb68343c2007-05-01 08:53:39 +00007791 } else {
7792 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007793 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper0515cd42012-01-07 18:31:09 +00007794 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007795 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007796 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007797 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007798 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007799 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007800 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007801 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007802 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007803 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007804 DAG.getUNDEF(N->getValueType(1)));
7805 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007806 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007807 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007808 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007809 }
Evan Chenga684cd22007-05-01 00:38:21 +00007810 }
7811 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007812
Chris Lattnere260ed82005-10-10 22:04:48 +00007813 // If this load is directly stored, replace the load value with the stored
7814 // value.
7815 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007816 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007817 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007818 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007819 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7820 if (PrevST->getBasePtr() == Ptr &&
7821 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007822 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007823 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007825
Evan Cheng43cd9e32010-04-01 06:04:33 +00007826 // Try to infer better alignment information than the load already has.
7827 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007828 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007829 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7830 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007831 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007832 LD->getValueType(0),
7833 Chain, Ptr, LD->getPointerInfo(),
7834 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007835 LD->isVolatile(), LD->isNonTemporal(), Align,
7836 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007837 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7838 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007839 }
7840 }
7841
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007842 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7843 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00007844#ifndef NDEBUG
7845 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7846 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7847 UseAA = false;
7848#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00007849 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007850 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007851 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007852
Jim Laskey708d0db2006-10-04 16:53:27 +00007853 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007854 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007855 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007856
Jim Laskeyd07be232006-09-25 16:29:54 +00007857 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007858 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007859 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007860 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007861 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007862 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007863 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007864 BetterChain, Ptr, LD->getMemoryVT(),
7865 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007866 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007867
Jim Laskey708d0db2006-10-04 16:53:27 +00007868 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007869 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007870 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007871
Nate Begeman879d8f12009-09-15 00:18:30 +00007872 // Make sure the new and old chains are cleaned up.
7873 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007874
Jim Laskeydcf983c2006-10-13 23:32:28 +00007875 // Replace uses with load result and token factor. Don't add users
7876 // to work list.
7877 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00007878 }
7879 }
7880
Evan Cheng357017f2006-11-03 03:06:21 +00007881 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00007882 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007883 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00007884
Quentin Colombetde0e0622013-10-11 18:29:42 +00007885 // Try to slice up N to more direct loads if the slices are mapped to
7886 // different register banks or pairing can take place.
7887 if (SliceUpLoad(N))
7888 return SDValue(N, 0);
7889
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007890 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00007891}
7892
Quentin Colombetde0e0622013-10-11 18:29:42 +00007893namespace {
7894/// \brief Helper structure used to slice a load in smaller loads.
7895/// Basically a slice is obtained from the following sequence:
7896/// Origin = load Ty1, Base
7897/// Shift = srl Ty1 Origin, CstTy Amount
7898/// Inst = trunc Shift to Ty2
7899///
7900/// Then, it will be rewriten into:
7901/// Slice = load SliceTy, Base + SliceOffset
7902/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7903///
7904/// SliceTy is deduced from the number of bits that are actually used to
7905/// build Inst.
7906struct LoadedSlice {
7907 /// \brief Helper structure used to compute the cost of a slice.
7908 struct Cost {
7909 /// Are we optimizing for code size.
7910 bool ForCodeSize;
7911 /// Various cost.
7912 unsigned Loads;
7913 unsigned Truncates;
7914 unsigned CrossRegisterBanksCopies;
7915 unsigned ZExts;
7916 unsigned Shift;
7917
7918 Cost(bool ForCodeSize = false)
7919 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7920 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7921
7922 /// \brief Get the cost of one isolated slice.
7923 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7924 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7925 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7926 EVT TruncType = LS.Inst->getValueType(0);
7927 EVT LoadedType = LS.getLoadedType();
7928 if (TruncType != LoadedType &&
7929 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7930 ZExts = 1;
7931 }
7932
7933 /// \brief Account for slicing gain in the current cost.
7934 /// Slicing provide a few gains like removing a shift or a
7935 /// truncate. This method allows to grow the cost of the original
7936 /// load with the gain from this slice.
7937 void addSliceGain(const LoadedSlice &LS) {
7938 // Each slice saves a truncate.
7939 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7940 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7941 LS.Inst->getOperand(0).getValueType()))
7942 ++Truncates;
7943 // If there is a shift amount, this slice gets rid of it.
7944 if (LS.Shift)
7945 ++Shift;
7946 // If this slice can merge a cross register bank copy, account for it.
7947 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7948 ++CrossRegisterBanksCopies;
7949 }
7950
7951 Cost &operator+=(const Cost &RHS) {
7952 Loads += RHS.Loads;
7953 Truncates += RHS.Truncates;
7954 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7955 ZExts += RHS.ZExts;
7956 Shift += RHS.Shift;
7957 return *this;
7958 }
7959
7960 bool operator==(const Cost &RHS) const {
7961 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7962 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7963 ZExts == RHS.ZExts && Shift == RHS.Shift;
7964 }
7965
7966 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7967
7968 bool operator<(const Cost &RHS) const {
7969 // Assume cross register banks copies are as expensive as loads.
7970 // FIXME: Do we want some more target hooks?
7971 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7972 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7973 // Unless we are optimizing for code size, consider the
7974 // expensive operation first.
7975 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7976 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7977 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7978 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7979 }
7980
7981 bool operator>(const Cost &RHS) const { return RHS < *this; }
7982
7983 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7984
7985 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7986 };
7987 // The last instruction that represent the slice. This should be a
7988 // truncate instruction.
7989 SDNode *Inst;
7990 // The original load instruction.
7991 LoadSDNode *Origin;
7992 // The right shift amount in bits from the original load.
7993 unsigned Shift;
7994 // The DAG from which Origin came from.
7995 // This is used to get some contextual information about legal types, etc.
7996 SelectionDAG *DAG;
7997
7998 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7999 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8000 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8001
8002 LoadedSlice(const LoadedSlice &LS)
8003 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8004
8005 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8006 /// \return Result is \p BitWidth and has used bits set to 1 and
8007 /// not used bits set to 0.
8008 APInt getUsedBits() const {
8009 // Reproduce the trunc(lshr) sequence:
8010 // - Start from the truncated value.
8011 // - Zero extend to the desired bit width.
8012 // - Shift left.
8013 assert(Origin && "No original load to compare against.");
8014 unsigned BitWidth = Origin->getValueSizeInBits(0);
8015 assert(Inst && "This slice is not bound to an instruction");
8016 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8017 "Extracted slice is bigger than the whole type!");
8018 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8019 UsedBits.setAllBits();
8020 UsedBits = UsedBits.zext(BitWidth);
8021 UsedBits <<= Shift;
8022 return UsedBits;
8023 }
8024
8025 /// \brief Get the size of the slice to be loaded in bytes.
8026 unsigned getLoadedSize() const {
8027 unsigned SliceSize = getUsedBits().countPopulation();
8028 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8029 return SliceSize / 8;
8030 }
8031
8032 /// \brief Get the type that will be loaded for this slice.
8033 /// Note: This may not be the final type for the slice.
8034 EVT getLoadedType() const {
8035 assert(DAG && "Missing context");
8036 LLVMContext &Ctxt = *DAG->getContext();
8037 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8038 }
8039
8040 /// \brief Get the alignment of the load used for this slice.
8041 unsigned getAlignment() const {
8042 unsigned Alignment = Origin->getAlignment();
8043 unsigned Offset = getOffsetFromBase();
8044 if (Offset != 0)
8045 Alignment = MinAlign(Alignment, Alignment + Offset);
8046 return Alignment;
8047 }
8048
8049 /// \brief Check if this slice can be rewritten with legal operations.
8050 bool isLegal() const {
8051 // An invalid slice is not legal.
8052 if (!Origin || !Inst || !DAG)
8053 return false;
8054
8055 // Offsets are for indexed load only, we do not handle that.
8056 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8057 return false;
8058
8059 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8060
8061 // Check that the type is legal.
8062 EVT SliceType = getLoadedType();
8063 if (!TLI.isTypeLegal(SliceType))
8064 return false;
8065
8066 // Check that the load is legal for this type.
8067 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8068 return false;
8069
8070 // Check that the offset can be computed.
8071 // 1. Check its type.
8072 EVT PtrType = Origin->getBasePtr().getValueType();
8073 if (PtrType == MVT::Untyped || PtrType.isExtended())
8074 return false;
8075
8076 // 2. Check that it fits in the immediate.
8077 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8078 return false;
8079
8080 // 3. Check that the computation is legal.
8081 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8082 return false;
8083
8084 // Check that the zext is legal if it needs one.
8085 EVT TruncateType = Inst->getValueType(0);
8086 if (TruncateType != SliceType &&
8087 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8088 return false;
8089
8090 return true;
8091 }
8092
8093 /// \brief Get the offset in bytes of this slice in the original chunk of
8094 /// bits.
8095 /// \pre DAG != NULL.
8096 uint64_t getOffsetFromBase() const {
8097 assert(DAG && "Missing context.");
8098 bool IsBigEndian =
8099 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8100 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8101 uint64_t Offset = Shift / 8;
8102 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8103 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8104 "The size of the original loaded type is not a multiple of a"
8105 " byte.");
8106 // If Offset is bigger than TySizeInBytes, it means we are loading all
8107 // zeros. This should have been optimized before in the process.
8108 assert(TySizeInBytes > Offset &&
8109 "Invalid shift amount for given loaded size");
8110 if (IsBigEndian)
8111 Offset = TySizeInBytes - Offset - getLoadedSize();
8112 return Offset;
8113 }
8114
8115 /// \brief Generate the sequence of instructions to load the slice
8116 /// represented by this object and redirect the uses of this slice to
8117 /// this new sequence of instructions.
8118 /// \pre this->Inst && this->Origin are valid Instructions and this
8119 /// object passed the legal check: LoadedSlice::isLegal returned true.
8120 /// \return The last instruction of the sequence used to load the slice.
8121 SDValue loadSlice() const {
8122 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8123 const SDValue &OldBaseAddr = Origin->getBasePtr();
8124 SDValue BaseAddr = OldBaseAddr;
8125 // Get the offset in that chunk of bytes w.r.t. the endianess.
8126 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8127 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8128 if (Offset) {
8129 // BaseAddr = BaseAddr + Offset.
8130 EVT ArithType = BaseAddr.getValueType();
8131 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8132 DAG->getConstant(Offset, ArithType));
8133 }
8134
8135 // Create the type of the loaded slice according to its size.
8136 EVT SliceType = getLoadedType();
8137
8138 // Create the load for the slice.
8139 SDValue LastInst = DAG->getLoad(
8140 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8141 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8142 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8143 // If the final type is not the same as the loaded type, this means that
8144 // we have to pad with zero. Create a zero extend for that.
8145 EVT FinalType = Inst->getValueType(0);
8146 if (SliceType != FinalType)
8147 LastInst =
8148 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8149 return LastInst;
8150 }
8151
8152 /// \brief Check if this slice can be merged with an expensive cross register
8153 /// bank copy. E.g.,
8154 /// i = load i32
8155 /// f = bitcast i32 i to float
8156 bool canMergeExpensiveCrossRegisterBankCopy() const {
8157 if (!Inst || !Inst->hasOneUse())
8158 return false;
8159 SDNode *Use = *Inst->use_begin();
8160 if (Use->getOpcode() != ISD::BITCAST)
8161 return false;
8162 assert(DAG && "Missing context");
8163 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8164 EVT ResVT = Use->getValueType(0);
8165 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8166 const TargetRegisterClass *ArgRC =
8167 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8168 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8169 return false;
8170
8171 // At this point, we know that we perform a cross-register-bank copy.
8172 // Check if it is expensive.
8173 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8174 // Assume bitcasts are cheap, unless both register classes do not
8175 // explicitly share a common sub class.
8176 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8177 return false;
8178
8179 // Check if it will be merged with the load.
8180 // 1. Check the alignment constraint.
8181 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8182 ResVT.getTypeForEVT(*DAG->getContext()));
8183
8184 if (RequiredAlignment > getAlignment())
8185 return false;
8186
8187 // 2. Check that the load is a legal operation for that type.
8188 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8189 return false;
8190
8191 // 3. Check that we do not have a zext in the way.
8192 if (Inst->getValueType(0) != getLoadedType())
8193 return false;
8194
8195 return true;
8196 }
8197};
8198}
8199
Quentin Colombetde0e0622013-10-11 18:29:42 +00008200/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8201/// \p UsedBits looks like 0..0 1..1 0..0.
8202static bool areUsedBitsDense(const APInt &UsedBits) {
8203 // If all the bits are one, this is dense!
8204 if (UsedBits.isAllOnesValue())
8205 return true;
8206
8207 // Get rid of the unused bits on the right.
8208 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8209 // Get rid of the unused bits on the left.
8210 if (NarrowedUsedBits.countLeadingZeros())
8211 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8212 // Check that the chunk of bits is completely used.
8213 return NarrowedUsedBits.isAllOnesValue();
8214}
8215
8216/// \brief Check whether or not \p First and \p Second are next to each other
8217/// in memory. This means that there is no hole between the bits loaded
8218/// by \p First and the bits loaded by \p Second.
8219static bool areSlicesNextToEachOther(const LoadedSlice &First,
8220 const LoadedSlice &Second) {
8221 assert(First.Origin == Second.Origin && First.Origin &&
8222 "Unable to match different memory origins.");
8223 APInt UsedBits = First.getUsedBits();
8224 assert((UsedBits & Second.getUsedBits()) == 0 &&
8225 "Slices are not supposed to overlap.");
8226 UsedBits |= Second.getUsedBits();
8227 return areUsedBitsDense(UsedBits);
8228}
8229
8230/// \brief Adjust the \p GlobalLSCost according to the target
8231/// paring capabilities and the layout of the slices.
8232/// \pre \p GlobalLSCost should account for at least as many loads as
8233/// there is in the slices in \p LoadedSlices.
8234static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8235 LoadedSlice::Cost &GlobalLSCost) {
8236 unsigned NumberOfSlices = LoadedSlices.size();
8237 // If there is less than 2 elements, no pairing is possible.
8238 if (NumberOfSlices < 2)
8239 return;
8240
8241 // Sort the slices so that elements that are likely to be next to each
8242 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008243 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8244 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8245 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8246 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8247 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008248 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8249 // First (resp. Second) is the first (resp. Second) potentially candidate
8250 // to be placed in a paired load.
8251 const LoadedSlice *First = NULL;
8252 const LoadedSlice *Second = NULL;
8253 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8254 // Set the beginning of the pair.
8255 First = Second) {
8256
8257 Second = &LoadedSlices[CurrSlice];
8258
8259 // If First is NULL, it means we start a new pair.
8260 // Get to the next slice.
8261 if (!First)
8262 continue;
8263
8264 EVT LoadedType = First->getLoadedType();
8265
8266 // If the types of the slices are different, we cannot pair them.
8267 if (LoadedType != Second->getLoadedType())
8268 continue;
8269
8270 // Check if the target supplies paired loads for this type.
8271 unsigned RequiredAlignment = 0;
8272 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8273 // move to the next pair, this type is hopeless.
8274 Second = NULL;
8275 continue;
8276 }
8277 // Check if we meet the alignment requirement.
8278 if (RequiredAlignment > First->getAlignment())
8279 continue;
8280
8281 // Check that both loads are next to each other in memory.
8282 if (!areSlicesNextToEachOther(*First, *Second))
8283 continue;
8284
8285 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8286 --GlobalLSCost.Loads;
8287 // Move to the next pair.
8288 Second = NULL;
8289 }
8290}
8291
8292/// \brief Check the profitability of all involved LoadedSlice.
8293/// Currently, it is considered profitable if there is exactly two
8294/// involved slices (1) which are (2) next to each other in memory, and
8295/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8296///
8297/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8298/// the elements themselves.
8299///
8300/// FIXME: When the cost model will be mature enough, we can relax
8301/// constraints (1) and (2).
8302static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8303 const APInt &UsedBits, bool ForCodeSize) {
8304 unsigned NumberOfSlices = LoadedSlices.size();
8305 if (StressLoadSlicing)
8306 return NumberOfSlices > 1;
8307
8308 // Check (1).
8309 if (NumberOfSlices != 2)
8310 return false;
8311
8312 // Check (2).
8313 if (!areUsedBitsDense(UsedBits))
8314 return false;
8315
8316 // Check (3).
8317 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8318 // The original code has one big load.
8319 OrigCost.Loads = 1;
8320 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8321 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8322 // Accumulate the cost of all the slices.
8323 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8324 GlobalSlicingCost += SliceCost;
8325
8326 // Account as cost in the original configuration the gain obtained
8327 // with the current slices.
8328 OrigCost.addSliceGain(LS);
8329 }
8330
8331 // If the target supports paired load, adjust the cost accordingly.
8332 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8333 return OrigCost > GlobalSlicingCost;
8334}
8335
8336/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8337/// operations, split it in the various pieces being extracted.
8338///
8339/// This sort of thing is introduced by SROA.
8340/// This slicing takes care not to insert overlapping loads.
8341/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8342bool DAGCombiner::SliceUpLoad(SDNode *N) {
8343 if (Level < AfterLegalizeDAG)
8344 return false;
8345
8346 LoadSDNode *LD = cast<LoadSDNode>(N);
8347 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8348 !LD->getValueType(0).isInteger())
8349 return false;
8350
8351 // Keep track of already used bits to detect overlapping values.
8352 // In that case, we will just abort the transformation.
8353 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8354
8355 SmallVector<LoadedSlice, 4> LoadedSlices;
8356
8357 // Check if this load is used as several smaller chunks of bits.
8358 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8359 // of computation for each trunc.
8360 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8361 UI != UIEnd; ++UI) {
8362 // Skip the uses of the chain.
8363 if (UI.getUse().getResNo() != 0)
8364 continue;
8365
8366 SDNode *User = *UI;
8367 unsigned Shift = 0;
8368
8369 // Check if this is a trunc(lshr).
8370 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8371 isa<ConstantSDNode>(User->getOperand(1))) {
8372 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8373 User = *User->use_begin();
8374 }
8375
8376 // At this point, User is a Truncate, iff we encountered, trunc or
8377 // trunc(lshr).
8378 if (User->getOpcode() != ISD::TRUNCATE)
8379 return false;
8380
8381 // The width of the type must be a power of 2 and greater than 8-bits.
8382 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008383 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008384 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008385 unsigned Width = User->getValueSizeInBits(0);
8386 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8387 return 0;
8388
8389 // Build the slice for this chain of computations.
8390 LoadedSlice LS(User, LD, Shift, &DAG);
8391 APInt CurrentUsedBits = LS.getUsedBits();
8392
8393 // Check if this slice overlaps with another.
8394 if ((CurrentUsedBits & UsedBits) != 0)
8395 return false;
8396 // Update the bits used globally.
8397 UsedBits |= CurrentUsedBits;
8398
8399 // Check if the new slice would be legal.
8400 if (!LS.isLegal())
8401 return false;
8402
8403 // Record the slice.
8404 LoadedSlices.push_back(LS);
8405 }
8406
8407 // Abort slicing if it does not seem to be profitable.
8408 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8409 return false;
8410
8411 ++SlicedLoads;
8412
8413 // Rewrite each chain to use an independent load.
8414 // By construction, each chain can be represented by a unique load.
8415
8416 // Prepare the argument for the new token factor for all the slices.
8417 SmallVector<SDValue, 8> ArgChains;
8418 for (SmallVectorImpl<LoadedSlice>::const_iterator
8419 LSIt = LoadedSlices.begin(),
8420 LSItEnd = LoadedSlices.end();
8421 LSIt != LSItEnd; ++LSIt) {
8422 SDValue SliceInst = LSIt->loadSlice();
8423 CombineTo(LSIt->Inst, SliceInst, true);
8424 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8425 SliceInst = SliceInst.getOperand(0);
8426 assert(SliceInst->getOpcode() == ISD::LOAD &&
8427 "It takes more than a zext to get to the loaded slice!!");
8428 ArgChains.push_back(SliceInst.getValue(1));
8429 }
8430
8431 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8432 &ArgChains[0], ArgChains.size());
8433 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8434 return true;
8435}
8436
Chris Lattner4041ab62010-04-15 04:48:01 +00008437/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8438/// load is having specific bytes cleared out. If so, return the byte size
8439/// being masked out and the shift amount.
8440static std::pair<unsigned, unsigned>
8441CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8442 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008443
Chris Lattner4041ab62010-04-15 04:48:01 +00008444 // Check for the structure we're looking for.
8445 if (V->getOpcode() != ISD::AND ||
8446 !isa<ConstantSDNode>(V->getOperand(1)) ||
8447 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8448 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008449
Chris Lattner3245afd2010-04-15 06:10:49 +00008450 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008451 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008452 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008453
Chris Lattner3245afd2010-04-15 06:10:49 +00008454 // The store should be chained directly to the load or be an operand of a
8455 // tokenfactor.
8456 if (LD == Chain.getNode())
8457 ; // ok.
8458 else if (Chain->getOpcode() != ISD::TokenFactor)
8459 return Result; // Fail.
8460 else {
8461 bool isOk = false;
8462 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8463 if (Chain->getOperand(i).getNode() == LD) {
8464 isOk = true;
8465 break;
8466 }
8467 if (!isOk) return Result;
8468 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008469
Chris Lattner4041ab62010-04-15 04:48:01 +00008470 // This only handles simple types.
8471 if (V.getValueType() != MVT::i16 &&
8472 V.getValueType() != MVT::i32 &&
8473 V.getValueType() != MVT::i64)
8474 return Result;
8475
8476 // Check the constant mask. Invert it so that the bits being masked out are
8477 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8478 // follow the sign bit for uniformity.
8479 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008480 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008481 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008482 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008483 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8484 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008485
Chris Lattner4041ab62010-04-15 04:48:01 +00008486 // See if we have a continuous run of bits. If so, we have 0*1+0*
8487 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8488 return Result;
8489
8490 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8491 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8492 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008493
Chris Lattner4041ab62010-04-15 04:48:01 +00008494 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8495 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008496 case 1:
8497 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008498 case 4: break;
8499 default: return Result; // All one mask, or 5-byte mask.
8500 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008501
Chris Lattner4041ab62010-04-15 04:48:01 +00008502 // Verify that the first bit starts at a multiple of mask so that the access
8503 // is aligned the same as the access width.
8504 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008505
Chris Lattner4041ab62010-04-15 04:48:01 +00008506 Result.first = MaskedBytes;
8507 Result.second = NotMaskTZ/8;
8508 return Result;
8509}
8510
8511
8512/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8513/// provides a value as specified by MaskInfo. If so, replace the specified
8514/// store with a narrower store of truncated IVal.
8515static SDNode *
8516ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8517 SDValue IVal, StoreSDNode *St,
8518 DAGCombiner *DC) {
8519 unsigned NumBytes = MaskInfo.first;
8520 unsigned ByteShift = MaskInfo.second;
8521 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008522
Chris Lattner4041ab62010-04-15 04:48:01 +00008523 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8524 // that uses this. If not, this is not a replacement.
8525 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8526 ByteShift*8, (ByteShift+NumBytes)*8);
8527 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008528
Chris Lattner4041ab62010-04-15 04:48:01 +00008529 // Check that it is legal on the target to do this. It is legal if the new
8530 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8531 // legalization.
8532 MVT VT = MVT::getIntegerVT(NumBytes*8);
8533 if (!DC->isTypeLegal(VT))
8534 return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008535
Chris Lattner4041ab62010-04-15 04:48:01 +00008536 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8537 // shifted by ByteShift and truncated down to NumBytes.
8538 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008539 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008540 DAG.getConstant(ByteShift*8,
8541 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008542
8543 // Figure out the offset for the store and the alignment of the access.
8544 unsigned StOffset;
8545 unsigned NewAlign = St->getAlignment();
8546
8547 if (DAG.getTargetLoweringInfo().isLittleEndian())
8548 StOffset = ByteShift;
8549 else
8550 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008551
Chris Lattner4041ab62010-04-15 04:48:01 +00008552 SDValue Ptr = St->getBasePtr();
8553 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008554 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008555 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8556 NewAlign = MinAlign(NewAlign, StOffset);
8557 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008558
Chris Lattner4041ab62010-04-15 04:48:01 +00008559 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008560 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008561
Chris Lattner4041ab62010-04-15 04:48:01 +00008562 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008563 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008564 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008565 false, false, NewAlign).getNode();
8566}
8567
Evan Chenga9cda8a2009-05-28 00:35:15 +00008568
8569/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8570/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8571/// of the loaded bits, try narrowing the load and store if it would end up
8572/// being a win for performance or code size.
8573SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8574 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008575 if (ST->isVolatile())
8576 return SDValue();
8577
Evan Chenga9cda8a2009-05-28 00:35:15 +00008578 SDValue Chain = ST->getChain();
8579 SDValue Value = ST->getValue();
8580 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008581 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008582
8583 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008584 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008585
8586 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008587
Chris Lattner4041ab62010-04-15 04:48:01 +00008588 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8589 // is a byte mask indicating a consecutive number of bytes, check to see if
8590 // Y is known to provide just those bytes. If so, we try to replace the
8591 // load + replace + store sequence with a single (narrower) store, which makes
8592 // the load dead.
8593 if (Opc == ISD::OR) {
8594 std::pair<unsigned, unsigned> MaskedLoad;
8595 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8596 if (MaskedLoad.first)
8597 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8598 Value.getOperand(1), ST,this))
8599 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008600
Chris Lattner4041ab62010-04-15 04:48:01 +00008601 // Or is commutative, so try swapping X and Y.
8602 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8603 if (MaskedLoad.first)
8604 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8605 Value.getOperand(0), ST,this))
8606 return SDValue(NewST, 0);
8607 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008608
Evan Chenga9cda8a2009-05-28 00:35:15 +00008609 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8610 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008611 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008612
8613 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008614 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8615 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008616 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008617 if (LD->getBasePtr() != Ptr ||
8618 LD->getPointerInfo().getAddrSpace() !=
8619 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008620 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008621
8622 // Find the type to narrow it the load / op / store to.
8623 SDValue N1 = Value.getOperand(1);
8624 unsigned BitWidth = N1.getValueSizeInBits();
8625 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8626 if (Opc == ISD::AND)
8627 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008628 if (Imm == 0 || Imm.isAllOnesValue())
8629 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008630 unsigned ShAmt = Imm.countTrailingZeros();
8631 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8632 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008633 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008634 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008635 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008636 TLI.isNarrowingProfitable(VT, NewVT))) {
8637 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008638 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008639 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008640 if (NewBW >= BitWidth)
8641 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008642
8643 // If the lsb changed does not start at the type bitwidth boundary,
8644 // start at the previous one.
8645 if (ShAmt % NewBW)
8646 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008647 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8648 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008649 if ((Imm & Mask) == Imm) {
8650 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8651 if (Opc == ISD::AND)
8652 NewImm ^= APInt::getAllOnesValue(NewBW);
8653 uint64_t PtrOff = ShAmt / 8;
8654 // For big endian targets, we need to adjust the offset to the pointer to
8655 // load the correct bytes.
8656 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008657 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008658
8659 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008660 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008661 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008662 return SDValue();
8663
Andrew Trickef9de2a2013-05-25 02:42:55 +00008664 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008665 Ptr.getValueType(), Ptr,
8666 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008667 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008668 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008669 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008670 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008671 LD->isInvariant(), NewAlign,
8672 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008673 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008674 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008675 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008676 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008677 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008678 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008679
8680 AddToWorkList(NewPtr.getNode());
8681 AddToWorkList(NewLD.getNode());
8682 AddToWorkList(NewVal.getNode());
8683 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008684 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008685 ++OpsNarrowed;
8686 return NewST;
8687 }
8688 }
8689
Evan Cheng6673ff02009-05-28 18:41:02 +00008690 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008691}
8692
Evan Chengd42641c2011-02-02 01:06:55 +00008693/// TransformFPLoadStorePair - For a given floating point load / store pair,
8694/// if the load value isn't used by any other operations, then consider
8695/// transforming the pair to integer load / store operations if the target
8696/// deems the transformation profitable.
8697SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8698 StoreSDNode *ST = cast<StoreSDNode>(N);
8699 SDValue Chain = ST->getChain();
8700 SDValue Value = ST->getValue();
8701 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8702 Value.hasOneUse() &&
8703 Chain == SDValue(Value.getNode(), 1)) {
8704 LoadSDNode *LD = cast<LoadSDNode>(Value);
8705 EVT VT = LD->getMemoryVT();
8706 if (!VT.isFloatingPoint() ||
8707 VT != ST->getMemoryVT() ||
8708 LD->isNonTemporal() ||
8709 ST->isNonTemporal() ||
8710 LD->getPointerInfo().getAddrSpace() != 0 ||
8711 ST->getPointerInfo().getAddrSpace() != 0)
8712 return SDValue();
8713
8714 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8715 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8716 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8717 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8718 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8719 return SDValue();
8720
8721 unsigned LDAlign = LD->getAlignment();
8722 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008723 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008724 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008725 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8726 return SDValue();
8727
Andrew Trickef9de2a2013-05-25 02:42:55 +00008728 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008729 LD->getChain(), LD->getBasePtr(),
8730 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008731 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008732
Andrew Trickef9de2a2013-05-25 02:42:55 +00008733 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008734 NewLD, ST->getBasePtr(),
8735 ST->getPointerInfo(),
8736 false, false, STAlign);
8737
8738 AddToWorkList(NewLD.getNode());
8739 AddToWorkList(NewST.getNode());
8740 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008741 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008742 ++LdStFP2Int;
8743 return NewST;
8744 }
8745
8746 return SDValue();
8747}
8748
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008749/// Helper struct to parse and store a memory address as base + index + offset.
8750/// We ignore sign extensions when it is safe to do so.
8751/// The following two expressions are not equivalent. To differentiate we need
8752/// to store whether there was a sign extension involved in the index
8753/// computation.
8754/// (load (i64 add (i64 copyfromreg %c)
8755/// (i64 signextend (add (i8 load %index)
8756/// (i8 1))))
8757/// vs
8758///
8759/// (load (i64 add (i64 copyfromreg %c)
8760/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8761/// (i32 1)))))
8762struct BaseIndexOffset {
8763 SDValue Base;
8764 SDValue Index;
8765 int64_t Offset;
8766 bool IsIndexSignExt;
8767
8768 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8769
8770 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8771 bool IsIndexSignExt) :
8772 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8773
8774 bool equalBaseIndex(const BaseIndexOffset &Other) {
8775 return Other.Base == Base && Other.Index == Index &&
8776 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008777 }
8778
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008779 /// Parses tree in Ptr for base, index, offset addresses.
8780 static BaseIndexOffset match(SDValue Ptr) {
8781 bool IsIndexSignExt = false;
8782
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008783 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8784 // instruction, then it could be just the BASE or everything else we don't
8785 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008786 if (Ptr->getOpcode() != ISD::ADD)
8787 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8788
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008789 // We know that we have at least an ADD instruction. Try to pattern match
8790 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008791 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8792 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8793 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8794 IsIndexSignExt);
8795 }
8796
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008797 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008798 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008799 // (i64 add (i64 %array_ptr)
8800 // (i64 mul (i64 %induction_var)
8801 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008802 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008803 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008804
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008805 // Look at Base + Index + Offset cases.
8806 SDValue Base = Ptr->getOperand(0);
8807 SDValue IndexOffset = Ptr->getOperand(1);
8808
8809 // Skip signextends.
8810 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8811 IndexOffset = IndexOffset->getOperand(0);
8812 IsIndexSignExt = true;
8813 }
8814
8815 // Either the case of Base + Index (no offset) or something else.
8816 if (IndexOffset->getOpcode() != ISD::ADD)
8817 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8818
8819 // Now we have the case of Base + Index + offset.
8820 SDValue Index = IndexOffset->getOperand(0);
8821 SDValue Offset = IndexOffset->getOperand(1);
8822
8823 if (!isa<ConstantSDNode>(Offset))
8824 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8825
8826 // Ignore signextends.
8827 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8828 Index = Index->getOperand(0);
8829 IsIndexSignExt = true;
8830 } else IsIndexSignExt = false;
8831
8832 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8833 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8834 }
8835};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008836
8837/// Holds a pointer to an LSBaseSDNode as well as information on where it
8838/// is located in a sequence of memory operations connected by a chain.
8839struct MemOpLink {
8840 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8841 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8842 // Ptr to the mem node.
8843 LSBaseSDNode *MemNode;
8844 // Offset from the base ptr.
8845 int64_t OffsetFromBase;
8846 // What is the sequence number of this mem node.
8847 // Lowest mem operand in the DAG starts at zero.
8848 unsigned SequenceNum;
8849};
8850
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008851bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8852 EVT MemVT = St->getMemoryVT();
8853 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008854 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8855 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008856
8857 // Don't merge vectors into wider inputs.
8858 if (MemVT.isVector() || !MemVT.isSimple())
8859 return false;
8860
8861 // Perform an early exit check. Do not bother looking at stored values that
8862 // are not constants or loads.
8863 SDValue StoredVal = St->getValue();
8864 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8865 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8866 !IsLoadSrc)
8867 return false;
8868
8869 // Only look at ends of store sequences.
8870 SDValue Chain = SDValue(St, 1);
8871 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8872 return false;
8873
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008874 // This holds the base pointer, index, and the offset in bytes from the base
8875 // pointer.
8876 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008877
8878 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008879 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008880 return false;
8881
8882 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008883 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008884 return false;
8885
Nadav Rotem307d7672012-11-29 00:00:08 +00008886 // Save the LoadSDNodes that we find in the chain.
8887 // We need to make sure that these nodes do not interfere with
8888 // any of the store nodes.
8889 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8890
8891 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008892 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00008893
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008894 // Walk up the chain and look for nodes with offsets from the same
8895 // base pointer. Stop when reaching an instruction with a different kind
8896 // or instruction which has a different base pointer.
8897 unsigned Seq = 0;
8898 StoreSDNode *Index = St;
8899 while (Index) {
8900 // If the chain has more than one use, then we can't reorder the mem ops.
8901 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8902 break;
8903
8904 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008905 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008906
8907 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008908 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008909 break;
8910
8911 // Check that the alignment is the same.
8912 if (Index->getAlignment() != St->getAlignment())
8913 break;
8914
8915 // The memory operands must not be volatile.
8916 if (Index->isVolatile() || Index->isIndexed())
8917 break;
8918
8919 // No truncation.
8920 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8921 if (St->isTruncatingStore())
8922 break;
8923
8924 // The stored memory type must be the same.
8925 if (Index->getMemoryVT() != MemVT)
8926 break;
8927
8928 // We do not allow unaligned stores because we want to prevent overriding
8929 // stores.
8930 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8931 break;
8932
8933 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008934 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008935
Nadav Rotem307d7672012-11-29 00:00:08 +00008936 // Find the next memory operand in the chain. If the next operand in the
8937 // chain is a store then move up and continue the scan with the next
8938 // memory operand. If the next operand is a load save it and use alias
8939 // information to check if it interferes with anything.
8940 SDNode *NextInChain = Index->getChain().getNode();
8941 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00008942 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00008943 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00008944 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00008945 break;
8946 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00008947 if (Ldn->isVolatile()) {
8948 Index = NULL;
8949 break;
8950 }
8951
Nadav Rotem307d7672012-11-29 00:00:08 +00008952 // Save the load node for later. Continue the scan.
8953 AliasLoadNodes.push_back(Ldn);
8954 NextInChain = Ldn->getChain().getNode();
8955 continue;
8956 } else {
8957 Index = NULL;
8958 break;
8959 }
8960 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008961 }
8962
8963 // Check if there is anything to merge.
8964 if (StoreNodes.size() < 2)
8965 return false;
8966
8967 // Sort the memory operands according to their distance from the base pointer.
8968 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008969 [](MemOpLink LHS, MemOpLink RHS) {
8970 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
8971 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
8972 LHS.SequenceNum > RHS.SequenceNum);
8973 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008974
8975 // Scan the memory operations on the chain and find the first non-consecutive
8976 // store memory address.
8977 unsigned LastConsecutiveStore = 0;
8978 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00008979 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8980
8981 // Check that the addresses are consecutive starting from the second
8982 // element in the list of stores.
8983 if (i > 0) {
8984 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8985 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8986 break;
8987 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008988
Nadav Rotem307d7672012-11-29 00:00:08 +00008989 bool Alias = false;
8990 // Check if this store interferes with any of the loads that we found.
8991 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8992 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8993 Alias = true;
8994 break;
8995 }
Nadav Rotem307d7672012-11-29 00:00:08 +00008996 // We found a load that alias with this store. Stop the sequence.
8997 if (Alias)
8998 break;
8999
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009000 // Mark this node as useful.
9001 LastConsecutiveStore = i;
9002 }
9003
9004 // The node with the lowest store address.
9005 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9006
9007 // Store the constants into memory as one consecutive store.
9008 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009009 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009010 unsigned LastLegalVectorType = 0;
9011 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009012 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9013 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9014 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009015
9016 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009017 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009018 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009019 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009020 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009021 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009022 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009023 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009024
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009025 // Find a legal type for the constant store.
9026 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9027 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9028 if (TLI.isTypeLegal(StoreTy))
9029 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009030 // Or check whether a truncstore is legal.
9031 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9032 TargetLowering::TypePromoteInteger) {
9033 EVT LegalizedStoredValueTy =
9034 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9035 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9036 LastLegalType = i+1;
9037 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009038
9039 // Find a legal type for the vector store.
9040 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9041 if (TLI.isTypeLegal(Ty))
9042 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009043 }
9044
Bob Wilson3365b802012-12-20 01:36:20 +00009045 // We only use vectors if the constant is known to be zero and the
9046 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009047 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009048 LastLegalVectorType = 0;
9049
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009050 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009051 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009052 return false;
9053
Nadav Rotem495b1a42013-02-14 18:28:52 +00009054 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009055 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9056
9057 // Make sure we have something to merge.
9058 if (NumElem < 2)
9059 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009060
9061 unsigned EarliestNodeUsed = 0;
9062 for (unsigned i=0; i < NumElem; ++i) {
9063 // Find a chain for the new wide-store operand. Notice that some
9064 // of the store nodes that we found may not be selected for inclusion
9065 // in the wide store. The chain we use needs to be the chain of the
9066 // earliest store node which is *used* and replaced by the wide store.
9067 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9068 EarliestNodeUsed = i;
9069 }
9070
9071 // The earliest Node in the DAG.
9072 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009073 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009074
Nadav Rotemb27777f2012-10-04 22:35:15 +00009075 SDValue StoredVal;
9076 if (UseVector) {
9077 // Find a legal type for the vector store.
9078 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9079 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9080 StoredVal = DAG.getConstant(0, Ty);
9081 } else {
9082 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9083 APInt StoreInt(StoreBW, 0);
9084
9085 // Construct a single integer constant which is made of the smaller
9086 // constant inputs.
9087 bool IsLE = TLI.isLittleEndian();
9088 for (unsigned i = 0; i < NumElem ; ++i) {
9089 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9090 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9091 SDValue Val = St->getValue();
9092 StoreInt<<=ElementSizeBytes*8;
9093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9094 StoreInt|=C->getAPIntValue().zext(StoreBW);
9095 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9096 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9097 } else {
9098 assert(false && "Invalid constant element type");
9099 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009100 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009101
9102 // Create the new Load and Store operations.
9103 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9104 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009105 }
9106
Nadav Rotemb27777f2012-10-04 22:35:15 +00009107 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009108 FirstInChain->getBasePtr(),
9109 FirstInChain->getPointerInfo(),
9110 false, false,
9111 FirstInChain->getAlignment());
9112
9113 // Replace the first store with the new store
9114 CombineTo(EarliestOp, NewStore);
9115 // Erase all other stores.
9116 for (unsigned i = 0; i < NumElem ; ++i) {
9117 if (StoreNodes[i].MemNode == EarliestOp)
9118 continue;
9119 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009120 // ReplaceAllUsesWith will replace all uses that existed when it was
9121 // called, but graph optimizations may cause new ones to appear. For
9122 // example, the case in pr14333 looks like
9123 //
9124 // St's chain -> St -> another store -> X
9125 //
9126 // And the only difference from St to the other store is the chain.
9127 // When we change it's chain to be St's chain they become identical,
9128 // get CSEed and the net result is that X is now a use of St.
9129 // Since we know that St is redundant, just iterate.
9130 while (!St->use_empty())
9131 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009132 removeFromWorkList(St);
9133 DAG.DeleteNode(St);
9134 }
9135
9136 return true;
9137 }
9138
9139 // Below we handle the case of multiple consecutive stores that
9140 // come from multiple consecutive loads. We merge them into a single
9141 // wide load and a single wide store.
9142
9143 // Look for load nodes which are used by the stored values.
9144 SmallVector<MemOpLink, 8> LoadNodes;
9145
9146 // Find acceptable loads. Loads need to have the same chain (token factor),
9147 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009148 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009149 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9150 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9151 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9152 if (!Ld) break;
9153
9154 // Loads must only have one use.
9155 if (!Ld->hasNUsesOfValue(1, 0))
9156 break;
9157
9158 // Check that the alignment is the same as the stores.
9159 if (Ld->getAlignment() != St->getAlignment())
9160 break;
9161
9162 // The memory operands must not be volatile.
9163 if (Ld->isVolatile() || Ld->isIndexed())
9164 break;
9165
9166 // We do not accept ext loads.
9167 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9168 break;
9169
9170 // The stored memory type must be the same.
9171 if (Ld->getMemoryVT() != MemVT)
9172 break;
9173
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009174 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009175 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009176 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009177 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009178 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009179 break;
9180 } else {
9181 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009182 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009183 }
9184
9185 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009186 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009187 }
9188
9189 if (LoadNodes.size() < 2)
9190 return false;
9191
9192 // Scan the memory operations on the chain and find the first non-consecutive
9193 // load memory address. These variables hold the index in the store node
9194 // array.
9195 unsigned LastConsecutiveLoad = 0;
9196 // This variable refers to the size and not index in the array.
9197 unsigned LastLegalVectorType = 0;
9198 unsigned LastLegalIntegerType = 0;
9199 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009200 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9201 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9202 // All loads much share the same chain.
9203 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9204 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009205
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009206 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9207 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9208 break;
9209 LastConsecutiveLoad = i;
9210
9211 // Find a legal type for the vector store.
9212 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9213 if (TLI.isTypeLegal(StoreTy))
9214 LastLegalVectorType = i + 1;
9215
9216 // Find a legal type for the integer store.
9217 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9218 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9219 if (TLI.isTypeLegal(StoreTy))
9220 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009221 // Or check whether a truncstore and extload is legal.
9222 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9223 TargetLowering::TypePromoteInteger) {
9224 EVT LegalizedStoredValueTy =
9225 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9226 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9227 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9228 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9229 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9230 LastLegalIntegerType = i+1;
9231 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009232 }
9233
9234 // Only use vector types if the vector type is larger than the integer type.
9235 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009236 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009237 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9238
9239 // We add +1 here because the LastXXX variables refer to location while
9240 // the NumElem refers to array/index size.
9241 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9242 NumElem = std::min(LastLegalType, NumElem);
9243
9244 if (NumElem < 2)
9245 return false;
9246
9247 // The earliest Node in the DAG.
9248 unsigned EarliestNodeUsed = 0;
9249 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9250 for (unsigned i=1; i<NumElem; ++i) {
9251 // Find a chain for the new wide-store operand. Notice that some
9252 // of the store nodes that we found may not be selected for inclusion
9253 // in the wide store. The chain we use needs to be the chain of the
9254 // earliest store node which is *used* and replaced by the wide store.
9255 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9256 EarliestNodeUsed = i;
9257 }
9258
9259 // Find if it is better to use vectors or integers to load and store
9260 // to memory.
9261 EVT JointMemOpVT;
9262 if (UseVectorTy) {
9263 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9264 } else {
9265 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9266 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9267 }
9268
Andrew Trickef9de2a2013-05-25 02:42:55 +00009269 SDLoc LoadDL(LoadNodes[0].MemNode);
9270 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009271
9272 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9273 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9274 FirstLoad->getChain(),
9275 FirstLoad->getBasePtr(),
9276 FirstLoad->getPointerInfo(),
9277 false, false, false,
9278 FirstLoad->getAlignment());
9279
9280 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9281 FirstInChain->getBasePtr(),
9282 FirstInChain->getPointerInfo(), false, false,
9283 FirstInChain->getAlignment());
9284
Nadav Rotemac920662012-10-03 19:30:31 +00009285 // Replace one of the loads with the new load.
9286 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9287 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9288 SDValue(NewLoad.getNode(), 1));
9289
9290 // Remove the rest of the load chains.
9291 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009292 // Replace all chain users of the old load nodes with the chain of the new
9293 // load node.
9294 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009295 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9296 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009297
Nadav Rotemac920662012-10-03 19:30:31 +00009298 // Replace the first store with the new store.
9299 CombineTo(EarliestOp, NewStore);
9300 // Erase all other stores.
9301 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009302 // Remove all Store nodes.
9303 if (StoreNodes[i].MemNode == EarliestOp)
9304 continue;
9305 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9306 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9307 removeFromWorkList(St);
9308 DAG.DeleteNode(St);
9309 }
9310
9311 return true;
9312}
9313
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009314SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009315 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009316 SDValue Chain = ST->getChain();
9317 SDValue Value = ST->getValue();
9318 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009319
Evan Chenga4cf58a2007-05-07 21:27:48 +00009320 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009321 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009322 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009323 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009324 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009325 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009326 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009327 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009328 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009329 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009330 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009331 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009332 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009333 ST->isNonTemporal(), OrigAlign,
9334 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009335 }
Owen Andersona5192842011-04-14 17:30:49 +00009336
Chris Lattner41c80e82011-04-09 02:32:02 +00009337 // Turn 'store undef, Ptr' -> nothing.
9338 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9339 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009340
Nate Begeman8e20c762006-12-11 02:23:46 +00009341 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009342 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009343 // NOTE: If the original store is volatile, this transform must not increase
9344 // the number of stores. For example, on x86-32 an f64 can be stored in one
9345 // processor operation but an i64 (which is not legal) requires two. So the
9346 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009347 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009348 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009349 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009350 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009351 case MVT::f16: // We don't do this for these yet.
9352 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009353 case MVT::f128:
9354 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009355 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009356 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009357 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009358 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009359 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009360 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009361 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009362 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009363 }
9364 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009365 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009366 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009367 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009368 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009369 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009370 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009371 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009372 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009373 }
Owen Andersona5192842011-04-14 17:30:49 +00009374
Chris Lattner41c80e82011-04-09 02:32:02 +00009375 if (!ST->isVolatile() &&
9376 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009377 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009378 // argument passing. Since this is so common, custom legalize the
9379 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009380 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009381 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9382 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009383 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009384
Dan Gohman2af30632007-07-09 22:18:38 +00009385 unsigned Alignment = ST->getAlignment();
9386 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009387 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009388 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009389
Andrew Trickef9de2a2013-05-25 02:42:55 +00009390 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009391 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009392 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009393 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009394 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009395 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009396 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009397 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009398 Ptr, ST->getPointerInfo().getWithOffset(4),
9399 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009400 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009401 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009402 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009403 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009404
Chris Lattnerb7524b62006-12-12 04:16:14 +00009405 break;
Evan Cheng21836982006-12-11 17:25:19 +00009406 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009407 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009408 }
9409
Evan Cheng43cd9e32010-04-01 06:04:33 +00009410 // Try to infer better alignment information than the store already has.
9411 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009412 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9413 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009414 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009415 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009416 ST->isVolatile(), ST->isNonTemporal(), Align,
9417 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009418 }
9419 }
9420
Evan Chengd42641c2011-02-02 01:06:55 +00009421 // Try transforming a pair floating point load / store ops to integer
9422 // load / store ops.
9423 SDValue NewST = TransformFPLoadStorePair(N);
9424 if (NewST.getNode())
9425 return NewST;
9426
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009427 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9428 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009429#ifndef NDEBUG
9430 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9431 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9432 UseAA = false;
9433#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009434 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009435 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009436 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009437
Jim Laskey708d0db2006-10-04 16:53:27 +00009438 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009439 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009440 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009441
9442 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009443 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009444 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009445 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009446 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009447 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009448 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009450
Jim Laskeyd07be232006-09-25 16:29:54 +00009451 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009452 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009453 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009454
Nate Begeman879d8f12009-09-15 00:18:30 +00009455 // Make sure the new and old chains are cleaned up.
9456 AddToWorkList(Token.getNode());
9457
Jim Laskeydcf983c2006-10-13 23:32:28 +00009458 // Don't add users to work list.
9459 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009460 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009461 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009462
Evan Cheng33157702006-11-05 09:31:14 +00009463 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009464 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009465 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009466
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009467 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009468 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009469 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009470 // See if we can simplify the input to this truncstore with knowledge that
9471 // only the low bits are being used. For example:
9472 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009473 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009474 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009475 APInt::getLowBitsSet(
9476 Value.getValueType().getScalarType().getSizeInBits(),
9477 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009478 AddToWorkList(Value.getNode());
9479 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009480 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009481 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009482
Chris Lattnerf47e3062007-10-13 06:58:48 +00009483 // Otherwise, see if we can simplify the operation with
9484 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009485 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009486 APInt::getLowBitsSet(
9487 Value.getValueType().getScalarType().getSizeInBits(),
9488 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009489 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009490 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009491
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009492 // If this is a load followed by a store to the same location, then the store
9493 // is dead/noop.
9494 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009495 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009496 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009497 // There can't be any side effects between the load and store, such as
9498 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009499 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009500 // The store is dead, remove it.
9501 return Chain;
9502 }
9503 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009504
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009505 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9506 // truncating store. We can do this even if this is already a truncstore.
9507 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009508 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009509 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009510 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009511 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009512 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009513 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009514
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009515 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009516 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009517 if (!LegalTypes) {
9518 bool EverChanged = false;
9519
9520 do {
9521 // There can be multiple store sequences on the same chain.
9522 // Keep trying to merge store sequences until we are unable to do so
9523 // or until we merge the last store on the chain.
9524 bool Changed = MergeConsecutiveStores(ST);
9525 EverChanged |= Changed;
9526 if (!Changed) break;
9527 } while (ST->getOpcode() != ISD::DELETED_NODE);
9528
9529 if (EverChanged)
9530 return SDValue(N, 0);
9531 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009532
Evan Chenga9cda8a2009-05-28 00:35:15 +00009533 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009534}
9535
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009536SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9537 SDValue InVec = N->getOperand(0);
9538 SDValue InVal = N->getOperand(1);
9539 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009540 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009541
Bob Wilson42603952010-05-19 23:42:58 +00009542 // If the inserted element is an UNDEF, just use the input vector.
9543 if (InVal.getOpcode() == ISD::UNDEF)
9544 return InVec;
9545
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009546 EVT VT = InVec.getValueType();
9547
Owen Andersonb2c80da2011-02-25 21:41:48 +00009548 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009549 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9550 return SDValue();
9551
Eli Friedmanb7910b72011-09-09 21:04:06 +00009552 // Check that we know which element is being inserted
9553 if (!isa<ConstantSDNode>(EltNo))
9554 return SDValue();
9555 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009556
Eli Friedmanb7910b72011-09-09 21:04:06 +00009557 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9558 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9559 // vector elements.
9560 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009561 // Do not combine these two vectors if the output vector will not replace
9562 // the input vector.
9563 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009564 Ops.append(InVec.getNode()->op_begin(),
9565 InVec.getNode()->op_end());
9566 } else if (InVec.getOpcode() == ISD::UNDEF) {
9567 unsigned NElts = VT.getVectorNumElements();
9568 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9569 } else {
9570 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009571 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009572
9573 // Insert the element
9574 if (Elt < Ops.size()) {
9575 // All the operands of BUILD_VECTOR must have the same type;
9576 // we enforce that here.
9577 EVT OpVT = Ops[0].getValueType();
9578 if (InVal.getValueType() != OpVT)
9579 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9580 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9581 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9582 Ops[Elt] = InVal;
9583 }
9584
9585 // Return the new vector
9586 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9587 VT, &Ops[0], Ops.size());
Chris Lattner5336a592006-03-19 01:27:56 +00009588}
9589
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009590SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009591 // (vextract (scalar_to_vector val, 0) -> val
9592 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009593 EVT VT = InVec.getValueType();
9594 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009595
Duncan Sands6be291a2011-05-09 08:03:33 +00009596 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9597 // Check if the result type doesn't match the inserted element type. A
9598 // SCALAR_TO_VECTOR may truncate the inserted element and the
9599 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9600 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009601 if (InOp.getValueType() != NVT) {
9602 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009603 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009604 }
9605 return InOp;
9606 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009607
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009608 SDValue EltNo = N->getOperand(1);
9609 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9610
9611 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9612 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009613 // we may introduce new vector instructions which are not backed by TD
9614 // patterns. For example on AVX, extracting elements from a wide vector
9615 // without using extract_subvector.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009616 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9617 && ConstEltNo && !LegalOperations) {
9618 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9619 int NumElem = VT.getVectorNumElements();
9620 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9621 // Find the new index to extract from.
9622 int OrigElt = SVOp->getMaskElt(Elt);
9623
9624 // Extracting an undef index is undef.
9625 if (OrigElt == -1)
9626 return DAG.getUNDEF(NVT);
9627
9628 // Select the right vector half to extract from.
9629 if (OrigElt < NumElem) {
9630 InVec = InVec->getOperand(0);
9631 } else {
9632 InVec = InVec->getOperand(1);
9633 OrigElt -= NumElem;
9634 }
9635
Tom Stellardd42c5942013-08-05 22:22:01 +00009636 EVT IndexTy = TLI.getVectorIdxTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009637 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00009638 InVec, DAG.getConstant(OrigElt, IndexTy));
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009639 }
9640
Evan Cheng1120279a2008-05-13 08:35:03 +00009641 // Perform only after legalization to ensure build_vector / vector_shuffle
9642 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009643 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009644
Mon P Wangca6d6de2009-01-17 00:07:25 +00009645 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9646 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9647 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009648
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009649 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009650 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009651 bool NewLoad = false;
Mon P Wangb5eb7202008-12-11 00:26:16 +00009652 bool BCNumEltsChanged = false;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009653 EVT ExtVT = VT.getVectorElementType();
9654 EVT LVT = ExtVT;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009655
Evan Cheng7bf83092012-03-13 22:00:52 +00009656 // If the result of load has to be truncated, then it's not necessarily
9657 // profitable.
Evan Chengd5f8e572012-03-13 22:16:11 +00009658 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng7bf83092012-03-13 22:00:52 +00009659 return SDValue();
9660
Wesley Peck527da1b2010-11-23 03:31:01 +00009661 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009662 // Don't duplicate a load with other uses.
9663 if (!InVec.hasOneUse())
9664 return SDValue();
9665
Owen Anderson53aa7a92009-08-10 22:56:29 +00009666 EVT BCVT = InVec.getOperand(0).getValueType();
9667 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009668 return SDValue();
Mon P Wangb5eb7202008-12-11 00:26:16 +00009669 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9670 BCNumEltsChanged = true;
Evan Cheng1120279a2008-05-13 08:35:03 +00009671 InVec = InVec.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009672 ExtVT = BCVT.getVectorElementType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009673 NewLoad = true;
9674 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009675
Evan Cheng1120279a2008-05-13 08:35:03 +00009676 LoadSDNode *LN0 = NULL;
Nate Begeman5f829d82009-04-29 05:20:52 +00009677 const ShuffleVectorSDNode *SVN = NULL;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009678 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009679 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009680 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009681 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009682 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009683 // Don't duplicate a load with other uses.
9684 if (!InVec.hasOneUse())
9685 return SDValue();
9686
Evan Cheng1120279a2008-05-13 08:35:03 +00009687 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009688 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009689 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9690 // =>
9691 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009692
Eli Friedmane96286c2011-12-26 22:49:32 +00009693 // Don't duplicate a load with other uses.
9694 if (!InVec.hasOneUse())
9695 return SDValue();
9696
Mon P Wangb5eb7202008-12-11 00:26:16 +00009697 // If the bit convert changed the number of elements, it is unsafe
9698 // to examine the mask.
9699 if (BCNumEltsChanged)
9700 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009701
9702 // Select the input vector, guarding against out of range extract vector.
9703 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009704 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009705 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9706
Eli Friedmane96286c2011-12-26 22:49:32 +00009707 if (InVec.getOpcode() == ISD::BITCAST) {
9708 // Don't duplicate a load with other uses.
9709 if (!InVec.hasOneUse())
9710 return SDValue();
9711
Evan Cheng1120279a2008-05-13 08:35:03 +00009712 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009713 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009714 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009715 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009716 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009717 }
9718 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009719
Eli Friedmane96286c2011-12-26 22:49:32 +00009720 // Make sure we found a non-volatile load and the extractelement is
9721 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009722 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009723 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009724
Eric Christopherc6418b12010-11-03 20:44:42 +00009725 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9726 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009727 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009728
Evan Cheng1120279a2008-05-13 08:35:03 +00009729 unsigned Align = LN0->getAlignment();
9730 if (NewLoad) {
9731 // Check the resultant load doesn't need a higher alignment than the
9732 // original load.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009733 unsigned NewAlign =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009734 TLI.getDataLayout()
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009735 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendling27d9dd42009-01-30 23:36:47 +00009736
Dan Gohman4aa18462009-01-28 17:46:25 +00009737 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009738 return SDValue();
Bill Wendling27d9dd42009-01-30 23:36:47 +00009739
Evan Cheng1120279a2008-05-13 08:35:03 +00009740 Align = NewAlign;
9741 }
9742
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009743 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009744 unsigned PtrOff = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00009745
Eric Christopherc6418b12010-11-03 20:44:42 +00009746 if (Elt) {
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009747 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009748 EVT PtrType = NewPtr.getValueType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009749 if (TLI.isBigEndian())
Duncan Sands13237ac2008-06-06 12:08:01 +00009750 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009751 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng1120279a2008-05-13 08:35:03 +00009752 DAG.getConstant(PtrOff, PtrType));
9753 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009754
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009755 // The replacement we need to do here is a little tricky: we need to
9756 // replace an extractelement of a load with a load.
9757 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmane96286c2011-12-26 22:49:32 +00009758 // Note that this replacement assumes that the extractvalue is the only
9759 // use of the load; that's okay because we don't want to perform this
9760 // transformation in other cases anyway.
Evan Cheng7bf83092012-03-13 22:00:52 +00009761 SDValue Load;
Evan Chengd5f8e572012-03-13 22:16:11 +00009762 SDValue Chain;
Evan Cheng7bf83092012-03-13 22:00:52 +00009763 if (NVT.bitsGT(LVT)) {
9764 // If the result type of vextract is wider than the load, then issue an
9765 // extending load instead.
9766 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9767 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009768 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng7bf83092012-03-13 22:00:52 +00009769 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009770 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9771 Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009772 Chain = Load.getValue(1);
9773 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009774 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng7bf83092012-03-13 22:00:52 +00009775 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lincfe7f352013-07-08 00:37:03 +00009776 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009777 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009778 Chain = Load.getValue(1);
9779 if (NVT.bitsLT(LVT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009780 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009781 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009782 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009783 }
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009784 WorkListRemover DeadNodes(*this);
9785 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chengd5f8e572012-03-13 22:16:11 +00009786 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009787 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009788 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9789 // worklist explicitly as well.
9790 AddToWorkList(Load.getNode());
Craig Topperaaeae982012-03-20 05:28:39 +00009791 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009792 // Make sure to revisit this node to clean it up; it will usually be dead.
9793 AddToWorkList(N);
9794 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009795 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009796
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009797 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009798}
Evan Cheng0de312d2007-10-06 08:19:55 +00009799
Michael Liao6d106b72012-10-23 23:06:52 +00009800// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9801SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9802 // We perform this optimization post type-legalization because
9803 // the type-legalizer often scalarizes integer-promoted vectors.
9804 // Performing this optimization before may create bit-casts which
9805 // will be type-legalized to complex code sequences.
9806 // We perform this optimization only before the operation legalizer because we
9807 // may introduce illegal operations.
9808 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9809 return SDValue();
9810
Dan Gohmana8665142007-06-25 16:23:39 +00009811 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009812 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009813 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009814
Nadav Rotembf6568b2011-10-29 21:23:04 +00009815 // Check to see if this is a BUILD_VECTOR of a bunch of values
9816 // which come from any_extend or zero_extend nodes. If so, we can create
9817 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009818 // optimizations. We do not handle sign-extend because we can't fill the sign
9819 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009820 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009821 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009822
Craig Topper02cb0fb2012-01-17 09:09:48 +00009823 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009824 SDValue In = N->getOperand(i);
9825 // Ignore undef inputs.
9826 if (In.getOpcode() == ISD::UNDEF) continue;
9827
9828 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9829 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9830
Nadav Rotemf3103612011-10-31 20:08:25 +00009831 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009832 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009833 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009834 break;
9835 }
9836
9837 // The input is a ZeroExt or AnyExt. Check the original type.
9838 EVT InTy = In.getOperand(0).getValueType();
9839
9840 // Check that all of the widened source types are the same.
9841 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009842 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009843 SourceType = InTy;
9844 else if (InTy != SourceType) {
9845 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009846 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009847 break;
9848 }
9849
9850 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009851 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009852 }
9853
Nadav Rotemf3103612011-10-31 20:08:25 +00009854 // In order to have valid types, all of the inputs must be extended from the
9855 // same source type and all of the inputs must be any or zero extend.
9856 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009857 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009858 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +00009859 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9860 isPowerOf2_32(SourceType.getSizeInBits());
9861
Nadav Rotem6fd1d322012-03-15 08:49:06 +00009862 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9863 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +00009864 if (!ValidTypes)
9865 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +00009866
Michael Liao6d106b72012-10-23 23:06:52 +00009867 bool isLE = TLI.isLittleEndian();
9868 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9869 assert(ElemRatio > 1 && "Invalid element size ratio");
9870 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9871 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009872
Michael Liao6d106b72012-10-23 23:06:52 +00009873 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9874 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009875
Michael Liao6d106b72012-10-23 23:06:52 +00009876 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +00009877 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +00009878 SDValue Cast = N->getOperand(i);
9879 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9880 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9881 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9882 SDValue In;
9883 if (Cast.getOpcode() == ISD::UNDEF)
9884 In = DAG.getUNDEF(SourceType);
9885 else
9886 In = Cast->getOperand(0);
9887 unsigned Index = isLE ? (i * ElemRatio) :
9888 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +00009889
Michael Liao6d106b72012-10-23 23:06:52 +00009890 assert(Index < Ops.size() && "Invalid index");
9891 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009892 }
Chris Lattner5336a592006-03-19 01:27:56 +00009893
Michael Liao6d106b72012-10-23 23:06:52 +00009894 // The type of the new BUILD_VECTOR node.
9895 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9896 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9897 "Invalid vector size");
9898 // Check if the new vector type is legal.
9899 if (!isTypeLegal(VecVT)) return SDValue();
9900
9901 // Make the new BUILD_VECTOR.
9902 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9903
9904 // The new BUILD_VECTOR node has the potential to be further optimized.
9905 AddToWorkList(BV.getNode());
9906 // Bitcast to the desired type.
9907 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9908}
9909
Michael Liao59229792012-10-24 04:14:18 +00009910SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9911 EVT VT = N->getValueType(0);
9912
9913 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009914 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +00009915
9916 EVT SrcVT = MVT::Other;
9917 unsigned Opcode = ISD::DELETED_NODE;
9918 unsigned NumDefs = 0;
9919
9920 for (unsigned i = 0; i != NumInScalars; ++i) {
9921 SDValue In = N->getOperand(i);
9922 unsigned Opc = In.getOpcode();
9923
9924 if (Opc == ISD::UNDEF)
9925 continue;
9926
9927 // If all scalar values are floats and converted from integers.
9928 if (Opcode == ISD::DELETED_NODE &&
9929 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9930 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +00009931 }
Tom Stellard567f8862013-01-02 22:13:01 +00009932
Michael Liao59229792012-10-24 04:14:18 +00009933 if (Opc != Opcode)
9934 return SDValue();
9935
9936 EVT InVT = In.getOperand(0).getValueType();
9937
9938 // If all scalar values are typed differently, bail out. It's chosen to
9939 // simplify BUILD_VECTOR of integer types.
9940 if (SrcVT == MVT::Other)
9941 SrcVT = InVT;
9942 if (SrcVT != InVT)
9943 return SDValue();
9944 NumDefs++;
9945 }
9946
9947 // If the vector has just one element defined, it's not worth to fold it into
9948 // a vectorized one.
9949 if (NumDefs < 2)
9950 return SDValue();
9951
9952 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9953 && "Should only handle conversion from integer to float.");
9954 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9955
9956 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +00009957
9958 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9959 return SDValue();
9960
Michael Liao59229792012-10-24 04:14:18 +00009961 SmallVector<SDValue, 8> Opnds;
9962 for (unsigned i = 0; i != NumInScalars; ++i) {
9963 SDValue In = N->getOperand(i);
9964
9965 if (In.getOpcode() == ISD::UNDEF)
9966 Opnds.push_back(DAG.getUNDEF(SrcVT));
9967 else
9968 Opnds.push_back(In.getOperand(0));
9969 }
9970 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9971 &Opnds[0], Opnds.size());
9972 AddToWorkList(BV.getNode());
9973
9974 return DAG.getNode(Opcode, dl, VT, BV);
9975}
9976
Michael Liao6d106b72012-10-23 23:06:52 +00009977SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9978 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009979 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +00009980 EVT VT = N->getValueType(0);
9981
9982 // A vector built entirely of undefs is undef.
9983 if (ISD::allOperandsUndef(N))
9984 return DAG.getUNDEF(VT);
9985
9986 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9987 if (V.getNode())
9988 return V;
9989
Michael Liao59229792012-10-24 04:14:18 +00009990 V = reduceBuildVecConvertToConvertBuildVec(N);
9991 if (V.getNode())
9992 return V;
9993
Dan Gohmana8665142007-06-25 16:23:39 +00009994 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9995 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9996 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +00009997
9998 // May only combine to shuffle after legalize if shuffle is legal.
9999 if (LegalOperations &&
10000 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10001 return SDValue();
10002
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010003 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010004 for (unsigned i = 0; i != NumInScalars; ++i) {
10005 // Ignore undef inputs.
10006 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010007
Dan Gohmana8665142007-06-25 16:23:39 +000010008 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010009 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010010 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010011 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010012 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010013 break;
10014 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010015
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010016 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010017 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010018 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10019 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010020
Gabor Greiff304a7a2008-08-28 21:40:38 +000010021 if (VecIn1.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010022 VecIn1 = ExtractedFromVec;
Gabor Greiff304a7a2008-08-28 21:40:38 +000010023 } else if (VecIn2.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010024 VecIn2 = ExtractedFromVec;
10025 } else {
10026 // Too many inputs.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010027 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010028 break;
10029 }
10030 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010031
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010032 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010033 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010034 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010035 for (unsigned i = 0; i != NumInScalars; ++i) {
10036 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010037 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010038 continue;
10039 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010040
Rafael Espindolab93db662009-04-24 12:40:33 +000010041 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010042 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010043 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010044 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010045 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10046 if (ExtIndex > VT.getVectorNumElements())
10047 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010048
Nate Begeman5f829d82009-04-29 05:20:52 +000010049 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010050 continue;
10051 }
10052
10053 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010054 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010055 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010056 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010057
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010058 // We can't generate a shuffle node with mismatched input and output types.
10059 // Attempt to transform a single input vector to the correct type.
10060 if ((VT != VecIn1.getValueType())) {
10061 // We don't support shuffeling between TWO values of different types.
10062 if (VecIn2.getNode() != 0)
10063 return SDValue();
10064
10065 // We only support widening of vectors which are half the size of the
10066 // output registers. For example XMM->YMM widening on X86 with AVX.
10067 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10068 return SDValue();
10069
James Molloy1e5c6112012-09-10 14:01:21 +000010070 // If the input vector type has a different base type to the output
10071 // vector type, bail out.
10072 if (VecIn1.getValueType().getVectorElementType() !=
10073 VT.getVectorElementType())
10074 return SDValue();
10075
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010076 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010077 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010078 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010079 }
10080
10081 // If VecIn2 is unused then change it to undef.
10082 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10083
Nadav Rotem841c9a82012-09-20 08:53:31 +000010084 // Check that we were able to transform all incoming values to the same
10085 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010086 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10087 VecIn1.getValueType() != VT)
10088 return SDValue();
10089
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010090 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010091 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010092 return SDValue();
10093
Dan Gohmana8665142007-06-25 16:23:39 +000010094 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010095 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010096 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010097 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010098 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010099 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010100
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010101 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010102}
10103
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010104SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010105 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10106 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10107 // inputs come from at most two distinct vectors, turn this into a shuffle
10108 // node.
10109
10110 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010111 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010112 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010113
Nadav Rotem01892102012-07-14 21:30:27 +000010114 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010115 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010116 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010117 return DAG.getUNDEF(VT);
10118
10119 // Optimize concat_vectors where one of the vectors is undef.
10120 if (N->getNumOperands() == 2 &&
10121 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10122 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010123 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010124
10125 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10126 if (In->getOpcode() == ISD::BITCAST &&
10127 !In->getOperand(0)->getValueType(0).isVector()) {
10128 SDValue Scalar = In->getOperand(0);
10129 EVT SclTy = Scalar->getValueType(0);
10130
10131 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10132 return SDValue();
10133
10134 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10135 VT.getSizeInBits() / SclTy.getSizeInBits());
10136 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10137 return SDValue();
10138
10139 SDLoc dl = SDLoc(N);
10140 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10141 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10142 }
10143 }
Nadav Rotem01892102012-07-14 21:30:27 +000010144
Robert Lougher7d9084f2014-02-11 15:42:46 +000010145 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10146 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10147 if (N->getNumOperands() == 2 &&
10148 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10149 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10150 EVT VT = N->getValueType(0);
10151 SDValue N0 = N->getOperand(0);
10152 SDValue N1 = N->getOperand(1);
10153 SmallVector<SDValue, 8> Opnds;
10154 unsigned BuildVecNumElts = N0.getNumOperands();
10155
10156 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10157 Opnds.push_back(N0.getOperand(i));
10158 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10159 Opnds.push_back(N1.getOperand(i));
10160
10161 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10162 Opnds.size());
10163 }
10164
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010165 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10166 // nodes often generate nop CONCAT_VECTOR nodes.
10167 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10168 // place the incoming vectors at the exact same location.
10169 SDValue SingleSource = SDValue();
10170 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10171
10172 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10173 SDValue Op = N->getOperand(i);
10174
10175 if (Op.getOpcode() == ISD::UNDEF)
10176 continue;
10177
10178 // Check if this is the identity extract:
10179 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10180 return SDValue();
10181
10182 // Find the single incoming vector for the extract_subvector.
10183 if (SingleSource.getNode()) {
10184 if (Op.getOperand(0) != SingleSource)
10185 return SDValue();
10186 } else {
10187 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010188
10189 // Check the source type is the same as the type of the result.
10190 // If not, this concat may extend the vector, so we can not
10191 // optimize it away.
10192 if (SingleSource.getValueType() != N->getValueType(0))
10193 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010194 }
10195
10196 unsigned IdentityIndex = i * PartNumElem;
10197 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10198 // The extract index must be constant.
10199 if (!CS)
10200 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010201
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010202 // Check that we are reading from the identity index.
10203 if (CS->getZExtValue() != IdentityIndex)
10204 return SDValue();
10205 }
10206
10207 if (SingleSource.getNode())
10208 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010209
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010210 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010211}
10212
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010213SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10214 EVT NVT = N->getValueType(0);
10215 SDValue V = N->getOperand(0);
10216
Michael Liao7a442c802012-10-17 20:48:33 +000010217 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10218 // Combine:
10219 // (extract_subvec (concat V1, V2, ...), i)
10220 // Into:
10221 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010222 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10223 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010224 if (V->getOperand(0).getValueType() != NVT)
10225 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010226 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10227 unsigned NumElems = NVT.getVectorNumElements();
10228 assert((Idx % NumElems) == 0 &&
10229 "IDX in concat is not a multiple of the result vector length.");
10230 return V->getOperand(Idx / NumElems);
10231 }
10232
Michael Liaobb05a1d2013-03-25 23:47:35 +000010233 // Skip bitcasting
10234 if (V->getOpcode() == ISD::BITCAST)
10235 V = V.getOperand(0);
10236
10237 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010238 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010239 // Handle only simple case where vector being inserted and vector
10240 // being extracted are of same type, and are half size of larger vectors.
10241 EVT BigVT = V->getOperand(0).getValueType();
10242 EVT SmallVT = V->getOperand(1).getValueType();
10243 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10244 return SDValue();
10245
10246 // Only handle cases where both indexes are constants with the same type.
10247 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10248 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10249
10250 if (InsIdx && ExtIdx &&
10251 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10252 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10253 // Combine:
10254 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10255 // Into:
10256 // indices are equal or bit offsets are equal => V1
10257 // otherwise => (extract_subvec V1, ExtIdx)
10258 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10259 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10260 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10261 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10262 DAG.getNode(ISD::BITCAST, dl,
10263 N->getOperand(0).getValueType(),
10264 V->getOperand(0)), N->getOperand(1));
10265 }
10266 }
10267
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010268 return SDValue();
10269}
10270
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010271// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10272static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10273 EVT VT = N->getValueType(0);
10274 unsigned NumElts = VT.getVectorNumElements();
10275
10276 SDValue N0 = N->getOperand(0);
10277 SDValue N1 = N->getOperand(1);
10278 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10279
10280 SmallVector<SDValue, 4> Ops;
10281 EVT ConcatVT = N0.getOperand(0).getValueType();
10282 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10283 unsigned NumConcats = NumElts / NumElemsPerConcat;
10284
10285 // Look at every vector that's inserted. We're looking for exact
10286 // subvector-sized copies from a concatenated vector
10287 for (unsigned I = 0; I != NumConcats; ++I) {
10288 // Make sure we're dealing with a copy.
10289 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010290 bool AllUndef = true, NoUndef = true;
10291 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10292 if (SVN->getMaskElt(J) >= 0)
10293 AllUndef = false;
10294 else
10295 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010296 }
10297
Hao Liubc601962013-05-13 02:07:05 +000010298 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010299 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10300 return SDValue();
10301
10302 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10303 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10304 return SDValue();
10305
10306 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10307 if (FirstElt < N0.getNumOperands())
10308 Ops.push_back(N0.getOperand(FirstElt));
10309 else
10310 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10311
10312 } else if (AllUndef) {
10313 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10314 } else { // Mixed with general masks and undefs, can't do optimization.
10315 return SDValue();
10316 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010317 }
10318
Andrew Trickef9de2a2013-05-25 02:42:55 +000010319 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010320 Ops.size());
10321}
10322
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010323SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010324 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010325 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010326
Mon P Wang25f01062008-11-10 04:46:22 +000010327 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010328 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010329
Craig Topper5894fe42012-04-09 05:16:56 +000010330 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010331
Craig Topper279c77b2012-01-04 08:07:43 +000010332 // Canonicalize shuffle undef, undef -> undef
10333 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10334 return DAG.getUNDEF(VT);
10335
10336 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10337
10338 // Canonicalize shuffle v, v -> v, undef
10339 if (N0 == N1) {
10340 SmallVector<int, 8> NewMask;
10341 for (unsigned i = 0; i != NumElts; ++i) {
10342 int Idx = SVN->getMaskElt(i);
10343 if (Idx >= (int)NumElts) Idx -= NumElts;
10344 NewMask.push_back(Idx);
10345 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010346 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010347 &NewMask[0]);
10348 }
10349
10350 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10351 if (N0.getOpcode() == ISD::UNDEF) {
10352 SmallVector<int, 8> NewMask;
10353 for (unsigned i = 0; i != NumElts; ++i) {
10354 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010355 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010356 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010357 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010358 else
10359 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010360 }
10361 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010362 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010363 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010364 &NewMask[0]);
10365 }
10366
10367 // Remove references to rhs if it is undef
10368 if (N1.getOpcode() == ISD::UNDEF) {
10369 bool Changed = false;
10370 SmallVector<int, 8> NewMask;
10371 for (unsigned i = 0; i != NumElts; ++i) {
10372 int Idx = SVN->getMaskElt(i);
10373 if (Idx >= (int)NumElts) {
10374 Idx = -1;
10375 Changed = true;
10376 }
10377 NewMask.push_back(Idx);
10378 }
10379 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010380 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010381 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010382
Bob Wilsonf63da122010-10-28 17:06:14 +000010383 // If it is a splat, check if the argument vector is another splat or a
10384 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010385 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010386 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010387
Dan Gohmana8665142007-06-25 16:23:39 +000010388 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010389 // not the number of vector elements, look through it. Be careful not to
10390 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010391 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010392 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010393 if (ConvInput.getValueType().isVector() &&
10394 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010395 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010396 }
10397
Dan Gohmana8665142007-06-25 16:23:39 +000010398 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010399 assert(V->getNumOperands() == NumElts &&
10400 "BUILD_VECTOR has wrong number of operands");
10401 SDValue Base;
10402 bool AllSame = true;
10403 for (unsigned i = 0; i != NumElts; ++i) {
10404 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10405 Base = V->getOperand(i);
10406 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010407 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010408 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010409 // Splat of <u, u, u, u>, return <u, u, u, u>
10410 if (!Base.getNode())
10411 return N0;
10412 for (unsigned i = 0; i != NumElts; ++i) {
10413 if (V->getOperand(i) != Base) {
10414 AllSame = false;
10415 break;
10416 }
10417 }
10418 // Splat of <x, x, x, x>, return <x, x, x, x>
10419 if (AllSame)
10420 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010421 }
10422 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010423
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010424 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10425 Level < AfterLegalizeVectorOps &&
10426 (N1.getOpcode() == ISD::UNDEF ||
10427 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10428 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10429 SDValue V = partitionShuffleOfConcats(N, DAG);
10430
10431 if (V.getNode())
10432 return V;
10433 }
10434
Nadav Rotemb0783502012-04-01 19:31:22 +000010435 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010436 // and it reverses the swizzle of the previous shuffle then we can
10437 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010438 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10439 N1.getOpcode() == ISD::UNDEF) {
10440
Nadav Rotemb0783502012-04-01 19:31:22 +000010441 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10442
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010443 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10444 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10445 return SDValue();
10446
Craig Topper5894fe42012-04-09 05:16:56 +000010447 // The incoming shuffle must be of the same type as the result of the
10448 // current shuffle.
10449 assert(OtherSV->getOperand(0).getValueType() == VT &&
10450 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010451
10452 for (unsigned i = 0; i != NumElts; ++i) {
10453 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010454 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010455 // Next, this index comes from the first value, which is the incoming
10456 // shuffle. Adopt the incoming index.
10457 if (Idx >= 0)
10458 Idx = OtherSV->getMaskElt(Idx);
10459
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010460 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010461 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010462 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010463 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010464
10465 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010466 }
10467
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010468 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010469}
10470
Manman Ren413a6cb2014-01-31 01:10:35 +000010471SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10472 SDValue N0 = N->getOperand(0);
10473 SDValue N2 = N->getOperand(2);
10474
10475 // If the input vector is a concatenation, and the insert replaces
10476 // one of the halves, we can optimize into a single concat_vectors.
10477 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10478 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10479 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10480 EVT VT = N->getValueType(0);
10481
10482 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10483 // (concat_vectors Z, Y)
10484 if (InsIdx == 0)
10485 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10486 N->getOperand(1), N0.getOperand(1));
10487
10488 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10489 // (concat_vectors X, Z)
10490 if (InsIdx == VT.getVectorNumElements()/2)
10491 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10492 N0.getOperand(0), N->getOperand(1));
10493 }
10494
10495 return SDValue();
10496}
10497
Evan Chenga320abc2006-04-20 08:56:16 +000010498/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010499/// an AND to a vector_shuffle with the destination vector and a zero vector.
10500/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010501/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010502SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010503 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010504 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010505 SDValue LHS = N->getOperand(0);
10506 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010507 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010508 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010509 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010510 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010511 SmallVector<int, 8> Indices;
10512 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010513 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010514 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010515 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010516 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010517
10518 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010519 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010520 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010521 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010522 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010523 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010524 }
10525
10526 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010527 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010528 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010529 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010530
Dan Gohmana8665142007-06-25 16:23:39 +000010531 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010532 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010533 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010534 DAG.getConstant(0, EltVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010535 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010536 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peck527da1b2010-11-23 03:31:01 +000010537 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010538 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010539 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010540 }
10541 }
Bill Wendling31b50992009-01-30 23:59:18 +000010542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010543 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010544}
10545
Dan Gohmana8665142007-06-25 16:23:39 +000010546/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010547SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010548 assert(N->getValueType(0).isVector() &&
10549 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010550
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010551 SDValue LHS = N->getOperand(0);
10552 SDValue RHS = N->getOperand(1);
10553 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010554 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010555
Dan Gohmana8665142007-06-25 16:23:39 +000010556 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010557 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010558 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010559 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010560 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010561 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10562 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010563 return SDValue();
10564
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010565 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010566 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010567 SDValue LHSOp = LHS.getOperand(i);
10568 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010569
Evan Cheng64d28462006-05-31 06:08:35 +000010570 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010571 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10572 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010573 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010574 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010575 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010576 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010577 break;
10578 }
Bill Wendling31b50992009-01-30 23:59:18 +000010579
Bob Wilson54081442010-12-17 23:06:49 +000010580 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010581 EVT RVT = RHSOp.getValueType();
10582 if (RVT != VT) {
10583 // Integer BUILD_VECTOR operands may have types larger than the element
10584 // size (e.g., when the element type is not legal). Prior to type
10585 // legalization, the types may not match between the two BUILD_VECTORS.
10586 // Truncate one of the operands to make them match.
10587 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010588 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010589 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010590 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010591 VT = RVT;
10592 }
10593 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010594 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010595 LHSOp, RHSOp);
10596 if (FoldOp.getOpcode() != ISD::UNDEF &&
10597 FoldOp.getOpcode() != ISD::Constant &&
10598 FoldOp.getOpcode() != ISD::ConstantFP)
10599 break;
10600 Ops.push_back(FoldOp);
10601 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010602 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010603
Bob Wilson54081442010-12-17 23:06:49 +000010604 if (Ops.size() == LHS.getNumOperands())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010605 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilson54081442010-12-17 23:06:49 +000010606 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattner0442a182006-04-02 03:25:57 +000010607 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010608
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010609 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010610}
10611
Craig Topper82384612012-09-11 01:45:21 +000010612/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10613SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010614 assert(N->getValueType(0).isVector() &&
10615 "SimplifyVUnaryOp only works on vectors!");
10616
10617 SDValue N0 = N->getOperand(0);
10618
10619 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10620 return SDValue();
10621
10622 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10623 SmallVector<SDValue, 8> Ops;
10624 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10625 SDValue Op = N0.getOperand(i);
10626 if (Op.getOpcode() != ISD::UNDEF &&
10627 Op.getOpcode() != ISD::ConstantFP)
10628 break;
10629 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010630 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010631 if (FoldOp.getOpcode() != ISD::UNDEF &&
10632 FoldOp.getOpcode() != ISD::ConstantFP)
10633 break;
10634 Ops.push_back(FoldOp);
10635 AddToWorkList(FoldOp.getNode());
10636 }
10637
10638 if (Ops.size() != N0.getNumOperands())
10639 return SDValue();
10640
Andrew Trickef9de2a2013-05-25 02:42:55 +000010641 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topper82384612012-09-11 01:45:21 +000010642 N0.getValueType(), &Ops[0], Ops.size());
10643}
10644
Andrew Trickef9de2a2013-05-25 02:42:55 +000010645SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010646 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010647 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010648
Bill Wendling31b50992009-01-30 23:59:18 +000010649 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010650 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010651
Nate Begeman2042aa52005-10-08 00:29:44 +000010652 // If we got a simplified select_cc node back from SimplifySelectCC, then
10653 // break it down into a new SETCC node, and a new SELECT node, and then return
10654 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010655 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010656 // Check to see if we got a select_cc back (to turn into setcc/select).
10657 // Otherwise, just return whatever node we got back, like fabs.
10658 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010659 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010660 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010661 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010662 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010663 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010664 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10665 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010666 }
Bill Wendling31b50992009-01-30 23:59:18 +000010667
Nate Begeman2042aa52005-10-08 00:29:44 +000010668 return SCC;
10669 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010670 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010671}
10672
Chris Lattner6c14c352005-10-18 06:04:22 +000010673/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10674/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010675/// select. Callers of this should assume that TheSelect is deleted if this
10676/// returns true. As such, they should return the appropriate thing (e.g. the
10677/// node) back to the top-level of the DAG combiner loop to avoid it being
10678/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010679bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010680 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010681
Nadav Rotema49a02a2011-02-11 19:57:47 +000010682 // Cannot simplify select with vector condition
10683 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10684
Chris Lattner6c14c352005-10-18 06:04:22 +000010685 // If this is a select from two identical things, try to pull the operation
10686 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010687 if (LHS.getOpcode() != RHS.getOpcode() ||
10688 !LHS.hasOneUse() || !RHS.hasOneUse())
10689 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010690
Chris Lattner254c4452010-09-21 15:46:59 +000010691 // If this is a load and the token chain is identical, replace the select
10692 // of two loads with a load through a select of the address to load from.
10693 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10694 // constants have been dropped into the constant pool.
10695 if (LHS.getOpcode() == ISD::LOAD) {
10696 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10697 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010698
Chris Lattner254c4452010-09-21 15:46:59 +000010699 // Token chains must be identical.
10700 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010701 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010702 LLD->isVolatile() || RLD->isVolatile() ||
10703 // If this is an EXTLOAD, the VT's must match.
10704 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010705 // If this is an EXTLOAD, the kind of extension must match.
10706 (LLD->getExtensionType() != RLD->getExtensionType() &&
10707 // The only exception is if one of the extensions is anyext.
10708 LLD->getExtensionType() != ISD::EXTLOAD &&
10709 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010710 // FIXME: this discards src value information. This is
10711 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010712 // both potential memory locations. Since we are discarding
10713 // src value info, don't do the transformation if the memory
10714 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010715 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010716 RLD->getPointerInfo().getAddrSpace() != 0 ||
10717 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10718 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010719 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010720
Chris Lattnere3267522010-09-21 15:58:55 +000010721 // Check that the select condition doesn't reach either load. If so,
10722 // folding this will induce a cycle into the DAG. If not, this is safe to
10723 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010724 SDValue Addr;
10725 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010726 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10727 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10728 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10729 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010730 // The loads must not depend on one another.
10731 if (LLD->isPredecessorOf(RLD) ||
10732 RLD->isPredecessorOf(LLD))
10733 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010734 Addr = DAG.getSelect(SDLoc(TheSelect),
10735 LLD->getBasePtr().getValueType(),
10736 TheSelect->getOperand(0), LLD->getBasePtr(),
10737 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010738 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010739 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10740 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10741
10742 if ((LLD->hasAnyUseOfValue(1) &&
10743 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010744 (RLD->hasAnyUseOfValue(1) &&
10745 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010746 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010747
Andrew Trickef9de2a2013-05-25 02:42:55 +000010748 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010749 LLD->getBasePtr().getValueType(),
10750 TheSelect->getOperand(0),
10751 TheSelect->getOperand(1),
10752 LLD->getBasePtr(), RLD->getBasePtr(),
10753 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010754 }
10755
Chris Lattnere3267522010-09-21 15:58:55 +000010756 SDValue Load;
10757 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10758 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010759 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010760 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010761 LLD->getChain(), Addr, MachinePointerInfo(),
10762 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010763 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010764 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010765 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10766 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010767 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010768 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010769 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010770 LLD->getChain(), Addr, MachinePointerInfo(),
10771 LLD->getMemoryVT(), LLD->isVolatile(),
10772 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010773 }
Chris Lattnere3267522010-09-21 15:58:55 +000010774
10775 // Users of the select now use the result of the load.
10776 CombineTo(TheSelect, Load);
10777
10778 // Users of the old loads now use the new load's chain. We know the
10779 // old-load value is dead now.
10780 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10781 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10782 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010783 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010784
Chris Lattner6c14c352005-10-18 06:04:22 +000010785 return false;
10786}
10787
Chris Lattner43d63772009-03-11 05:08:08 +000010788/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10789/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010790SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010791 SDValue N2, SDValue N3,
10792 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010793 // (x ? y : y) -> y.
10794 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010795
Owen Anderson53aa7a92009-08-10 22:56:29 +000010796 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010797 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10798 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10799 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010800
10801 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010802 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010803 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010804 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10805 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010806
10807 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010808 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010809 return N2;
10810 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010811 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010812 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010813
Nate Begeman2042aa52005-10-08 00:29:44 +000010814 // Check to see if we can simplify the select into an fabs node
10815 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10816 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010817 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010818 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10819 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10820 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10821 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010822 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010823
Nate Begeman2042aa52005-10-08 00:29:44 +000010824 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10825 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10826 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10827 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010828 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010829 }
10830 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010831
Chris Lattner43d63772009-03-11 05:08:08 +000010832 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10833 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10834 // in it. This is a win when the constant is not otherwise available because
10835 // it replaces two constant pool loads with one. We only do this if the FP
10836 // type is known to be legal, because if it isn't, then we are before legalize
10837 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010838 // messing with soft float) and if the ConstantFP is not legal, because if
10839 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010840 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10841 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10842 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010843 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10844 TargetLowering::Legal) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010845 // If both constants have multiple uses, then we won't need to do an
10846 // extra load, they are likely around in registers for other users.
10847 (TV->hasOneUse() || FV->hasOneUse())) {
10848 Constant *Elts[] = {
10849 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10850 const_cast<ConstantFP*>(TV->getConstantFPValue())
10851 };
Chris Lattner229907c2011-07-18 04:54:35 +000010852 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010853 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010854
Chris Lattner43d63772009-03-11 05:08:08 +000010855 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010856 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010857 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10858 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000010859 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000010860
10861 // Get the offsets to the 0 and 1 element of the array so that we can
10862 // select between them.
10863 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010864 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000010865 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000010866
Chris Lattner43d63772009-03-11 05:08:08 +000010867 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000010868 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000010869 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010870 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010871 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10872 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010873 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000010874 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000010875 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010876 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000010877 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000010878 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000010879 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000010880
10881 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010882 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010883
Nate Begeman2042aa52005-10-08 00:29:44 +000010884 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000010885 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000010886 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000010887 (N1C->isNullValue() || // (a < 0) ? b : 0
10888 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000010889 EVT XType = N0.getValueType();
10890 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000010891 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000010892 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000010893 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010894 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10895 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000010896 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000010897 SDValue ShCt = DAG.getConstant(ShCtV,
10898 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010899 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010900 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010901 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000010902
Duncan Sands11dd4242008-06-08 20:54:56 +000010903 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000010904 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010905 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010906 }
Bill Wendling31b50992009-01-30 23:59:18 +000010907
10908 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000010909 }
Bill Wendling31b50992009-01-30 23:59:18 +000010910
Andrew Trickef9de2a2013-05-25 02:42:55 +000010911 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010912 XType, N0,
10913 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010914 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010915 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000010916
Duncan Sands11dd4242008-06-08 20:54:56 +000010917 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000010918 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010919 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010920 }
Bill Wendling31b50992009-01-30 23:59:18 +000010921
10922 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000010923 }
10924 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010925
Owen Anderson3231d132010-09-22 22:58:22 +000010926 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10927 // where y is has a single bit set.
10928 // A plaintext description would be, we can turn the SELECT_CC into an AND
10929 // when the condition can be materialized as an all-ones register. Any
10930 // single bit-test can be materialized as an all-ones register with
10931 // shift-left and shift-right-arith.
10932 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10933 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000010934 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000010935 N2C && N2C->isNullValue()) {
10936 SDValue AndLHS = N0->getOperand(0);
10937 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10938 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10939 // Shift the tested bit over the sign bit.
10940 APInt AndMask = ConstAndRHS->getAPIntValue();
10941 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000010942 DAG.getConstant(AndMask.countLeadingZeros(),
10943 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010944 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000010945
Owen Anderson3231d132010-09-22 22:58:22 +000010946 // Now arithmetic right shift it all the way over, so the result is either
10947 // all-ones, or zero.
10948 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000010949 DAG.getConstant(AndMask.getBitWidth()-1,
10950 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010951 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000010952
Owen Anderson3231d132010-09-22 22:58:22 +000010953 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10954 }
10955 }
10956
Nate Begeman6828ed92005-10-10 21:26:48 +000010957 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000010958 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000010959 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10960 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010961
Chris Lattnera083ffc2007-04-11 06:50:51 +000010962 // If the caller doesn't want us to simplify this into a zext of a compare,
10963 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010964 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010965 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010966
Nate Begeman6828ed92005-10-10 21:26:48 +000010967 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010968 // NOTE: Don't create a SETCC if it's not legal on this target.
10969 if (!LegalOperations ||
10970 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000010971 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010972 SDValue Temp, SCC;
10973 // cast from setcc result type to select result type
10974 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000010975 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010976 N0, N1, CC);
10977 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010978 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010979 N2.getValueType());
10980 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000010981 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010982 N2.getValueType(), SCC);
10983 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010984 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10985 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000010986 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010987 }
10988
10989 AddToWorkList(SCC.getNode());
10990 AddToWorkList(Temp.getNode());
10991
10992 if (N2C->getAPIntValue() == 1)
10993 return Temp;
10994
10995 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000010996 return DAG.getNode(
10997 ISD::SHL, DL, N2.getValueType(), Temp,
10998 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10999 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011000 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011001 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011002
Nate Begeman2042aa52005-10-08 00:29:44 +000011003 // Check to see if this is the equivalent of setcc
11004 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11005 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011006 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011007 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011008 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011009 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11010 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011011 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011012 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011013 return Res;
11014 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011015
Bill Wendling31b50992009-01-30 23:59:18 +000011016 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011017 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011018 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011019 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011020 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011021 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011022 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011023 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011024 }
Bill Wendling31b50992009-01-30 23:59:18 +000011025 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011026 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011027 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011028 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011029 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011030 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011031 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011032 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011033 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011034 }
Bill Wendling31b50992009-01-30 23:59:18 +000011035 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011036 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011037 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011038 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011039 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011040 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011041 }
11042 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011043
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011044 // Check to see if this is an integer abs.
11045 // select_cc setg[te] X, 0, X, -X ->
11046 // select_cc setgt X, -1, X, -X ->
11047 // select_cc setl[te] X, 0, -X, X ->
11048 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011049 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011050 if (N1C) {
11051 ConstantSDNode *SubC = NULL;
11052 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11053 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11054 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11055 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11056 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11057 (N1C->isOne() && CC == ISD::SETLT)) &&
11058 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11059 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11060
Owen Anderson53aa7a92009-08-10 22:56:29 +000011061 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011062 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011063 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011064 N0,
11065 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011066 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011067 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011068 XType, N0, Shift);
11069 AddToWorkList(Shift.getNode());
11070 AddToWorkList(Add.getNode());
11071 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011072 }
11073 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011074
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011075 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011076}
11077
Evan Cheng92658d52007-02-08 22:13:59 +000011078/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011079SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011080 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011081 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011082 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011083 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011084 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011085}
11086
Nate Begemanc6f067a2005-10-20 02:15:44 +000011087/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11088/// return a DAG expression to select that will generate the same value by
11089/// multiplying by a magic number. See:
11090/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011091SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011092 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011093 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011094
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011095 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011096 ii != ee; ++ii)
11097 AddToWorkList(*ii);
11098 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011099}
11100
11101/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11102/// return a DAG expression to select that will generate the same value by
11103/// multiplying by a magic number. See:
11104/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011105SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011106 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011107 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011108
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011109 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011110 ii != ee; ++ii)
11111 AddToWorkList(*ii);
11112 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011113}
11114
Nate Begeman18150d52009-09-25 06:05:26 +000011115/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011116// to alias with anything but itself. Provides base object and offset as
11117// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011118static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011119 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011120 // Assume it is a primitive operation.
Nate Begeman18150d52009-09-25 06:05:26 +000011121 Base = Ptr; Offset = 0; GV = 0; CV = 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011122
Jim Laskey0463e082006-10-07 23:37:56 +000011123 // If it's an adding a simple constant then integrate the offset.
11124 if (Base.getOpcode() == ISD::ADD) {
11125 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11126 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011127 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011128 }
11129 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011130
Nate Begeman18150d52009-09-25 06:05:26 +000011131 // Return the underlying GlobalValue, and update the Offset. Return false
11132 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11133 // by multiple nodes with different offsets.
11134 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11135 GV = G->getGlobal();
11136 Offset += G->getOffset();
11137 return false;
11138 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011139
Nate Begeman18150d52009-09-25 06:05:26 +000011140 // Return the underlying Constant value, and update the Offset. Return false
11141 // for ConstantSDNodes since the same constant pool entry may be represented
11142 // by multiple nodes with different offsets.
11143 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011144 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11145 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011146 Offset += C->getOffset();
11147 return false;
11148 }
Jim Laskey0463e082006-10-07 23:37:56 +000011149 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011150 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011151}
11152
11153/// isAlias - Return true if there is any possibility that the two addresses
11154/// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011155bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011156 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +000011157 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011158 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011159 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +000011160 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011161 unsigned SrcValueAlign2,
11162 const MDNode *TBAAInfo2) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011163 // If they are the same then they must be aliases.
11164 if (Ptr1 == Ptr2) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011165
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011166 // If they are both volatile then they cannot be reordered.
11167 if (IsVolatile1 && IsVolatile2) return true;
11168
Jim Laskey0463e082006-10-07 23:37:56 +000011169 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011170 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011171 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011172 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011173 const void *CV1, *CV2;
Nate Begeman18150d52009-09-25 06:05:26 +000011174 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11175 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011176
Nate Begeman18150d52009-09-25 06:05:26 +000011177 // If they have a same base address then check to see if they overlap.
11178 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Bill Wendling31b50992009-01-30 23:59:18 +000011179 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011180
Owen Anderson272ff942010-09-20 20:39:59 +000011181 // It is possible for different frame indices to alias each other, mostly
11182 // when tail call optimization reuses return address slots for arguments.
11183 // To catch this case, look up the actual index of frame indices to compute
11184 // the real alias relationship.
11185 if (isFrameIndex1 && isFrameIndex2) {
11186 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11187 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11188 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11189 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11190 }
11191
Wesley Peck527da1b2010-11-23 03:31:01 +000011192 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011193 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011194 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11195 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011196
Nate Begeman879d8f12009-09-15 00:18:30 +000011197 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11198 // compared to the size and offset of the access, we may be able to prove they
11199 // do not alias. This check is conservative for now to catch cases created by
11200 // splitting vector types.
11201 if ((SrcValueAlign1 == SrcValueAlign2) &&
11202 (SrcValueOffset1 != SrcValueOffset2) &&
11203 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11204 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11205 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
Wesley Peck527da1b2010-11-23 03:31:01 +000011206
Nate Begeman879d8f12009-09-15 00:18:30 +000011207 // There is no overlap between these relatively aligned accesses of similar
11208 // size, return no alias.
11209 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11210 return false;
11211 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011212
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011213 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11214 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011215#ifndef NDEBUG
11216 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11217 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11218 UseAA = false;
11219#endif
Hal Finkel31658832013-09-15 02:19:49 +000011220 if (UseAA && SrcValue1 && SrcValue2) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011221 // Use alias analysis information.
Dan Gohman9625d812007-08-27 16:32:11 +000011222 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11223 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11224 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011225 AliasAnalysis::AliasResult AAResult =
Hal Finkeldbebb522014-01-25 19:24:54 +000011226 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11227 UseTBAA ? TBAAInfo1 : 0),
11228 AliasAnalysis::Location(SrcValue2, Overlap2,
11229 UseTBAA ? TBAAInfo2 : 0));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011230 if (AAResult == AliasAnalysis::NoAlias)
11231 return false;
11232 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011233
11234 // Otherwise we have to assume they alias.
11235 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011236}
11237
Nadav Rotem307d7672012-11-29 00:00:08 +000011238bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11239 SDValue Ptr0, Ptr1;
11240 int64_t Size0, Size1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011241 bool IsVolatile0, IsVolatile1;
Nadav Rotem307d7672012-11-29 00:00:08 +000011242 const Value *SrcValue0, *SrcValue1;
11243 int SrcValueOffset0, SrcValueOffset1;
11244 unsigned SrcValueAlign0, SrcValueAlign1;
11245 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011246 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotem307d7672012-11-29 00:00:08 +000011247 SrcValueAlign0, SrcTBAAInfo0);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011248 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotem307d7672012-11-29 00:00:08 +000011249 SrcValueAlign1, SrcTBAAInfo1);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011250 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011251 SrcValueAlign0, SrcTBAAInfo0,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011252 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011253 SrcValueAlign1, SrcTBAAInfo1);
Nadav Rotem307d7672012-11-29 00:00:08 +000011254}
11255
Jim Laskey0463e082006-10-07 23:37:56 +000011256/// FindAliasInfo - Extracts the relevant alias information from the memory
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011257/// node. Returns true if the operand was a nonvolatile load.
Jim Laskey08edf332006-10-11 13:47:09 +000011258bool DAGCombiner::FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011259 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011260 const Value *&SrcValue,
11261 int &SrcValueOffset,
11262 unsigned &SrcValueAlign,
11263 const MDNode *&TBAAInfo) const {
11264 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11265
11266 Ptr = LS->getBasePtr();
11267 Size = LS->getMemoryVT().getSizeInBits() >> 3;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011268 IsVolatile = LS->isVolatile();
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011269 SrcValue = LS->getSrcValue();
11270 SrcValueOffset = LS->getSrcValueOffset();
11271 SrcValueAlign = LS->getOriginalAlignment();
11272 TBAAInfo = LS->getTBAAInfo();
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011273 return isa<LoadSDNode>(LS) && !IsVolatile;
Jim Laskey0463e082006-10-07 23:37:56 +000011274}
11275
Jim Laskey708d0db2006-10-04 16:53:27 +000011276/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11277/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011278void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011279 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011280 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011281 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011282
Jim Laskeyd07be232006-09-25 16:29:54 +000011283 // Get alias information for node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011284 SDValue Ptr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011285 int64_t Size;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011286 bool IsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011287 const Value *SrcValue;
11288 int SrcValueOffset;
11289 unsigned SrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011290 const MDNode *SrcTBAAInfo;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011291 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11292 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
Jim Laskeyd07be232006-09-25 16:29:54 +000011293
Jim Laskey708d0db2006-10-04 16:53:27 +000011294 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011295 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011296 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011297
Jim Laskey6549d222006-10-05 15:07:25 +000011298 // Look at each chain and determine if it is an alias. If so, add it to the
11299 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011300 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011301 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011302 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011303 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011304
11305 // For TokenFactor nodes, look at each operand and only continue up the
11306 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011307 // find more and revert to original chain since the xform is unlikely to be
11308 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011309 //
11310 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011311 // chain we found before we hit a tokenfactor rather than the original
11312 // chain.
11313 if (Depth > 6 || Aliases.size() == 2) {
11314 Aliases.clear();
11315 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011316 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011317 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011318
Nate Begeman879d8f12009-09-15 00:18:30 +000011319 // Don't bother if we've been before.
11320 if (!Visited.insert(Chain.getNode()))
11321 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011322
Jim Laskey6549d222006-10-05 15:07:25 +000011323 switch (Chain.getOpcode()) {
11324 case ISD::EntryToken:
11325 // Entry token is ideal chain operand, but handled in FindBetterChain.
11326 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011327
Jim Laskey6549d222006-10-05 15:07:25 +000011328 case ISD::LOAD:
11329 case ISD::STORE: {
11330 // Get alias information for Chain.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011331 SDValue OpPtr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011332 int64_t OpSize;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011333 bool OpIsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011334 const Value *OpSrcValue;
11335 int OpSrcValueOffset;
11336 unsigned OpSrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011337 const MDNode *OpSrcTBAAInfo;
Gabor Greiff304a7a2008-08-28 21:40:38 +000011338 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011339 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011340 OpSrcValueAlign,
11341 OpSrcTBAAInfo);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011342
Jim Laskey6549d222006-10-05 15:07:25 +000011343 // If chain is alias then stop here.
11344 if (!(IsLoad && IsOpLoad) &&
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011345 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11346 SrcValueAlign, SrcTBAAInfo,
11347 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011348 OpSrcValueAlign, OpSrcTBAAInfo)) {
Jim Laskey6549d222006-10-05 15:07:25 +000011349 Aliases.push_back(Chain);
11350 } else {
11351 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011352 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011353 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011354 }
Jim Laskey6549d222006-10-05 15:07:25 +000011355 break;
11356 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011357
Jim Laskey6549d222006-10-05 15:07:25 +000011358 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011359 // We have to check each of the operands of the token factor for "small"
11360 // token factors, so we queue them up. Adding the operands to the queue
11361 // (stack) in reverse order maintains the original order and increases the
11362 // likelihood that getNode will find a matching token factor (CSE.)
11363 if (Chain.getNumOperands() > 16) {
11364 Aliases.push_back(Chain);
11365 break;
11366 }
Jim Laskey6549d222006-10-05 15:07:25 +000011367 for (unsigned n = Chain.getNumOperands(); n;)
11368 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011369 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011370 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011371
Jim Laskey6549d222006-10-05 15:07:25 +000011372 default:
11373 // For all other instructions we will just have to take what we can get.
11374 Aliases.push_back(Chain);
11375 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011376 }
11377 }
Hal Finkel51a98382014-01-24 20:12:02 +000011378
11379 // We need to be careful here to also search for aliases through the
11380 // value operand of a store, etc. Consider the following situation:
11381 // Token1 = ...
11382 // L1 = load Token1, %52
11383 // S1 = store Token1, L1, %51
11384 // L2 = load Token1, %52+8
11385 // S2 = store Token1, L2, %51+8
11386 // Token2 = Token(S1, S2)
11387 // L3 = load Token2, %53
11388 // S3 = store Token2, L3, %52
11389 // L4 = load Token2, %53+8
11390 // S4 = store Token2, L4, %52+8
11391 // If we search for aliases of S3 (which loads address %52), and we look
11392 // only through the chain, then we'll miss the trivial dependence on L1
11393 // (which also loads from %52). We then might change all loads and
11394 // stores to use Token1 as their chain operand, which could result in
11395 // copying %53 into %52 before copying %52 into %51 (which should
11396 // happen first).
11397 //
11398 // The problem is, however, that searching for such data dependencies
11399 // can become expensive, and the cost is not directly related to the
11400 // chain depth. Instead, we'll rule out such configurations here by
11401 // insisting that we've visited all chain users (except for users
11402 // of the original chain, which is not necessary). When doing this,
11403 // we need to look through nodes we don't care about (otherwise, things
11404 // like register copies will interfere with trivial cases).
11405
11406 SmallVector<const SDNode *, 16> Worklist;
11407 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11408 IE = Visited.end(); I != IE; ++I)
11409 if (*I != OriginalChain.getNode())
11410 Worklist.push_back(*I);
11411
11412 while (!Worklist.empty()) {
11413 const SDNode *M = Worklist.pop_back_val();
11414
11415 // We have already visited M, and want to make sure we've visited any uses
11416 // of M that we care about. For uses that we've not visisted, and don't
11417 // care about, queue them to the worklist.
11418
11419 for (SDNode::use_iterator UI = M->use_begin(),
11420 UIE = M->use_end(); UI != UIE; ++UI)
11421 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11422 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11423 // We've not visited this use, and we care about it (it could have an
11424 // ordering dependency with the original node).
11425 Aliases.clear();
11426 Aliases.push_back(OriginalChain);
11427 return;
11428 }
11429
11430 // We've not visited this use, but we don't care about it. Mark it as
11431 // visited and enqueue it to the worklist.
11432 Worklist.push_back(*UI);
11433 }
11434 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011435}
11436
11437/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11438/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011439SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11440 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011441
Jim Laskey708d0db2006-10-04 16:53:27 +000011442 // Accumulate all the aliases to this node.
11443 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011444
Dan Gohman4298df62011-05-17 22:20:36 +000011445 // If no operands then chain to entry token.
11446 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011447 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011448
11449 // If a single operand then chain to it. We don't need to revisit it.
11450 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011451 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011452
Jim Laskey708d0db2006-10-04 16:53:27 +000011453 // Construct a custom tailored token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011454 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begeman879d8f12009-09-15 00:18:30 +000011455 &Aliases[0], Aliases.size());
Jim Laskeyd07be232006-09-25 16:29:54 +000011456}
11457
Nate Begeman21158fc2005-09-01 00:19:25 +000011458// SelectionDAG::Combine - This is the entry point for the file.
11459//
Bill Wendling084669a2009-04-29 00:15:41 +000011460void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011461 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011462 /// run - This is the main entry point to this class.
11463 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011464 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011465}