blob: 97885d4f3f84122518db446abe379e6e868848a3 [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
Adam Nemet67483892014-03-04 23:28:31 +0000351 /// \brief Try to transform a truncation where C is a constant:
352 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
353 ///
354 /// \p N needs to be a truncation and its first operand an AND. Other
355 /// requirements are checked by the function (e.g. that trunc is
356 /// single-use) and if missed an empty SDValue is returned.
357 SDValue distributeTruncateThroughAnd(SDNode *N);
358
Chris Lattner4041ab62010-04-15 04:48:01 +0000359 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000360 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000361 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363 AttributeSet FnAttrs =
364 DAG.getMachineFunction().getFunction()->getAttributes();
365 ForCodeSize =
366 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367 Attribute::OptimizeForSize) ||
368 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000370
Nate Begeman21158fc2005-09-01 00:19:25 +0000371 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000372 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000373
Chris Lattner4041ab62010-04-15 04:48:01 +0000374 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000375
Chris Lattner4041ab62010-04-15 04:48:01 +0000376 /// getShiftAmountTy - Returns a type large enough to hold any valid
377 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000378 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000379 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380 if (LHSTy.isVector())
381 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000382 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000384 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000385
Chris Lattner4041ab62010-04-15 04:48:01 +0000386 /// isTypeLegal - This method returns true if we are running before type
387 /// legalization or if the specified VT is legal.
388 bool isTypeLegal(const EVT &VT) {
389 if (!LegalTypes) return true;
390 return TLI.isTypeLegal(VT);
391 }
Matt Arsenault758659232013-05-18 00:21:46 +0000392
393 /// getSetCCResultType - Convenience wrapper around
394 /// TargetLowering::getSetCCResultType
395 EVT getSetCCResultType(EVT VT) const {
396 return TLI.getSetCCResultType(*DAG.getContext(), VT);
397 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000398 };
399}
400
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000401
402namespace {
403/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
404/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000405class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000406 DAGCombiner &DC;
407public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000408 explicit WorkListRemover(DAGCombiner &dc)
409 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000410
Duncan Sandsbf170802008-06-11 11:42:12 +0000411 virtual void NodeDeleted(SDNode *N, SDNode *E) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000412 DC.removeFromWorkList(N);
413 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000414};
415}
416
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000417//===----------------------------------------------------------------------===//
418// TargetLowering::DAGCombinerInfo implementation
419//===----------------------------------------------------------------------===//
420
421void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422 ((DAGCombiner*)DC)->AddToWorkList(N);
423}
424
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000425void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426 ((DAGCombiner*)DC)->removeFromWorkList(N);
427}
428
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000429SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000430CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000432}
433
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000434SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000435CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000437}
438
439
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000440SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000441CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000443}
444
Dan Gohmane58ab792009-01-29 01:59:02 +0000445void TargetLowering::DAGCombinerInfo::
446CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
448}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000449
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000450//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000451// Helper Functions
452//===----------------------------------------------------------------------===//
453
454/// isNegatibleForFree - Return 1 if we can compute the negated form of the
455/// specified expression for the same cost as the expression itself, or 2 if we
456/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000457static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000458 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000459 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000460 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000461 // fneg is removable even if it has multiple uses.
462 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000463
Chris Lattnere49c9742007-05-14 22:04:50 +0000464 // Don't allow anything with multiple uses.
465 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000466
Chris Lattner46980832007-05-25 02:19:06 +0000467 // Don't recurse exponentially.
468 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000469
Chris Lattnere49c9742007-05-14 22:04:50 +0000470 switch (Op.getOpcode()) {
471 default: return false;
472 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000473 // Don't invert constant FP values after legalize. The negated constant
474 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000475 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000476 case ISD::FADD:
477 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000478 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000479
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000480 // After operation legalization, it might not be legal to create new FSUBs.
481 if (LegalOperations &&
482 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
483 return 0;
484
Craig Topper03f39772012-09-09 22:58:45 +0000485 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000486 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
487 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000488 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000489 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000490 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000491 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000492 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000493 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000494 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000495
Bill Wendling6fbf5492009-01-30 23:10:18 +0000496 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000497 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000498
Chris Lattnere49c9742007-05-14 22:04:50 +0000499 case ISD::FMUL:
500 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000501 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000502
Bill Wendling6fbf5492009-01-30 23:10:18 +0000503 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000504 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
505 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000506 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000507
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000508 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000509 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000510
Chris Lattnere49c9742007-05-14 22:04:50 +0000511 case ISD::FP_EXTEND:
512 case ISD::FP_ROUND:
513 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000514 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000515 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000516 }
517}
518
519/// GetNegatedExpression - If isNegatibleForFree returns true, this function
520/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000521static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000522 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000523 // fneg is removable even if it has multiple uses.
524 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000525
Chris Lattnere49c9742007-05-14 22:04:50 +0000526 // Don't allow anything with multiple uses.
527 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000528
Chris Lattner46980832007-05-25 02:19:06 +0000529 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000530 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000531 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000532 case ISD::ConstantFP: {
533 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
534 V.changeSign();
535 return DAG.getConstantFP(V, Op.getValueType());
536 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000537 case ISD::FADD:
538 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000539 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000540
Bill Wendling6fbf5492009-01-30 23:10:18 +0000541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000543 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000544 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000545 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000546 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000547 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000548 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000550 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000551 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000552 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000553 Op.getOperand(0));
554 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000555 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000556 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000557
Bill Wendling6fbf5492009-01-30 23:10:18 +0000558 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000559 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000560 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000561 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562
Bill Wendling6fbf5492009-01-30 23:10:18 +0000563 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000564 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000565 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000566
Chris Lattnere49c9742007-05-14 22:04:50 +0000567 case ISD::FMUL:
568 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000569 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000570
Bill Wendling6fbf5492009-01-30 23:10:18 +0000571 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000572 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000573 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000574 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000575 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000576 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000577 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000578 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579
Bill Wendling6fbf5492009-01-30 23:10:18 +0000580 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000581 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000582 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000583 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000584 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000585
Chris Lattnere49c9742007-05-14 22:04:50 +0000586 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000587 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000588 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000589 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000590 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000591 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000592 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000593 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000594 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000595 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000596 }
597}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000598
599
Nate Begeman2504fe22005-09-01 23:24:04 +0000600// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
601// that selects between the values 1 and 0, making it equivalent to a setcc.
Scott Michelcf0da6c2009-02-17 22:15:04 +0000602// Also, set the incoming LHS, RHS, and CC references to the appropriate
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000603// nodes based on the type of node we are checking. This simplifies life a
604// bit for the callers.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000605static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
606 SDValue &CC) {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000607 if (N.getOpcode() == ISD::SETCC) {
608 LHS = N.getOperand(0);
609 RHS = N.getOperand(1);
610 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000611 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000612 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000613 if (N.getOpcode() == ISD::SELECT_CC &&
Nate Begeman21158fc2005-09-01 00:19:25 +0000614 N.getOperand(2).getOpcode() == ISD::Constant &&
615 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohmanb72127a2008-03-13 22:13:53 +0000616 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000617 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
618 LHS = N.getOperand(0);
619 RHS = N.getOperand(1);
620 CC = N.getOperand(4);
Nate Begeman21158fc2005-09-01 00:19:25 +0000621 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000622 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000623 return false;
624}
625
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000626// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
627// one use. If this is true, it allows the users to invert the operation for
628// free when it is profitable to do so.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000629static bool isOneUseSetCC(SDValue N) {
630 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000631 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000632 return true;
633 return false;
634}
635
Juergen Ributzka68402822014-01-13 21:49:25 +0000636// \brief Returns the SDNode if it is a constant BuildVector or constant int.
637static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638 if (isa<ConstantSDNode>(N))
639 return N.getNode();
640 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641 if(BV && BV->isConstant())
642 return BV;
643 return NULL;
644}
645
Andrew Trickef9de2a2013-05-25 02:42:55 +0000646SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000647 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000648 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000649 if (N0.getOpcode() == Opc) {
650 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
651 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
652 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
653 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
654 if (!OpNode.getNode())
655 return SDValue();
656 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000657 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000658 if (N0.hasOneUse()) {
659 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
660 // use
661 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
662 if (!OpNode.getNode())
663 return SDValue();
664 AddToWorkList(OpNode.getNode());
665 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000666 }
667 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000668 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000669
Juergen Ributzka68402822014-01-13 21:49:25 +0000670 if (N1.getOpcode() == Opc) {
671 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
672 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
673 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
674 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
675 if (!OpNode.getNode())
676 return SDValue();
677 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
678 }
679 if (N1.hasOneUse()) {
680 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
681 // use
682 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
683 if (!OpNode.getNode())
684 return SDValue();
685 AddToWorkList(OpNode.getNode());
686 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
687 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000688 }
689 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000690
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000691 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000692}
693
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000694SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
695 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000696 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
697 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000698 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000699 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000700 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000701 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000702 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000703 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000704 assert((!To[i].getNode() ||
705 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000706 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000707 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000708 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000709 if (AddTo) {
710 // Push the new nodes and any users onto the worklist
711 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000712 if (To[i].getNode()) {
713 AddToWorkList(To[i].getNode());
714 AddUsersToWorkList(To[i].getNode());
715 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000716 }
717 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000718
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000719 // Finally, if the node is now dead, remove it from the graph. The node
720 // may not be dead if the replacement process recursively simplified to
721 // something else needing this node.
722 if (N->use_empty()) {
723 // Nodes can be reintroduced into the worklist. Make sure we do not
724 // process a node that has been replaced.
725 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000726
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000727 // Finally, since the node is now dead, remove it from the graph.
728 DAG.DeleteNode(N);
729 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000730 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000731}
732
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000733void DAGCombiner::
734CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000735 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000736 // are deleted, make sure to remove them from our worklist.
737 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000738 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000739
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000740 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000741 AddToWorkList(TLO.New.getNode());
742 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000743
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000744 // Finally, if the node is now dead, remove it from the graph. The node
745 // may not be dead if the replacement process recursively simplified to
746 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000747 if (TLO.Old.getNode()->use_empty()) {
748 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000749
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000750 // If the operands of this node are only used by the node, they will now
751 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000752 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
753 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
754 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000755
Gabor Greiff304a7a2008-08-28 21:40:38 +0000756 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000757 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000758}
759
760/// SimplifyDemandedBits - Check the specified integer node value to see if
761/// it can be simplified or if things it uses can be simplified by bit
762/// propagation. If so, return true.
763bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000764 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000765 APInt KnownZero, KnownOne;
766 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
767 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000768
Dan Gohmane58ab792009-01-29 01:59:02 +0000769 // Revisit the node.
770 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000771
Dan Gohmane58ab792009-01-29 01:59:02 +0000772 // Replace the old value with the new one.
773 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000774 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000775 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000776 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000777 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000778 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000779
Dan Gohmane58ab792009-01-29 01:59:02 +0000780 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000781 return true;
782}
783
Evan Cheng0abb54d2010-04-24 04:43:44 +0000784void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000785 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000786 EVT VT = Load->getValueType(0);
787 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000788
Evan Cheng0abb54d2010-04-24 04:43:44 +0000789 DEBUG(dbgs() << "\nReplacing.9 ";
790 Load->dump(&DAG);
791 dbgs() << "\nWith: ";
792 Trunc.getNode()->dump(&DAG);
793 dbgs() << '\n');
794 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000795 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
796 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000797 removeFromWorkList(Load);
798 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000799 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000800}
801
802SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
803 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000804 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000806 EVT MemVT = LD->getMemoryVT();
807 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000808 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000809 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000810 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000811 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000812 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000813 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000814 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000815 }
816
Evan Chenge19aa5c2010-04-19 19:29:22 +0000817 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000818 switch (Opc) {
819 default: break;
820 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000821 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000822 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000823 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000824 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000825 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000826 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000827 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000828 case ISD::Constant: {
829 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000830 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000831 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000832 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000833 }
834
835 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000836 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000837 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000838}
839
Evan Cheng0abb54d2010-04-24 04:43:44 +0000840SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000841 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
842 return SDValue();
843 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000844 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000845 bool Replace = false;
846 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
847 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000848 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000849 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000850
851 if (Replace)
852 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
853 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000854 DAG.getValueType(OldVT));
855}
856
Evan Cheng0abb54d2010-04-24 04:43:44 +0000857SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000858 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000859 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000860 bool Replace = false;
861 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
862 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000863 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000864 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000865
866 if (Replace)
867 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
868 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000869}
870
Evan Chengaf56fac2010-04-16 06:14:10 +0000871/// PromoteIntBinOp - Promote the specified integer binary operation if the
872/// target indicates it is beneficial. e.g. On x86, it's usually better to
873/// promote i16 operations to i32 since i16 instructions are longer.
874SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
875 if (!LegalOperations)
876 return SDValue();
877
878 EVT VT = Op.getValueType();
879 if (VT.isVector() || !VT.isInteger())
880 return SDValue();
881
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000882 // If operation type is 'undesirable', e.g. i16 on x86, consider
883 // promoting it.
884 unsigned Opc = Op.getOpcode();
885 if (TLI.isTypeDesirableForOp(Opc, VT))
886 return SDValue();
887
Evan Chengaf56fac2010-04-16 06:14:10 +0000888 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000889 // Consult target whether it is a good idea to promote this operation and
890 // what's the right type to promote it to.
891 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000892 assert(PVT != VT && "Don't know what type to promote to!");
893
Evan Cheng0abb54d2010-04-24 04:43:44 +0000894 bool Replace0 = false;
895 SDValue N0 = Op.getOperand(0);
896 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
897 if (NN0.getNode() == 0)
Evan Chengf1223bd2010-04-22 20:19:46 +0000898 return SDValue();
899
Evan Cheng0abb54d2010-04-24 04:43:44 +0000900 bool Replace1 = false;
901 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000902 SDValue NN1;
903 if (N0 == N1)
904 NN1 = NN0;
905 else {
906 NN1 = PromoteOperand(N1, PVT, Replace1);
907 if (NN1.getNode() == 0)
908 return SDValue();
909 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000910
Evan Cheng0abb54d2010-04-24 04:43:44 +0000911 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000912 if (NN1.getNode())
913 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000914
915 if (Replace0)
916 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
917 if (Replace1)
918 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000919
Evan Chenge8136902010-04-27 19:48:13 +0000920 DEBUG(dbgs() << "\nPromoting ";
921 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000922 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000923 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000924 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000925 }
926 return SDValue();
927}
928
929/// PromoteIntShiftOp - Promote the specified integer shift operation if the
930/// target indicates it is beneficial. e.g. On x86, it's usually better to
931/// promote i16 operations to i32 since i16 instructions are longer.
932SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
933 if (!LegalOperations)
934 return SDValue();
935
936 EVT VT = Op.getValueType();
937 if (VT.isVector() || !VT.isInteger())
938 return SDValue();
939
940 // If operation type is 'undesirable', e.g. i16 on x86, consider
941 // promoting it.
942 unsigned Opc = Op.getOpcode();
943 if (TLI.isTypeDesirableForOp(Opc, VT))
944 return SDValue();
945
946 EVT PVT = VT;
947 // Consult target whether it is a good idea to promote this operation and
948 // what's the right type to promote it to.
949 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950 assert(PVT != VT && "Don't know what type to promote to!");
951
Evan Cheng0abb54d2010-04-24 04:43:44 +0000952 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000953 SDValue N0 = Op.getOperand(0);
954 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000955 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000956 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000957 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000958 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000959 N0 = PromoteOperand(N0, PVT, Replace);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000960 if (N0.getNode() == 0)
961 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000962
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000963 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000964 if (Replace)
965 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000966
Evan Chenge8136902010-04-27 19:48:13 +0000967 DEBUG(dbgs() << "\nPromoting ";
968 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000969 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000970 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000971 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000972 }
973 return SDValue();
974}
975
Evan Chenge19aa5c2010-04-19 19:29:22 +0000976SDValue DAGCombiner::PromoteExtend(SDValue Op) {
977 if (!LegalOperations)
978 return SDValue();
979
980 EVT VT = Op.getValueType();
981 if (VT.isVector() || !VT.isInteger())
982 return SDValue();
983
984 // If operation type is 'undesirable', e.g. i16 on x86, consider
985 // promoting it.
986 unsigned Opc = Op.getOpcode();
987 if (TLI.isTypeDesirableForOp(Opc, VT))
988 return SDValue();
989
990 EVT PVT = VT;
991 // Consult target whether it is a good idea to promote this operation and
992 // what's the right type to promote it to.
993 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
994 assert(PVT != VT && "Don't know what type to promote to!");
995 // fold (aext (aext x)) -> (aext x)
996 // fold (aext (zext x)) -> (zext x)
997 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +0000998 DEBUG(dbgs() << "\nPromoting ";
999 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001000 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001001 }
1002 return SDValue();
1003}
1004
1005bool DAGCombiner::PromoteLoad(SDValue Op) {
1006 if (!LegalOperations)
1007 return false;
1008
1009 EVT VT = Op.getValueType();
1010 if (VT.isVector() || !VT.isInteger())
1011 return false;
1012
1013 // If operation type is 'undesirable', e.g. i16 on x86, consider
1014 // promoting it.
1015 unsigned Opc = Op.getOpcode();
1016 if (TLI.isTypeDesirableForOp(Opc, VT))
1017 return false;
1018
1019 EVT PVT = VT;
1020 // Consult target whether it is a good idea to promote this operation and
1021 // what's the right type to promote it to.
1022 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023 assert(PVT != VT && "Don't know what type to promote to!");
1024
Andrew Trickef9de2a2013-05-25 02:42:55 +00001025 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001026 SDNode *N = Op.getNode();
1027 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001028 EVT MemVT = LD->getMemoryVT();
1029 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001030 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001031 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001032 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001033 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001034 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001035 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001036 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1037
Evan Cheng0abb54d2010-04-24 04:43:44 +00001038 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001039 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001040 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001041 Result.getNode()->dump(&DAG);
1042 dbgs() << '\n');
1043 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001044 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1045 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001046 removeFromWorkList(N);
1047 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001048 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001049 return true;
1050 }
1051 return false;
1052}
1053
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001054
Chris Lattnere49c9742007-05-14 22:04:50 +00001055//===----------------------------------------------------------------------===//
1056// Main DAG Combiner implementation
1057//===----------------------------------------------------------------------===//
1058
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001059void DAGCombiner::Run(CombineLevel AtLevel) {
1060 // set the instance variables, so that the various visit routines may use it.
1061 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001062 LegalOperations = Level >= AfterLegalizeVectorOps;
1063 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001064
Evan Cheng5e7658c2008-08-29 22:21:44 +00001065 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001066 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1067 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001068 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001069
Evan Cheng5e7658c2008-08-29 22:21:44 +00001070 // Create a dummy node (which is not added to allnodes), that adds a reference
1071 // to the root node, preventing it from being deleted, and tracking any
1072 // changes of the root.
1073 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001074
Jim Laskeye7d2c242006-10-17 19:33:52 +00001075 // The root of the dag may dangle to deleted nodes until the dag combiner is
1076 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001077 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001078
James Molloy67b6b112012-02-16 09:17:04 +00001079 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001080 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001081 while (!WorkListContents.empty()) {
1082 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001083 // The WorkListOrder holds the SDNodes in order, but it may contain
1084 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001085 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1086 // worklist *should* contain, and check the node we want to visit is should
1087 // actually be visited.
1088 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001089 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001090 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001091
Evan Cheng5e7658c2008-08-29 22:21:44 +00001092 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1093 // N is deleted from the DAG, since they too may now be dead or may have a
1094 // reduced number of uses, allowing other xforms.
1095 if (N->use_empty() && N != &Dummy) {
1096 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1097 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001098
Evan Cheng5e7658c2008-08-29 22:21:44 +00001099 DAG.DeleteNode(N);
1100 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001101 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001102
Evan Cheng5e7658c2008-08-29 22:21:44 +00001103 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001104
Evan Cheng5e7658c2008-08-29 22:21:44 +00001105 if (RV.getNode() == 0)
1106 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001107
Evan Cheng5e7658c2008-08-29 22:21:44 +00001108 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001109
Evan Cheng5e7658c2008-08-29 22:21:44 +00001110 // If we get back the same node we passed in, rather than a new node or
1111 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001112 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001113 // mechanics for us, we have no work to do in this case.
1114 if (RV.getNode() == N)
1115 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001116
Evan Cheng5e7658c2008-08-29 22:21:44 +00001117 assert(N->getOpcode() != ISD::DELETED_NODE &&
1118 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1119 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001120
Wesley Peck527da1b2010-11-23 03:31:01 +00001121 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001122 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001123 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001124 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001125 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001126
Devang Patelefec7712011-05-23 22:04:42 +00001127 // Transfer debug value.
1128 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001129 WorkListRemover DeadNodes(*this);
1130 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001131 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001132 else {
1133 assert(N->getValueType(0) == RV.getValueType() &&
1134 N->getNumValues() == 1 && "Type mismatch");
1135 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001136 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001137 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001138
Evan Cheng5e7658c2008-08-29 22:21:44 +00001139 // Push the new node and any users onto the worklist
1140 AddToWorkList(RV.getNode());
1141 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001142
Evan Cheng5e7658c2008-08-29 22:21:44 +00001143 // Add any uses of the old node to the worklist in case this node is the
1144 // last one that uses them. They may become dead after this node is
1145 // deleted.
1146 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1147 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001148
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001149 // Finally, if the node is now dead, remove it from the graph. The node
1150 // may not be dead if the replacement process recursively simplified to
1151 // something else needing this node.
1152 if (N->use_empty()) {
1153 // Nodes can be reintroduced into the worklist. Make sure we do not
1154 // process a node that has been replaced.
1155 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001156
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001157 // Finally, since the node is now dead, remove it from the graph.
1158 DAG.DeleteNode(N);
1159 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001160 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001161
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001162 // If the root changed (e.g. it was a dead load, update the root).
1163 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001164 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001165}
1166
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001167SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001168 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001169 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001170 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001171 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001172 case ISD::ADD: return visitADD(N);
1173 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001174 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001175 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001176 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001177 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001178 case ISD::MUL: return visitMUL(N);
1179 case ISD::SDIV: return visitSDIV(N);
1180 case ISD::UDIV: return visitUDIV(N);
1181 case ISD::SREM: return visitSREM(N);
1182 case ISD::UREM: return visitUREM(N);
1183 case ISD::MULHU: return visitMULHU(N);
1184 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001185 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1186 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001187 case ISD::SMULO: return visitSMULO(N);
1188 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001189 case ISD::SDIVREM: return visitSDIVREM(N);
1190 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001191 case ISD::AND: return visitAND(N);
1192 case ISD::OR: return visitOR(N);
1193 case ISD::XOR: return visitXOR(N);
1194 case ISD::SHL: return visitSHL(N);
1195 case ISD::SRA: return visitSRA(N);
1196 case ISD::SRL: return visitSRL(N);
1197 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001198 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001199 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001200 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001201 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001202 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001203 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001204 case ISD::SELECT_CC: return visitSELECT_CC(N);
1205 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001206 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1207 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001208 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001209 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1210 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001211 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001212 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001213 case ISD::FADD: return visitFADD(N);
1214 case ISD::FSUB: return visitFSUB(N);
1215 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001216 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001217 case ISD::FDIV: return visitFDIV(N);
1218 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001219 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001220 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1221 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1222 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1223 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1224 case ISD::FP_ROUND: return visitFP_ROUND(N);
1225 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1226 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1227 case ISD::FNEG: return visitFNEG(N);
1228 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001229 case ISD::FFLOOR: return visitFFLOOR(N);
1230 case ISD::FCEIL: return visitFCEIL(N);
1231 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001232 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001233 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001234 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001235 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001236 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001237 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001238 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1239 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001240 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001241 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001242 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001243 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001244 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001245}
1246
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001247SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001248 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001249
1250 // If nothing happened, try a target-specific DAG combine.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001251 if (RV.getNode() == 0) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001252 assert(N->getOpcode() != ISD::DELETED_NODE &&
1253 "Node was deleted but visit returned NULL!");
1254
1255 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1256 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1257
1258 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001259 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001260 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001261
1262 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1263 }
1264 }
1265
Evan Chengf1005572010-04-28 07:10:39 +00001266 // If nothing happened still, try promoting the operation.
1267 if (RV.getNode() == 0) {
1268 switch (N->getOpcode()) {
1269 default: break;
1270 case ISD::ADD:
1271 case ISD::SUB:
1272 case ISD::MUL:
1273 case ISD::AND:
1274 case ISD::OR:
1275 case ISD::XOR:
1276 RV = PromoteIntBinOp(SDValue(N, 0));
1277 break;
1278 case ISD::SHL:
1279 case ISD::SRA:
1280 case ISD::SRL:
1281 RV = PromoteIntShiftOp(SDValue(N, 0));
1282 break;
1283 case ISD::SIGN_EXTEND:
1284 case ISD::ZERO_EXTEND:
1285 case ISD::ANY_EXTEND:
1286 RV = PromoteExtend(SDValue(N, 0));
1287 break;
1288 case ISD::LOAD:
1289 if (PromoteLoad(SDValue(N, 0)))
1290 RV = SDValue(N, 0);
1291 break;
1292 }
1293 }
1294
Scott Michelcf0da6c2009-02-17 22:15:04 +00001295 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001296 // sdisel CSE.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001297 if (RV.getNode() == 0 &&
Evan Cheng31604a62008-03-22 01:55:50 +00001298 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1299 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001300 SDValue N0 = N->getOperand(0);
1301 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001302
Evan Cheng31604a62008-03-22 01:55:50 +00001303 // Constant operands are canonicalized to RHS.
1304 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001305 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001306 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1307 Ops, 2);
Evan Chengfe7610f2008-03-24 23:55:16 +00001308 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001309 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001310 }
1311 }
1312
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001313 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001314}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001315
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001316/// getInputChainForNode - Given a node, return its input chain if it has one,
1317/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001318static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001319 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001320 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001321 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001322 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001323 return N->getOperand(NumOps-1);
1324 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001325 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001326 return N->getOperand(i);
1327 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001328 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001329}
1330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001331SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001332 // If N has two operands, where one has an input chain equal to the other,
1333 // the 'other' chain is redundant.
1334 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001335 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001336 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001337 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001338 return N->getOperand(1);
1339 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001340
Chris Lattner48fb92f2007-05-16 06:37:59 +00001341 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001342 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001343 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001344 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001345
Jim Laskey708d0db2006-10-04 16:53:27 +00001346 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001347 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001348
Jim Laskey0463e082006-10-07 23:37:56 +00001349 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001350 // encountered.
1351 for (unsigned i = 0; i < TFs.size(); ++i) {
1352 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001353
Jim Laskey708d0db2006-10-04 16:53:27 +00001354 // Check each of the operands.
1355 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001356 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001357
Jim Laskey708d0db2006-10-04 16:53:27 +00001358 switch (Op.getOpcode()) {
1359 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001360 // Entry tokens don't need to be added to the list. They are
1361 // rededundant.
1362 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001363 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001364
Jim Laskey708d0db2006-10-04 16:53:27 +00001365 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001366 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001367 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001368 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001369 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001370 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001371 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001372 Changed = true;
1373 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001374 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001375 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001376
Jim Laskey708d0db2006-10-04 16:53:27 +00001377 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001378 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001379 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001380 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001381 else
1382 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001383 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001384 }
1385 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001386 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001387
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001388 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001389
1390 // If we've change things around then replace token factor.
1391 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001392 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001393 // The entry token is the only possible outcome.
1394 Result = DAG.getEntryNode();
1395 } else {
1396 // New and improved token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001397 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00001398 MVT::Other, &Ops[0], Ops.size());
Nate Begeman02b23c62005-10-13 03:11:28 +00001399 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001400
Jim Laskeydcf983c2006-10-13 23:32:28 +00001401 // Don't add users to work list.
1402 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001403 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001404
Jim Laskey708d0db2006-10-04 16:53:27 +00001405 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001406}
1407
Chris Lattneree322b42008-02-13 07:25:05 +00001408/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001409SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001410 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001411 // Replacing results may cause a different MERGE_VALUES to suddenly
1412 // be CSE'd with N, and carry its uses with it. Iterate until no
1413 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001414 // First add the users of this node to the work list so that they
1415 // can be tried again once they have new operands.
1416 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001417 do {
1418 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001419 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001420 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001421 removeFromWorkList(N);
1422 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001423 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001424}
1425
Evan Cheng92011002007-01-19 17:51:44 +00001426static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001427SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001428 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001429 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001430 SDValue N00 = N0.getOperand(0);
1431 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001432 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001433
Gabor Greiff304a7a2008-08-28 21:40:38 +00001434 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001435 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001436 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001437 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1438 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001439 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001440 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001441 N00.getOperand(1), N01));
1442 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001443 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001445 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001446}
1447
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001448SDValue DAGCombiner::visitADD(SDNode *N) {
1449 SDValue N0 = N->getOperand(0);
1450 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001451 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1452 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001453 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001454
1455 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001456 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001457 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001458 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001459
1460 // fold (add x, 0) -> x, vector edition
1461 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1462 return N0;
1463 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1464 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001465 }
Bill Wendling0864a752008-12-10 22:36:00 +00001466
Dan Gohman06563a82007-07-03 14:03:57 +00001467 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001468 if (N0.getOpcode() == ISD::UNDEF)
1469 return N0;
1470 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001471 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001472 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001473 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001474 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001475 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001476 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001477 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001478 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001479 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001480 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001481 // fold (add Sym, c) -> Sym+c
1482 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001483 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001484 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001485 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001486 GA->getOffset() +
1487 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001488 // fold ((c1-A)+c2) -> (c1+c2)-A
1489 if (N1C && N0.getOpcode() == ISD::SUB)
1490 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001491 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001492 DAG.getConstant(N1C->getAPIntValue()+
1493 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001494 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001495 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001496 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001497 if (RADD.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001498 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001499 // fold ((0-A) + B) -> B-A
1500 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1501 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001502 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001503 // fold (A + (0-B)) -> A-B
1504 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1505 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001506 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001507 // fold (A+(B-A)) -> B
1508 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001509 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001510 // fold ((B-A)+A) -> B
1511 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1512 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001513 // fold (A+(B-(A+C))) to (B-C)
1514 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001515 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001516 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001517 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001518 // fold (A+(B-(C+A))) to (B-C)
1519 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001520 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001521 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001522 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001523 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001524 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1525 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001526 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001527 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001528 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001529
Dale Johannesen8c766702008-12-02 01:30:54 +00001530 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1531 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1532 SDValue N00 = N0.getOperand(0);
1533 SDValue N01 = N0.getOperand(1);
1534 SDValue N10 = N1.getOperand(0);
1535 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001536
1537 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001538 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1539 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1540 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001541 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001542
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001543 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1544 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001545
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001546 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001547 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001548 APInt LHSZero, LHSOne;
1549 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001550 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001551
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001552 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001553 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001554
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001555 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1556 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001557 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1558 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1559 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1560 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001561 }
1562 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001563
Evan Cheng92011002007-01-19 17:51:44 +00001564 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001565 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001566 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001567 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001568 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001569 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001570 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001571 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001572 }
1573
Dan Gohman954f4902010-01-19 23:30:49 +00001574 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1575 if (N1.getOpcode() == ISD::SHL &&
1576 N1.getOperand(0).getOpcode() == ISD::SUB)
1577 if (ConstantSDNode *C =
1578 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1579 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001580 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1581 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001582 N1.getOperand(0).getOperand(1),
1583 N1.getOperand(1)));
1584 if (N0.getOpcode() == ISD::SHL &&
1585 N0.getOperand(0).getOpcode() == ISD::SUB)
1586 if (ConstantSDNode *C =
1587 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1588 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001589 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1590 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001591 N0.getOperand(0).getOperand(1),
1592 N0.getOperand(1)));
1593
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001594 if (N1.getOpcode() == ISD::AND) {
1595 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001596 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001597 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1598 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001599
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001600 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1601 // and similar xforms where the inner op is either ~0 or 0.
1602 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001603 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001604 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1605 }
1606 }
1607
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001608 // add (sext i1), X -> sub X, (zext i1)
1609 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1610 N0.getOperand(0).getValueType() == MVT::i1 &&
1611 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001612 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001613 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1614 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1615 }
1616
Evan Chengf1005572010-04-28 07:10:39 +00001617 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001618}
1619
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001620SDValue DAGCombiner::visitADDC(SDNode *N) {
1621 SDValue N0 = N->getOperand(0);
1622 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001623 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1624 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001625 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001626
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001627 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001628 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001629 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001630 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001631 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001632
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001633 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001634 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001635 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001636
Chris Lattner47206662007-03-04 20:40:38 +00001637 // fold (addc x, 0) -> x + no carry out
1638 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001639 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001640 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001641
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001642 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001643 APInt LHSZero, LHSOne;
1644 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001645 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001646
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001647 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001648 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001649
Chris Lattner47206662007-03-04 20:40:38 +00001650 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1651 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001652 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001653 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001654 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001655 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001656 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001657
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001658 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001659}
1660
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001661SDValue DAGCombiner::visitADDE(SDNode *N) {
1662 SDValue N0 = N->getOperand(0);
1663 SDValue N1 = N->getOperand(1);
1664 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001665 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1666 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001667
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001668 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001669 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001670 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001671 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001672
Chris Lattner47206662007-03-04 20:40:38 +00001673 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001674 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001675 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001676
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001677 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001678}
1679
Eric Christophere5ca1e02011-02-16 04:50:12 +00001680// Since it may not be valid to emit a fold to zero for vector initializers
1681// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001682static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001683 SelectionDAG &DAG,
1684 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001685 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001686 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001687 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1688 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001689 return SDValue();
1690}
1691
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001692SDValue DAGCombiner::visitSUB(SDNode *N) {
1693 SDValue N0 = N->getOperand(0);
1694 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001697 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1698 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001699 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001700
Dan Gohmana8665142007-06-25 16:23:39 +00001701 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001702 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001703 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001704 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001705
1706 // fold (sub x, 0) -> x, vector edition
1707 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1708 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001709 }
Bill Wendling0864a752008-12-10 22:36:00 +00001710
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001711 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001712 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001713 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001714 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001715 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001716 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001717 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001718 // fold (sub x, c) -> (add x, -c)
1719 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001720 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001721 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001722 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1723 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001724 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001725 // fold A-(A-B) -> B
1726 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1727 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001728 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001729 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001730 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001731 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001732 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001733 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001734 // fold C2-(A+C1) -> (C2-C1)-A
1735 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001736 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1737 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001738 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001739 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001740 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001741 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001742 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001743 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1744 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001745 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001746 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001747 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001748 // fold ((A+(C+B))-B) -> A+C
1749 if (N0.getOpcode() == ISD::ADD &&
1750 N0.getOperand(1).getOpcode() == ISD::ADD &&
1751 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001752 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001753 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001754 // fold ((A-(B-C))-C) -> A-B
1755 if (N0.getOpcode() == ISD::SUB &&
1756 N0.getOperand(1).getOpcode() == ISD::SUB &&
1757 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001758 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001759 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001760
Dan Gohman06563a82007-07-03 14:03:57 +00001761 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001762 if (N0.getOpcode() == ISD::UNDEF)
1763 return N0;
1764 if (N1.getOpcode() == ISD::UNDEF)
1765 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001766
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001767 // If the relocation model supports it, consider symbol offsets.
1768 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001769 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001770 // fold (sub Sym, c) -> Sym-c
1771 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001772 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001773 GA->getOffset() -
1774 (uint64_t)N1C->getSExtValue());
1775 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1776 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1777 if (GA->getGlobal() == GB->getGlobal())
1778 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1779 VT);
1780 }
1781
Evan Chengf1005572010-04-28 07:10:39 +00001782 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001783}
1784
Craig Topper43a1bd62012-01-07 09:06:39 +00001785SDValue DAGCombiner::visitSUBC(SDNode *N) {
1786 SDValue N0 = N->getOperand(0);
1787 SDValue N1 = N->getOperand(1);
1788 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1789 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1790 EVT VT = N0.getValueType();
1791
1792 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001793 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001794 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1795 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001796 MVT::Glue));
1797
1798 // fold (subc x, x) -> 0 + no borrow
1799 if (N0 == N1)
1800 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001801 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001802 MVT::Glue));
1803
1804 // fold (subc x, 0) -> x + no borrow
1805 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001806 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001807 MVT::Glue));
1808
1809 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1810 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001811 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1812 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001813 MVT::Glue));
1814
1815 return SDValue();
1816}
1817
1818SDValue DAGCombiner::visitSUBE(SDNode *N) {
1819 SDValue N0 = N->getOperand(0);
1820 SDValue N1 = N->getOperand(1);
1821 SDValue CarryIn = N->getOperand(2);
1822
1823 // fold (sube x, y, false) -> (subc x, y)
1824 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001825 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001826
1827 return SDValue();
1828}
1829
Jack Carterd4e96152013-10-17 01:34:33 +00001830/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1831/// elements are all the same constant or undefined.
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001832static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1833 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1834 if (!C)
1835 return false;
1836
1837 APInt SplatUndef;
1838 unsigned SplatBitSize;
1839 bool HasAnyUndefs;
1840 EVT EltVT = N->getValueType(0).getVectorElementType();
1841 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1842 HasAnyUndefs) &&
1843 EltVT.getSizeInBits() >= SplatBitSize);
1844}
1845
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001846SDValue DAGCombiner::visitMUL(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001849 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001850
Dan Gohman06563a82007-07-03 14:03:57 +00001851 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001852 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001853 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001854
1855 bool N0IsConst = false;
1856 bool N1IsConst = false;
1857 APInt ConstValue0, ConstValue1;
1858 // fold vector ops
1859 if (VT.isVector()) {
1860 SDValue FoldedVOp = SimplifyVBinOp(N);
1861 if (FoldedVOp.getNode()) return FoldedVOp;
1862
1863 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1864 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1865 } else {
1866 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001867 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1868 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001869 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001870 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1871 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001872 }
1873
Nate Begeman21158fc2005-09-01 00:19:25 +00001874 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001875 if (N0IsConst && N1IsConst)
1876 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1877
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001878 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001879 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001880 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001881 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001882 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001883 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001884 // We require a splat of the entire scalar bit width for non-contiguous
1885 // bit patterns.
1886 bool IsFullSplat =
1887 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001888 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001889 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001890 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001891 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001892 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001893 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001894 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001895 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001896 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001897 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001898 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001899 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001900 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001901 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001902 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001903 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001904 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001906 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001907 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001908 DAG.getConstant(Log2Val,
1909 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001910 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001911
1912 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001913 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001914 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001915 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1916 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001917 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001918 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001919 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001920 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001921 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001922 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001923
Chris Lattner324871e2006-03-01 03:44:24 +00001924 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1925 // use.
1926 {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001927 SDValue Sh(0,0), Y(0,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001928 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001929 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001930 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001932 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001933 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001934 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001935 isa<ConstantSDNode>(N1.getOperand(1)) &&
1936 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001937 Sh = N1; Y = N0;
1938 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001939
Gabor Greiff304a7a2008-08-28 21:40:38 +00001940 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001941 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001942 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001943 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001944 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001945 }
1946 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001947
Chris Lattnerf29f5202006-03-04 23:33:26 +00001948 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001949 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1950 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1951 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001952 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1953 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001954 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001955 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001956 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001957
Nate Begeman22e251a2006-02-03 06:46:56 +00001958 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001959 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001960 if (RMUL.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001961 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001962
Evan Chengf1005572010-04-28 07:10:39 +00001963 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001964}
1965
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001966SDValue DAGCombiner::visitSDIV(SDNode *N) {
1967 SDValue N0 = N->getOperand(0);
1968 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001969 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1970 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001971 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001972
Dan Gohmana8665142007-06-25 16:23:39 +00001973 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001974 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001975 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001976 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001977 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001978
Nate Begeman21158fc2005-09-01 00:19:25 +00001979 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001980 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001981 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001982 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001983 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001984 return N0;
1985 // fold (sdiv X, -1) -> 0-X
1986 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001987 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00001988 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00001989 // If we know the sign bits of both operands are zero, strength reduce to a
1990 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00001991 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00001992 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001993 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00001994 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00001995 }
Nate Begeman57b35672006-02-17 07:26:20 +00001996 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedmanf9081a82011-12-07 03:55:52 +00001997 if (N1C && !N1C->isNullValue() &&
Eli Friedmane9e356a2011-10-27 02:06:39 +00001998 (N1C->getAPIntValue().isPowerOf2() ||
1999 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002000 // If dividing by powers of two is cheap, then don't perform the following
2001 // fold.
2002 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002003 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002004
Eli Friedmane9e356a2011-10-27 02:06:39 +00002005 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002006
Chris Lattner471627c2006-02-16 08:02:36 +00002007 // Splat the sign bit into the register
Andrew Trickef9de2a2013-05-25 02:42:55 +00002008 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling5b663e72009-01-30 02:52:17 +00002009 DAG.getConstant(VT.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002010 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002011 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002012
Chris Lattner471627c2006-02-16 08:02:36 +00002013 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002014 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling5b663e72009-01-30 02:52:17 +00002015 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002016 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002017 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002018 AddToWorkList(SRL.getNode());
2019 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002020 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002021 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002022
Nate Begeman4dd38312005-10-21 00:02:42 +00002023 // If we're dividing by a positive value, we're done. Otherwise, we must
2024 // negate the result.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002025 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002026 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002027
Gabor Greiff304a7a2008-08-28 21:40:38 +00002028 AddToWorkList(SRA.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002029 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002030 DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002031 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002032
Nate Begemanc6f067a2005-10-20 02:15:44 +00002033 // if integer divide is expensive and we satisfy the requirements, emit an
2034 // alternate sequence.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002035 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002036 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002037 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002038 }
Dan Gohmana8665142007-06-25 16:23:39 +00002039
Dan Gohman06563a82007-07-03 14:03:57 +00002040 // undef / X -> 0
2041 if (N0.getOpcode() == ISD::UNDEF)
2042 return DAG.getConstant(0, VT);
2043 // X / undef -> undef
2044 if (N1.getOpcode() == ISD::UNDEF)
2045 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002046
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002047 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002048}
2049
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002050SDValue DAGCombiner::visitUDIV(SDNode *N) {
2051 SDValue N0 = N->getOperand(0);
2052 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002053 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2054 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00002055 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002056
Dan Gohmana8665142007-06-25 16:23:39 +00002057 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002058 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002059 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002060 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002061 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002062
Nate Begeman21158fc2005-09-01 00:19:25 +00002063 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002064 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002065 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002066 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002067 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002068 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002069 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002070 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002071 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002072 if (N1.getOpcode() == ISD::SHL) {
2073 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002074 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002075 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002076 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002077 N1.getOperand(1),
2078 DAG.getConstant(SHC->getAPIntValue()
2079 .logBase2(),
2080 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002081 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002082 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002083 }
2084 }
2085 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002086 // fold (udiv x, c) -> alternate
Dan Gohmanb72127a2008-03-13 22:13:53 +00002087 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002088 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002089 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002090 }
Dan Gohmana8665142007-06-25 16:23:39 +00002091
Dan Gohman06563a82007-07-03 14:03:57 +00002092 // undef / X -> 0
2093 if (N0.getOpcode() == ISD::UNDEF)
2094 return DAG.getConstant(0, VT);
2095 // X / undef -> undef
2096 if (N1.getOpcode() == ISD::UNDEF)
2097 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002098
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002099 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002100}
2101
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002102SDValue DAGCombiner::visitSREM(SDNode *N) {
2103 SDValue N0 = N->getOperand(0);
2104 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002105 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2106 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002107 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002108
Nate Begeman21158fc2005-09-01 00:19:25 +00002109 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002110 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002111 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002112 // If we know the sign bits of both operands are zero, strength reduce to a
2113 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002114 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002115 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002116 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002117 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002118
Dan Gohman9a693412007-11-26 23:46:11 +00002119 // If X/C can be simplified by the division-by-constant logic, lower
2120 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002121 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002122 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002123 AddToWorkList(Div.getNode());
2124 SDValue OptimizedDiv = combine(Div.getNode());
2125 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002126 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002127 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002128 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002129 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002130 return Sub;
2131 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002132 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002133
Dan Gohman06563a82007-07-03 14:03:57 +00002134 // undef % X -> 0
2135 if (N0.getOpcode() == ISD::UNDEF)
2136 return DAG.getConstant(0, VT);
2137 // X % undef -> undef
2138 if (N1.getOpcode() == ISD::UNDEF)
2139 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002140
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002141 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002142}
2143
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002144SDValue DAGCombiner::visitUREM(SDNode *N) {
2145 SDValue N0 = N->getOperand(0);
2146 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002147 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2148 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002149 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002150
Nate Begeman21158fc2005-09-01 00:19:25 +00002151 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002152 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002153 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002154 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002155 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002156 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002157 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002158 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2159 if (N1.getOpcode() == ISD::SHL) {
2160 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002161 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002162 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002163 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002164 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002165 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002166 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002167 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002168 }
2169 }
2170 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002171
Dan Gohman9a693412007-11-26 23:46:11 +00002172 // If X/C can be simplified by the division-by-constant logic, lower
2173 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002174 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002175 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002176 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002177 SDValue OptimizedDiv = combine(Div.getNode());
2178 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002179 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002180 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002181 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002182 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002183 return Sub;
2184 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002185 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002186
Dan Gohman06563a82007-07-03 14:03:57 +00002187 // undef % X -> 0
2188 if (N0.getOpcode() == ISD::UNDEF)
2189 return DAG.getConstant(0, VT);
2190 // X % undef -> undef
2191 if (N1.getOpcode() == ISD::UNDEF)
2192 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002193
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002194 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002195}
2196
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002197SDValue DAGCombiner::visitMULHS(SDNode *N) {
2198 SDValue N0 = N->getOperand(0);
2199 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002201 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002202 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002203
Nate Begeman21158fc2005-09-01 00:19:25 +00002204 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002205 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002206 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002207 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002208 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002209 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002210 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002211 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002212 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002213 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002214 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002215
Chris Lattner10bd29f2010-12-13 08:39:01 +00002216 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2217 // plus a shift.
2218 if (VT.isSimple() && !VT.isVector()) {
2219 MVT Simple = VT.getSimpleVT();
2220 unsigned SimpleSize = Simple.getSizeInBits();
2221 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2222 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2223 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2224 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2225 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002226 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002227 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002228 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2229 }
2230 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002231
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002232 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002233}
2234
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002235SDValue DAGCombiner::visitMULHU(SDNode *N) {
2236 SDValue N0 = N->getOperand(0);
2237 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002238 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002239 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002240 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002241
Nate Begeman21158fc2005-09-01 00:19:25 +00002242 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002243 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002244 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002245 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002246 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002247 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002248 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002249 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002250 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002251
Chris Lattner10bd29f2010-12-13 08:39:01 +00002252 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2253 // plus a shift.
2254 if (VT.isSimple() && !VT.isVector()) {
2255 MVT Simple = VT.getSimpleVT();
2256 unsigned SimpleSize = Simple.getSizeInBits();
2257 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2258 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2259 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2260 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2261 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2262 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002263 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002264 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2265 }
2266 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002267
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002268 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002269}
2270
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002271/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2272/// compute two values. LoOp and HiOp give the opcodes for the two computations
2273/// that are being performed. Return true if a simplification was made.
2274///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002275SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002276 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002277 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002278 bool HiExists = N->hasAnyUseOfValue(1);
2279 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002280 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002281 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002282 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002283 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002284 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002285 }
2286
2287 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002288 bool LoExists = N->hasAnyUseOfValue(0);
2289 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002290 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002291 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002292 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002293 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002294 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002295 }
2296
Evan Chengece4c682007-11-08 09:25:29 +00002297 // If both halves are used, return as it is.
2298 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002299 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002300
2301 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002302 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002303 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002304 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002305 AddToWorkList(Lo.getNode());
2306 SDValue LoOpt = combine(Lo.getNode());
2307 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002308 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002309 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002310 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002311 }
2312
Evan Chengece4c682007-11-08 09:25:29 +00002313 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002314 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002315 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002316 AddToWorkList(Hi.getNode());
2317 SDValue HiOpt = combine(Hi.getNode());
2318 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002319 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002320 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002321 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002322 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002323
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002324 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002325}
2326
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002327SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2328 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002329 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002330
Chris Lattner15090e12010-12-15 06:04:19 +00002331 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002332 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002333
2334 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2335 // plus a shift.
2336 if (VT.isSimple() && !VT.isVector()) {
2337 MVT Simple = VT.getSimpleVT();
2338 unsigned SimpleSize = Simple.getSizeInBits();
2339 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2340 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2341 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2342 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2343 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2344 // Compute the high part as N1.
2345 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002346 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002347 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2348 // Compute the low part as N0.
2349 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2350 return CombineTo(N, Lo, Hi);
2351 }
2352 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002354 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002355}
2356
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002357SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2358 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002359 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002360
Chris Lattner15090e12010-12-15 06:04:19 +00002361 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002362 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002363
Chris Lattner15090e12010-12-15 06:04:19 +00002364 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2365 // plus a shift.
2366 if (VT.isSimple() && !VT.isVector()) {
2367 MVT Simple = VT.getSimpleVT();
2368 unsigned SimpleSize = Simple.getSizeInBits();
2369 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2370 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2371 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2372 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2373 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2374 // Compute the high part as N1.
2375 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002376 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002377 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2378 // Compute the low part as N0.
2379 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2380 return CombineTo(N, Lo, Hi);
2381 }
2382 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002383
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002384 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002385}
2386
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002387SDValue DAGCombiner::visitSMULO(SDNode *N) {
2388 // (smulo x, 2) -> (saddo x, x)
2389 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2390 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002391 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002392 N->getOperand(0), N->getOperand(0));
2393
2394 return SDValue();
2395}
2396
2397SDValue DAGCombiner::visitUMULO(SDNode *N) {
2398 // (umulo x, 2) -> (uaddo x, x)
2399 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2400 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002401 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002402 N->getOperand(0), N->getOperand(0));
2403
2404 return SDValue();
2405}
2406
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002407SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2408 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002409 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002410
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002411 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002412}
2413
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002414SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2415 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002416 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002417
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002418 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002419}
2420
Chris Lattner8d6fc202006-05-05 05:51:50 +00002421/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2422/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002423SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2424 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002425 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002426 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002427
Dan Gohmandd5286d2010-01-14 03:08:49 +00002428 // Bail early if none of these transforms apply.
2429 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2430
Chris Lattner002ee912006-05-05 06:31:05 +00002431 // For each of OP in AND/OR/XOR:
2432 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2433 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2434 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002435 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002436 //
2437 // do not sink logical op inside of a vector extend, since it may combine
2438 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002439 EVT Op0VT = N0.getOperand(0).getValueType();
2440 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002441 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002442 // Avoid infinite looping with PromoteIntBinOp.
2443 (N0.getOpcode() == ISD::ANY_EXTEND &&
2444 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002445 (N0.getOpcode() == ISD::TRUNCATE &&
2446 (!TLI.isZExtFree(VT, Op0VT) ||
2447 !TLI.isTruncateFree(Op0VT, VT)) &&
2448 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002449 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002450 Op0VT == N1.getOperand(0).getValueType() &&
2451 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002452 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002453 N0.getOperand(0).getValueType(),
2454 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002455 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002456 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002457 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002458
Chris Lattner5ac42932006-05-05 06:10:43 +00002459 // For each of OP in SHL/SRL/SRA/AND...
2460 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2461 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2462 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002463 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002464 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002465 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002466 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002467 N0.getOperand(0).getValueType(),
2468 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002469 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002470 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002471 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002473
Nadav Rotemb0783502012-04-01 19:31:22 +00002474 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2475 // Only perform this optimization after type legalization and before
2476 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2477 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2478 // we don't want to undo this promotion.
2479 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2480 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002481 if ((N0.getOpcode() == ISD::BITCAST ||
2482 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2483 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002484 SDValue In0 = N0.getOperand(0);
2485 SDValue In1 = N1.getOperand(0);
2486 EVT In0Ty = In0.getValueType();
2487 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002488 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002489 // If both incoming values are integers, and the original types are the
2490 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002491 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002492 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2493 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002494 AddToWorkList(Op.getNode());
2495 return BC;
2496 }
2497 }
2498
2499 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2500 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2501 // If both shuffles use the same mask, and both shuffle within a single
2502 // vector, then it is worthwhile to move the swizzle after the operation.
2503 // The type-legalizer generates this pattern when loading illegal
2504 // vector types from memory. In many cases this allows additional shuffle
2505 // optimizations.
Craig Topper9c3da312012-04-09 07:19:09 +00002506 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2507 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2508 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002509 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2510 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002511
2512 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2513 "Inputs to shuffles are not the same type");
Nadav Rotemb0783502012-04-01 19:31:22 +00002514
2515 unsigned NumElts = VT.getVectorNumElements();
Nadav Rotemb0783502012-04-01 19:31:22 +00002516
2517 // Check that both shuffles use the same mask. The masks are known to be of
2518 // the same length because the result vector type is the same.
2519 bool SameMask = true;
2520 for (unsigned i = 0; i != NumElts; ++i) {
2521 int Idx0 = SVN0->getMaskElt(i);
2522 int Idx1 = SVN1->getMaskElt(i);
2523 if (Idx0 != Idx1) {
2524 SameMask = false;
2525 break;
2526 }
2527 }
2528
Craig Topper9c3da312012-04-09 07:19:09 +00002529 if (SameMask) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002530 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
Craig Topper9c3da312012-04-09 07:19:09 +00002531 N0.getOperand(0), N1.getOperand(0));
Nadav Rotemb0783502012-04-01 19:31:22 +00002532 AddToWorkList(Op.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002533 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
Craig Topper9c3da312012-04-09 07:19:09 +00002534 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
Nadav Rotemb0783502012-04-01 19:31:22 +00002535 }
2536 }
Craig Topper9c3da312012-04-09 07:19:09 +00002537
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002538 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002539}
2540
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002541SDValue DAGCombiner::visitAND(SDNode *N) {
2542 SDValue N0 = N->getOperand(0);
2543 SDValue N1 = N->getOperand(1);
2544 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002545 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002547 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002548 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002549
Dan Gohmana8665142007-06-25 16:23:39 +00002550 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002551 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002552 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002553 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002554
2555 // fold (and x, 0) -> 0, vector edition
2556 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2557 return N0;
2558 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2559 return N1;
2560
2561 // fold (and x, -1) -> x, vector edition
2562 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2563 return N1;
2564 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2565 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002566 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002567
Dan Gohman06563a82007-07-03 14:03:57 +00002568 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002569 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002570 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002571 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002572 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002573 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002574 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002575 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002576 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002577 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002578 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002579 return N0;
2580 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002581 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002582 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002583 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002584 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002585 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002586 if (RAND.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00002587 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002588 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002589 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002590 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002591 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002592 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002593 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2594 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002595 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002596 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002597 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002598 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002599 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002600 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002601
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002602 // Replace uses of the AND with uses of the Zero extend node.
2603 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002604
Chris Lattner49beaf42006-02-02 07:17:31 +00002605 // We actually want to replace all uses of the any_extend with the
2606 // zero_extend, to avoid duplicating things. This will later cause this
2607 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002608 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002609 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002610 }
2611 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002612 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002613 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2614 // already be zero by virtue of the width of the base type of the load.
2615 //
2616 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2617 // more cases.
2618 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2619 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2620 N0.getOpcode() == ISD::LOAD) {
2621 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2622 N0 : N0.getOperand(0) );
2623
2624 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2625 // This can be a pure constant or a vector splat, in which case we treat the
2626 // vector as a scalar and use the splat value.
2627 APInt Constant = APInt::getNullValue(1);
2628 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2629 Constant = C->getAPIntValue();
2630 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2631 APInt SplatValue, SplatUndef;
2632 unsigned SplatBitSize;
2633 bool HasAnyUndefs;
2634 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2635 SplatBitSize, HasAnyUndefs);
2636 if (IsSplat) {
2637 // Undef bits can contribute to a possible optimisation if set, so
2638 // set them.
2639 SplatValue |= SplatUndef;
2640
2641 // The splat value may be something like "0x00FFFFFF", which means 0 for
2642 // the first vector value and FF for the rest, repeating. We need a mask
2643 // that will apply equally to all members of the vector, so AND all the
2644 // lanes of the constant together.
2645 EVT VT = Vector->getValueType(0);
2646 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002647
2648 // If the splat value has been compressed to a bitlength lower
2649 // than the size of the vector lane, we need to re-expand it to
2650 // the lane size.
2651 if (BitWidth > SplatBitSize)
2652 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2653 SplatBitSize < BitWidth;
2654 SplatBitSize = SplatBitSize * 2)
2655 SplatValue |= SplatValue.shl(SplatBitSize);
2656
James Molloy862fe492012-02-20 12:02:38 +00002657 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002658 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002659 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2660 }
2661 }
2662
2663 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2664 // actually legal and isn't going to get expanded, else this is a false
2665 // optimisation.
2666 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2667 Load->getMemoryVT());
2668
2669 // Resize the constant to the same size as the original memory access before
2670 // extension. If it is still the AllOnesValue then this AND is completely
2671 // unneeded.
2672 Constant =
2673 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2674
2675 bool B;
2676 switch (Load->getExtensionType()) {
2677 default: B = false; break;
2678 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2679 case ISD::ZEXTLOAD:
2680 case ISD::NON_EXTLOAD: B = true; break;
2681 }
2682
2683 if (B && Constant.isAllOnesValue()) {
2684 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2685 // preserve semantics once we get rid of the AND.
2686 SDValue NewLoad(Load, 0);
2687 if (Load->getExtensionType() == ISD::EXTLOAD) {
2688 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002689 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002690 Load->getChain(), Load->getBasePtr(),
2691 Load->getOffset(), Load->getMemoryVT(),
2692 Load->getMemOperand());
2693 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002694 if (Load->getNumValues() == 3) {
2695 // PRE/POST_INC loads have 3 values.
2696 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2697 NewLoad.getValue(2) };
2698 CombineTo(Load, To, 3, true);
2699 } else {
2700 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2701 }
James Molloy862fe492012-02-20 12:02:38 +00002702 }
2703
2704 // Fold the AND away, taking care not to fold to the old load node if we
2705 // replaced it.
2706 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2707
2708 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2709 }
2710 }
Nate Begeman049b7482005-09-09 19:49:52 +00002711 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2712 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2713 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2714 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002715
Nate Begeman049b7482005-09-09 19:49:52 +00002716 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002717 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002718 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002719 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002720 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002721 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002722 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002723 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002724 }
Bill Wendling86171912009-01-30 20:43:18 +00002725 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002727 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002728 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002729 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002730 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002731 }
Bill Wendling86171912009-01-30 20:43:18 +00002732 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002733 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002734 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002735 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002736 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002737 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002738 }
2739 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002740 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2741 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2742 Op0 == Op1 && LL.getValueType().isInteger() &&
2743 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2744 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2745 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2746 cast<ConstantSDNode>(RR)->isNullValue()))) {
2747 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2748 LL, DAG.getConstant(1, LL.getValueType()));
2749 AddToWorkList(ADDNode.getNode());
2750 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2751 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2752 }
Nate Begeman049b7482005-09-09 19:49:52 +00002753 // canonicalize equivalent to ll == rl
2754 if (LL == RR && LR == RL) {
2755 Op1 = ISD::getSetCCSwappedOperands(Op1);
2756 std::swap(RL, RR);
2757 }
2758 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002759 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002760 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002761 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002762 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002763 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2764 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002765 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002766 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002767 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002768 }
2769 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002770
Bill Wendling86171912009-01-30 20:43:18 +00002771 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002772 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002773 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002774 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002775 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002776
Nate Begemandc7bba92006-02-03 22:24:05 +00002777 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2778 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002779 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002780 SimplifyDemandedBits(SDValue(N, 0)))
2781 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002782
Nate Begeman02b23c62005-10-13 03:11:28 +00002783 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002784 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002785 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002786 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002787 // If we zero all the possible extended bits, then we can turn this into
2788 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002789 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002790 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002791 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002792 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002793 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002794 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002795 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002796 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002797 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002798 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002799 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002800 }
2801 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002802 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002803 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002804 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002806 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002807 // If we zero all the possible extended bits, then we can turn this into
2808 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002809 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002810 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002811 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002812 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002813 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002814 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002815 LN0->getChain(), LN0->getBasePtr(),
2816 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002817 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002818 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002820 }
2821 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002822
Chris Lattnerf0032b32006-02-28 06:49:37 +00002823 // fold (and (load x), 255) -> (zextload x, i8)
2824 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002825 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2826 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2827 (N0.getOpcode() == ISD::ANY_EXTEND &&
2828 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2829 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2830 LoadSDNode *LN0 = HasAnyExt
2831 ? cast<LoadSDNode>(N0.getOperand(0))
2832 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002833 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002834 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002835 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002836 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2837 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2838 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002839
Evan Cheng166a4e62010-01-06 19:38:29 +00002840 if (ExtVT == LoadedVT &&
2841 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002842 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002843
2844 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002845 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002846 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2847 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002848 AddToWorkList(N);
2849 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2850 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2851 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002852
Chris Lattner88de3842010-01-07 21:53:27 +00002853 // Do not change the width of a volatile load.
2854 // Do not generate loads of non-round integer types since these can
2855 // be expensive (and would be wrong if the type is not byte sized).
2856 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2857 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2858 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002859
Chris Lattner88de3842010-01-07 21:53:27 +00002860 unsigned Alignment = LN0->getAlignment();
2861 SDValue NewPtr = LN0->getBasePtr();
2862
2863 // For big endian targets, we need to add an offset to the pointer
2864 // to load the correct bytes. For little endian systems, we merely
2865 // need to read fewer bytes from the same pointer.
2866 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002867 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2868 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2869 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002870 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002871 NewPtr, DAG.getConstant(PtrOff, PtrType));
2872 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002873 }
Chris Lattner88de3842010-01-07 21:53:27 +00002874
2875 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002876
Chris Lattner88de3842010-01-07 21:53:27 +00002877 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2878 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002879 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002880 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002881 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002882 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002883 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002884 AddToWorkList(N);
2885 CombineTo(LN0, Load, Load.getValue(1));
2886 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002887 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002888 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002889 }
2890 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002891
Evan Chenge6a3b032012-07-17 18:54:11 +00002892 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2893 VT.getSizeInBits() <= 64) {
2894 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2895 APInt ADDC = ADDI->getAPIntValue();
2896 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2897 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2898 // immediate for an add, but it is legal if its top c2 bits are set,
2899 // transform the ADD so the immediate doesn't need to be materialized
2900 // in a register.
2901 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2902 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2903 SRLI->getZExtValue());
2904 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2905 ADDC |= Mask;
2906 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2907 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002908 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002909 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2910 CombineTo(N0.getNode(), NewAdd);
2911 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2912 }
2913 }
2914 }
2915 }
2916 }
2917 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002918
Tim Northover819bfb52013-08-27 13:46:45 +00002919 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2920 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2921 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2922 N0.getOperand(1), false);
2923 if (BSwap.getNode())
2924 return BSwap;
2925 }
2926
Evan Chengf1005572010-04-28 07:10:39 +00002927 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002928}
2929
Evan Cheng4c0bd962011-06-21 06:01:08 +00002930/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2931///
2932SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2933 bool DemandHighBits) {
2934 if (!LegalOperations)
2935 return SDValue();
2936
2937 EVT VT = N->getValueType(0);
2938 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2939 return SDValue();
2940 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2941 return SDValue();
2942
2943 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2944 bool LookPassAnd0 = false;
2945 bool LookPassAnd1 = false;
2946 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2947 std::swap(N0, N1);
2948 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2949 std::swap(N0, N1);
2950 if (N0.getOpcode() == ISD::AND) {
2951 if (!N0.getNode()->hasOneUse())
2952 return SDValue();
2953 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2954 if (!N01C || N01C->getZExtValue() != 0xFF00)
2955 return SDValue();
2956 N0 = N0.getOperand(0);
2957 LookPassAnd0 = true;
2958 }
2959
2960 if (N1.getOpcode() == ISD::AND) {
2961 if (!N1.getNode()->hasOneUse())
2962 return SDValue();
2963 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2964 if (!N11C || N11C->getZExtValue() != 0xFF)
2965 return SDValue();
2966 N1 = N1.getOperand(0);
2967 LookPassAnd1 = true;
2968 }
2969
2970 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2971 std::swap(N0, N1);
2972 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2973 return SDValue();
2974 if (!N0.getNode()->hasOneUse() ||
2975 !N1.getNode()->hasOneUse())
2976 return SDValue();
2977
2978 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2979 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2980 if (!N01C || !N11C)
2981 return SDValue();
2982 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2983 return SDValue();
2984
2985 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2986 SDValue N00 = N0->getOperand(0);
2987 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2988 if (!N00.getNode()->hasOneUse())
2989 return SDValue();
2990 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2991 if (!N001C || N001C->getZExtValue() != 0xFF)
2992 return SDValue();
2993 N00 = N00.getOperand(0);
2994 LookPassAnd0 = true;
2995 }
2996
2997 SDValue N10 = N1->getOperand(0);
2998 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2999 if (!N10.getNode()->hasOneUse())
3000 return SDValue();
3001 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3002 if (!N101C || N101C->getZExtValue() != 0xFF00)
3003 return SDValue();
3004 N10 = N10.getOperand(0);
3005 LookPassAnd1 = true;
3006 }
3007
3008 if (N00 != N10)
3009 return SDValue();
3010
Tim Northover819bfb52013-08-27 13:46:45 +00003011 // Make sure everything beyond the low halfword gets set to zero since the SRL
3012 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003013 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003014 if (DemandHighBits && OpSizeInBits > 16) {
3015 // If the left-shift isn't masked out then the only way this is a bswap is
3016 // if all bits beyond the low 8 are 0. In that case the entire pattern
3017 // reduces to a left shift anyway: leave it for other parts of the combiner.
3018 if (!LookPassAnd0)
3019 return SDValue();
3020
3021 // However, if the right shift isn't masked out then it might be because
3022 // it's not needed. See if we can spot that too.
3023 if (!LookPassAnd1 &&
3024 !DAG.MaskedValueIsZero(
3025 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3026 return SDValue();
3027 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003028
Andrew Trickef9de2a2013-05-25 02:42:55 +00003029 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003030 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003031 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003032 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3033 return Res;
3034}
3035
3036/// isBSwapHWordElement - Return true if the specified node is an element
3037/// that makes up a 32-bit packed halfword byteswap. i.e.
3038/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003039static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003040 if (!N.getNode()->hasOneUse())
3041 return false;
3042
3043 unsigned Opc = N.getOpcode();
3044 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3045 return false;
3046
3047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3048 if (!N1C)
3049 return false;
3050
3051 unsigned Num;
3052 switch (N1C->getZExtValue()) {
3053 default:
3054 return false;
3055 case 0xFF: Num = 0; break;
3056 case 0xFF00: Num = 1; break;
3057 case 0xFF0000: Num = 2; break;
3058 case 0xFF000000: Num = 3; break;
3059 }
3060
3061 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3062 SDValue N0 = N.getOperand(0);
3063 if (Opc == ISD::AND) {
3064 if (Num == 0 || Num == 2) {
3065 // (x >> 8) & 0xff
3066 // (x >> 8) & 0xff0000
3067 if (N0.getOpcode() != ISD::SRL)
3068 return false;
3069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3070 if (!C || C->getZExtValue() != 8)
3071 return false;
3072 } else {
3073 // (x << 8) & 0xff00
3074 // (x << 8) & 0xff000000
3075 if (N0.getOpcode() != ISD::SHL)
3076 return false;
3077 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 if (!C || C->getZExtValue() != 8)
3079 return false;
3080 }
3081 } else if (Opc == ISD::SHL) {
3082 // (x & 0xff) << 8
3083 // (x & 0xff0000) << 8
3084 if (Num != 0 && Num != 2)
3085 return false;
3086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3087 if (!C || C->getZExtValue() != 8)
3088 return false;
3089 } else { // Opc == ISD::SRL
3090 // (x & 0xff00) >> 8
3091 // (x & 0xff000000) >> 8
3092 if (Num != 1 && Num != 3)
3093 return false;
3094 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3095 if (!C || C->getZExtValue() != 8)
3096 return false;
3097 }
3098
3099 if (Parts[Num])
3100 return false;
3101
3102 Parts[Num] = N0.getOperand(0).getNode();
3103 return true;
3104}
3105
3106/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3107/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3108/// => (rotl (bswap x), 16)
3109SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3110 if (!LegalOperations)
3111 return SDValue();
3112
3113 EVT VT = N->getValueType(0);
3114 if (VT != MVT::i32)
3115 return SDValue();
3116 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3117 return SDValue();
3118
3119 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3120 // Look for either
3121 // (or (or (and), (and)), (or (and), (and)))
3122 // (or (or (or (and), (and)), (and)), (and))
3123 if (N0.getOpcode() != ISD::OR)
3124 return SDValue();
3125 SDValue N00 = N0.getOperand(0);
3126 SDValue N01 = N0.getOperand(1);
3127
Evan Chengbf0baa92012-12-13 01:34:32 +00003128 if (N1.getOpcode() == ISD::OR &&
3129 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003130 // (or (or (and), (and)), (or (and), (and)))
3131 SDValue N000 = N00.getOperand(0);
3132 if (!isBSwapHWordElement(N000, Parts))
3133 return SDValue();
3134
3135 SDValue N001 = N00.getOperand(1);
3136 if (!isBSwapHWordElement(N001, Parts))
3137 return SDValue();
3138 SDValue N010 = N01.getOperand(0);
3139 if (!isBSwapHWordElement(N010, Parts))
3140 return SDValue();
3141 SDValue N011 = N01.getOperand(1);
3142 if (!isBSwapHWordElement(N011, Parts))
3143 return SDValue();
3144 } else {
3145 // (or (or (or (and), (and)), (and)), (and))
3146 if (!isBSwapHWordElement(N1, Parts))
3147 return SDValue();
3148 if (!isBSwapHWordElement(N01, Parts))
3149 return SDValue();
3150 if (N00.getOpcode() != ISD::OR)
3151 return SDValue();
3152 SDValue N000 = N00.getOperand(0);
3153 if (!isBSwapHWordElement(N000, Parts))
3154 return SDValue();
3155 SDValue N001 = N00.getOperand(1);
3156 if (!isBSwapHWordElement(N001, Parts))
3157 return SDValue();
3158 }
3159
3160 // Make sure the parts are all coming from the same node.
3161 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3162 return SDValue();
3163
Andrew Trickef9de2a2013-05-25 02:42:55 +00003164 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003165 SDValue(Parts[0],0));
3166
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003167 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003168 // do (x << 16) | (x >> 16).
3169 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3170 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003171 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003172 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003173 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3174 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3175 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3176 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003177}
3178
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003179SDValue DAGCombiner::visitOR(SDNode *N) {
3180 SDValue N0 = N->getOperand(0);
3181 SDValue N1 = N->getOperand(1);
3182 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003183 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3184 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003185 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003186
Dan Gohmana8665142007-06-25 16:23:39 +00003187 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003188 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003189 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003190 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003191
3192 // fold (or x, 0) -> x, vector edition
3193 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3194 return N1;
3195 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3196 return N0;
3197
3198 // fold (or x, -1) -> -1, vector edition
3199 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3200 return N0;
3201 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3202 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003203
3204 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3205 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3206 // Do this only if the resulting shuffle is legal.
3207 if (isa<ShuffleVectorSDNode>(N0) &&
3208 isa<ShuffleVectorSDNode>(N1) &&
3209 N0->getOperand(1) == N1->getOperand(1) &&
3210 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3211 bool CanFold = true;
3212 unsigned NumElts = VT.getVectorNumElements();
3213 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3214 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3215 // We construct two shuffle masks:
3216 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3217 // and N1 as the second operand.
3218 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3219 // and N0 as the second operand.
3220 // We do this because OR is commutable and therefore there might be
3221 // two ways to fold this node into a shuffle.
3222 SmallVector<int,4> Mask1;
3223 SmallVector<int,4> Mask2;
3224
3225 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3226 int M0 = SV0->getMaskElt(i);
3227 int M1 = SV1->getMaskElt(i);
3228
3229 // Both shuffle indexes are undef. Propagate Undef.
3230 if (M0 < 0 && M1 < 0) {
3231 Mask1.push_back(M0);
3232 Mask2.push_back(M0);
3233 continue;
3234 }
3235
3236 if (M0 < 0 || M1 < 0 ||
3237 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3238 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3239 CanFold = false;
3240 break;
3241 }
3242
3243 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3244 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3245 }
3246
3247 if (CanFold) {
3248 // Fold this sequence only if the resulting shuffle is 'legal'.
3249 if (TLI.isShuffleMaskLegal(Mask1, VT))
3250 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3251 N1->getOperand(0), &Mask1[0]);
3252 if (TLI.isShuffleMaskLegal(Mask2, VT))
3253 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3254 N0->getOperand(0), &Mask2[0]);
3255 }
3256 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003257 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003258
Dan Gohman06563a82007-07-03 14:03:57 +00003259 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003260 if (!LegalOperations &&
3261 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003262 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3263 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3264 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003265 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003266 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003267 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003268 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003269 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003270 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003271 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003272 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003273 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003274 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003275 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003276 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003277 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003278 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003279 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003280
3281 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3282 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3283 if (BSwap.getNode() != 0)
3284 return BSwap;
3285 BSwap = MatchBSwapHWordLow(N, N0, N1);
3286 if (BSwap.getNode() != 0)
3287 return BSwap;
3288
Nate Begeman22e251a2006-02-03 06:46:56 +00003289 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003290 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003291 if (ROR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003292 return ROR;
3293 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003294 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003295 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003296 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003297 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003298 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3299 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3300 if (!COR.getNode())
3301 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003302 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3303 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003304 N0.getOperand(0), N1), COR);
3305 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003306 }
Nate Begeman049b7482005-09-09 19:49:52 +00003307 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3308 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3309 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3310 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003311
Nate Begeman049b7482005-09-09 19:49:52 +00003312 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003313 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003314 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3315 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003316 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003317 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003318 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003319 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003320 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003321 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003322 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003323 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3324 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003325 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003326 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003327 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003328 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003329 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003330 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003331 }
3332 }
3333 // canonicalize equivalent to ll == rl
3334 if (LL == RR && LR == RL) {
3335 Op1 = ISD::getSetCCSwappedOperands(Op1);
3336 std::swap(RL, RR);
3337 }
3338 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003339 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003340 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003341 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003342 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003343 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3344 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003345 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003346 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003347 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003348 }
3349 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003350
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003351 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003352 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003353 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003354 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003355 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003356
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003357 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003358 if (N0.getOpcode() == ISD::AND &&
3359 N1.getOpcode() == ISD::AND &&
3360 N0.getOperand(1).getOpcode() == ISD::Constant &&
3361 N1.getOperand(1).getOpcode() == ISD::Constant &&
3362 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003363 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003364 // We can only do this xform if we know that bits from X that are set in C2
3365 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003366 const APInt &LHSMask =
3367 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3368 const APInt &RHSMask =
3369 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003370
Dan Gohman309d3d52007-06-22 14:59:07 +00003371 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3372 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003373 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003374 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003375 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003376 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003377 }
3378 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003379
Chris Lattner97614c82006-09-14 20:50:57 +00003380 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003381 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003382 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003383
Dan Gohman600f62b2010-06-24 14:30:44 +00003384 // Simplify the operands using demanded-bits information.
3385 if (!VT.isVector() &&
3386 SimplifyDemandedBits(SDValue(N, 0)))
3387 return SDValue(N, 0);
3388
Evan Chengf1005572010-04-28 07:10:39 +00003389 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003390}
3391
Chris Lattner97614c82006-09-14 20:50:57 +00003392/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003393static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003394 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003395 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003396 Mask = Op.getOperand(1);
3397 Op = Op.getOperand(0);
3398 } else {
3399 return false;
3400 }
3401 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003402
Chris Lattner97614c82006-09-14 20:50:57 +00003403 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3404 Shift = Op;
3405 return true;
3406 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003407
Scott Michelcf0da6c2009-02-17 22:15:04 +00003408 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003409}
3410
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003411// Return true if we can prove that, whenever Neg and Pos are both in the
3412// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003413// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3414//
3415// (or (shift1 X, Neg), (shift2 X, Pos))
3416//
Adam Nemetc6553a82014-03-07 23:56:24 +00003417// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3418// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3419// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003420static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003421 // If OpSize is a power of 2 then:
3422 //
3423 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3424 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3425 //
3426 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3427 // for the stronger condition:
3428 //
3429 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3430 //
3431 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3432 // we can just replace Neg with Neg' for the rest of the function.
3433 //
3434 // In other cases we check for the even stronger condition:
3435 //
3436 // Neg == OpSize - Pos [B]
3437 //
3438 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3439 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003440 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003441 // We could actually use [A] whenever OpSize is a power of 2, but the
3442 // only extra cases that it would match are those uninteresting ones
3443 // where Neg and Pos are never in range at the same time. E.g. for
3444 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3445 // as well as (sub 32, Pos), but:
3446 //
3447 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3448 //
3449 // always invokes undefined behavior for 32-bit X.
3450 //
3451 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003452 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003453 if (Neg.getOpcode() == ISD::AND &&
3454 isPowerOf2_64(OpSize) &&
3455 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3456 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3457 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003458 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003459 }
3460
Richard Sandiford0f264db2014-01-09 10:49:40 +00003461 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3462 if (Neg.getOpcode() != ISD::SUB)
3463 return 0;
3464 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3465 if (!NegC)
3466 return 0;
3467 SDValue NegOp1 = Neg.getOperand(1);
3468
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003469 // The condition we need is now:
3470 //
3471 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3472 //
3473 // If NegOp1 == Pos then we need:
3474 //
3475 // OpSize & Mask == NegC & Mask
3476 //
3477 // (because "x & Mask" is a truncation and distributes through subtraction).
3478 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003479 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003480 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003481 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3482 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003483 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003484 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3485 //
3486 // which, again because "x & Mask" is a truncation, becomes:
3487 //
3488 // NegC & Mask == (OpSize - PosC) & Mask
3489 // OpSize & Mask == (NegC + PosC) & Mask
3490 else if (Pos.getOpcode() == ISD::ADD &&
3491 Pos.getOperand(0) == NegOp1 &&
3492 Pos.getOperand(1).getOpcode() == ISD::Constant)
3493 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3494 NegC->getAPIntValue());
3495 else
3496 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003497
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003498 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003499 if (MaskLoBits)
3500 // Opsize & Mask is 0 since Mask is Opsize - 1.
3501 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003502 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003503}
3504
Richard Sandiford95c864d2014-01-08 15:40:47 +00003505// A subroutine of MatchRotate used once we have found an OR of two opposite
3506// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3507// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3508// former being preferred if supported. InnerPos and InnerNeg are Pos and
3509// Neg with outer conversions stripped away.
3510SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3511 SDValue Neg, SDValue InnerPos,
3512 SDValue InnerNeg, unsigned PosOpcode,
3513 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003514 // fold (or (shl x, (*ext y)),
3515 // (srl x, (*ext (sub 32, y)))) ->
3516 // (rotl x, y) or (rotr x, (sub 32, y))
3517 //
3518 // fold (or (shl x, (*ext (sub 32, y))),
3519 // (srl x, (*ext y))) ->
3520 // (rotr x, y) or (rotl x, (sub 32, y))
3521 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003522 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003523 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3524 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3525 HasPos ? Pos : Neg).getNode();
3526 }
3527
3528 // fold (or (shl (*ext x), (*ext y)),
3529 // (srl (*ext x), (*ext (sub 32, y)))) ->
3530 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3531 //
3532 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3533 // (srl (*ext x), (*ext y))) ->
3534 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3535 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3536 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3537 SDValue InnerShifted = Shifted.getOperand(0);
3538 EVT InnerVT = InnerShifted.getValueType();
3539 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3540 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
Richard Sandiford0f264db2014-01-09 10:49:40 +00003541 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003542 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3543 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3544 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3545 }
3546 }
3547 }
3548
3549 return 0;
3550}
3551
Chris Lattner97614c82006-09-14 20:50:57 +00003552// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3553// idioms for rotate, and if the target supports rotation instructions, generate
3554// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003555SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003556 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003557 EVT VT = LHS.getValueType();
Chris Lattner97614c82006-09-14 20:50:57 +00003558 if (!TLI.isTypeLegal(VT)) return 0;
3559
3560 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003561 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3562 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Chris Lattner97614c82006-09-14 20:50:57 +00003563 if (!HasROTL && !HasROTR) return 0;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003564
Chris Lattner97614c82006-09-14 20:50:57 +00003565 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003566 SDValue LHSShift; // The shift.
3567 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003568 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3569 return 0; // Not part of a rotate.
3570
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003571 SDValue RHSShift; // The shift.
3572 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003573 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3574 return 0; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003575
Chris Lattner97614c82006-09-14 20:50:57 +00003576 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3577 return 0; // Not shifting the same value.
3578
3579 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3580 return 0; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003581
Chris Lattner97614c82006-09-14 20:50:57 +00003582 // Canonicalize shl to left side in a shl/srl pair.
3583 if (RHSShift.getOpcode() == ISD::SHL) {
3584 std::swap(LHS, RHS);
3585 std::swap(LHSShift, RHSShift);
3586 std::swap(LHSMask , RHSMask );
3587 }
3588
Duncan Sands13237ac2008-06-06 12:08:01 +00003589 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003590 SDValue LHSShiftArg = LHSShift.getOperand(0);
3591 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003592 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003593 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003594
3595 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3596 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003597 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3598 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003599 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3600 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003601 if ((LShVal + RShVal) != OpSizeInBits)
3602 return 0;
3603
Craig Topper65161fa2012-09-29 06:54:22 +00003604 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3605 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003606
Chris Lattner97614c82006-09-14 20:50:57 +00003607 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003608 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003609 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003610
Gabor Greiff304a7a2008-08-28 21:40:38 +00003611 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003612 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3613 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003614 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003615 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003616 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3617 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003618 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003619
Bill Wendling35972a92009-01-30 21:14:50 +00003620 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003621 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003622
Gabor Greiff304a7a2008-08-28 21:40:38 +00003623 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003624 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003625
Chris Lattner97614c82006-09-14 20:50:57 +00003626 // If there is a mask here, and we have a variable shift, we can't be sure
3627 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003628 if (LHSMask.getNode() || RHSMask.getNode())
Chris Lattner97614c82006-09-14 20:50:57 +00003629 return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003630
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003631 // If the shift amount is sign/zext/any-extended just peel it off.
3632 SDValue LExtOp0 = LHSShiftAmt;
3633 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003634 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3635 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3636 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3637 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3638 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3639 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3640 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3641 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003642 LExtOp0 = LHSShiftAmt.getOperand(0);
3643 RExtOp0 = RHSShiftAmt.getOperand(0);
3644 }
3645
Richard Sandiford95c864d2014-01-08 15:40:47 +00003646 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3647 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3648 if (TryL)
3649 return TryL;
3650
3651 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3652 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3653 if (TryR)
3654 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003655
Chris Lattner97614c82006-09-14 20:50:57 +00003656 return 0;
3657}
3658
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003659SDValue DAGCombiner::visitXOR(SDNode *N) {
3660 SDValue N0 = N->getOperand(0);
3661 SDValue N1 = N->getOperand(1);
3662 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003663 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3664 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003665 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003666
Dan Gohmana8665142007-06-25 16:23:39 +00003667 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003668 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003669 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003670 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003671
3672 // fold (xor x, 0) -> x, vector edition
3673 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3674 return N1;
3675 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3676 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003677 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003678
Evan Chengdf1690d2008-03-25 20:08:07 +00003679 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3680 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3681 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003682 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003683 if (N0.getOpcode() == ISD::UNDEF)
3684 return N0;
3685 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003686 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003687 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003688 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003689 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003690 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003691 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003692 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003693 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003694 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003695 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003696 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003697 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003698 if (RXOR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003699 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003700
Nate Begeman21158fc2005-09-01 00:19:25 +00003701 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003702 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003703 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003704 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3705 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003706
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003707 if (!LegalOperations ||
3708 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003709 switch (N0.getOpcode()) {
3710 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003711 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003712 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003713 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003714 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003715 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003716 N0.getOperand(3), NotCC);
3717 }
3718 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003719 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003720
Chris Lattner58c227b2007-09-10 21:39:07 +00003721 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003722 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003723 N0.getNode()->hasOneUse() &&
3724 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003725 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003726 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003727 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003728 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003729 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003730 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003731
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003732 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003733 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003734 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003735 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003736 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3737 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003738 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3739 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003740 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003741 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003742 }
3743 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003744 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003745 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003746 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003747 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003748 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3749 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003750 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3751 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003752 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003753 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003754 }
3755 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003756 // fold (xor (and x, y), y) -> (and (not x), y)
3757 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003758 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003759 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003760 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003761 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003762 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003763 }
Bill Wendling35972a92009-01-30 21:14:50 +00003764 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003765 if (N1C && N0.getOpcode() == ISD::XOR) {
3766 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3767 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3768 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003769 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003770 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003771 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003772 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003773 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003774 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003775 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003776 }
3777 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003778 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003779 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003780
Chris Lattner8d6fc202006-05-05 05:51:50 +00003781 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3782 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003783 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003784 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003785 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003786
Chris Lattner098c01e2006-04-08 04:15:24 +00003787 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003788 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003789 SimplifyDemandedBits(SDValue(N, 0)))
3790 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003791
Evan Chengf1005572010-04-28 07:10:39 +00003792 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003793}
3794
Chris Lattner7c709a52007-12-06 07:33:36 +00003795/// visitShiftByConstant - Handle transforms common to the three shifts, when
3796/// the shift amount is a constant.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003797SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003798 assert(isa<ConstantSDNode>(N->getOperand(1)) &&
3799 "Expected an ConstantSDNode operand.");
3800 // We can't and shouldn't fold opaque constants.
3801 if (cast<ConstantSDNode>(N->getOperand(1))->isOpaque())
3802 return SDValue();
3803
Gabor Greiff304a7a2008-08-28 21:40:38 +00003804 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003805 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003806
Chris Lattner7c709a52007-12-06 07:33:36 +00003807 // We want to pull some binops through shifts, so that we have (and (shift))
3808 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3809 // thing happens with address calculations, so it's important to canonicalize
3810 // it.
3811 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003812
Chris Lattner7c709a52007-12-06 07:33:36 +00003813 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003814 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003815 case ISD::OR:
3816 case ISD::XOR:
3817 HighBitSet = false; // We can only transform sra if the high bit is clear.
3818 break;
3819 case ISD::AND:
3820 HighBitSet = true; // We can only transform sra if the high bit is set.
3821 break;
3822 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003823 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003824 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003825 HighBitSet = false; // We can only transform sra if the high bit is clear.
3826 break;
3827 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003828
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003829 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003830 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003831 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003832
3833 // FIXME: disable this unless the input to the binop is a shift by a constant.
3834 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003835 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003836 // void foo(int *X, int i) { X[i & 1235] = 1; }
3837 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003838 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003839 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003840 BinOpLHSVal->getOpcode() != ISD::SRA &&
3841 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3842 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003843 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003844
Owen Anderson53aa7a92009-08-10 22:56:29 +00003845 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003846
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003847 // If this is a signed shift right, and the high bit is modified by the
3848 // logical operation, do not perform the transformation. The highBitSet
3849 // boolean indicates the value of the high bit of the constant which would
3850 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003851 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003852 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3853 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003854 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003855 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003856
Chris Lattner7c709a52007-12-06 07:33:36 +00003857 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003858 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003859 N->getValueType(0),
3860 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003861 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003862
3863 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003864 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003865 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003866 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003867
3868 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003869 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003870}
3871
Adam Nemet67483892014-03-04 23:28:31 +00003872SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3873 assert(N->getOpcode() == ISD::TRUNCATE);
3874 assert(N->getOperand(0).getOpcode() == ISD::AND);
3875
3876 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3877 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3878 SDValue N01 = N->getOperand(0).getOperand(1);
3879
3880 if (ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01)) {
3881 EVT TruncVT = N->getValueType(0);
3882 SDValue N00 = N->getOperand(0).getOperand(0);
3883 APInt TruncC = N01C->getAPIntValue();
3884 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3885
3886 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3887 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3888 DAG.getConstant(TruncC, TruncVT));
3889 }
3890 }
3891
3892 return SDValue();
3893}
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003894SDValue DAGCombiner::visitSHL(SDNode *N) {
3895 SDValue N0 = N->getOperand(0);
3896 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003897 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3898 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003899 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00003900 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003901
Daniel Sandersa1840d22013-11-11 17:23:41 +00003902 // fold vector ops
3903 if (VT.isVector()) {
3904 SDValue FoldedVOp = SimplifyVBinOp(N);
3905 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003906
3907 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3908 // If setcc produces all-one true value then:
3909 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3910 if (N1CV && N1CV->isConstant() &&
3911 TLI.getBooleanContents(true) ==
3912 TargetLowering::ZeroOrNegativeOneBooleanContent &&
3913 N0.getOpcode() == ISD::AND) {
3914 SDValue N00 = N0->getOperand(0);
3915 SDValue N01 = N0->getOperand(1);
3916 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3917
3918 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3919 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3920 if (C.getNode())
3921 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3922 }
3923 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003924 }
3925
Nate Begeman21158fc2005-09-01 00:19:25 +00003926 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003927 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003928 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003929 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003930 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003931 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003932 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003933 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003934 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003935 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003936 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003937 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003938 // fold (shl undef, x) -> 0
3939 if (N0.getOpcode() == ISD::UNDEF)
3940 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003941 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003942 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003943 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003944 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003945 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003946 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00003947 N1.getOperand(0).getOpcode() == ISD::AND) {
3948 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3949 if (NewOp1.getNode())
3950 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003951 }
3952
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003953 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3954 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003955
3956 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Scott Michelcf0da6c2009-02-17 22:15:04 +00003957 if (N1C && N0.getOpcode() == ISD::SHL &&
Nate Begeman21158fc2005-09-01 00:19:25 +00003958 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003959 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3960 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00003961 if (c1 + c2 >= OpSizeInBits)
Nate Begemand23739d2005-09-06 04:43:02 +00003962 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003963 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Nate Begemand23739d2005-09-06 04:43:02 +00003964 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman21158fc2005-09-01 00:19:25 +00003965 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00003966
3967 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3968 // For this to be valid, the second form must not preserve any of the bits
3969 // that are shifted out by the inner shift in the first form. This means
3970 // the outer shift size must be >= the number of bits added by the ext.
3971 // As a corollary, we don't care what kind of ext it is.
3972 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3973 N0.getOpcode() == ISD::ANY_EXTEND ||
3974 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3975 N0.getOperand(0).getOpcode() == ISD::SHL &&
3976 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00003977 uint64_t c1 =
Dale Johannesena94e36b2010-12-21 21:55:50 +00003978 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3979 uint64_t c2 = N1C->getZExtValue();
3980 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3981 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3982 if (c2 >= OpSizeInBits - InnerShiftSize) {
3983 if (c1 + c2 >= OpSizeInBits)
3984 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003985 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3986 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
Dale Johannesena94e36b2010-12-21 21:55:50 +00003987 N0.getOperand(0)->getOperand(0)),
3988 DAG.getConstant(c1 + c2, N1.getValueType()));
3989 }
3990 }
3991
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00003992 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3993 // Only fold this if the inner zext has no other uses to avoid increasing
3994 // the total number of instructions.
3995 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3996 N0.getOperand(0).getOpcode() == ISD::SRL &&
3997 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3998 uint64_t c1 =
3999 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4000 if (c1 < VT.getSizeInBits()) {
4001 uint64_t c2 = N1C->getZExtValue();
4002 if (c1 == c2) {
4003 SDValue NewOp0 = N0.getOperand(0);
4004 EVT CountVT = NewOp0.getOperand(1).getValueType();
4005 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4006 NewOp0, DAG.getConstant(c2, CountVT));
Andrea Di Biagio561badf2013-10-17 11:02:58 +00004007 AddToWorkList(NewSHL.getNode());
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004008 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4009 }
4010 }
4011 }
4012
Eli Friedman1877ac92011-06-09 22:14:44 +00004013 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4014 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004015 // Only fold this if the inner shift has no other uses -- if it does, folding
4016 // this will increase the total number of instructions.
4017 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
Nate Begeman21158fc2005-09-01 00:19:25 +00004018 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004019 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
Evan Chenga7bb55e2009-07-21 05:40:15 +00004020 if (c1 < VT.getSizeInBits()) {
4021 uint64_t c2 = N1C->getZExtValue();
Eli Friedman1877ac92011-06-09 22:14:44 +00004022 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
4023 VT.getSizeInBits() - c1);
4024 SDValue Shift;
4025 if (c2 > c1) {
4026 Mask = Mask.shl(c2-c1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004027 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman1877ac92011-06-09 22:14:44 +00004028 DAG.getConstant(c2-c1, N1.getValueType()));
4029 } else {
4030 Mask = Mask.lshr(c1-c2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004031 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman1877ac92011-06-09 22:14:44 +00004032 DAG.getConstant(c1-c2, N1.getValueType()));
4033 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00004034 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
Eli Friedman1877ac92011-06-09 22:14:44 +00004035 DAG.getConstant(Mask, VT));
Evan Chenga7bb55e2009-07-21 05:40:15 +00004036 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004037 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004038 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004039 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4040 SDValue HiBitsMask =
4041 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
4042 VT.getSizeInBits() -
4043 N1C->getZExtValue()),
4044 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004045 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004046 HiBitsMask);
4047 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004048
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004049 if (N1C) {
4050 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
4051 if (NewSHL.getNode())
4052 return NewSHL;
4053 }
4054
Evan Chengf1005572010-04-28 07:10:39 +00004055 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004056}
4057
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004058SDValue DAGCombiner::visitSRA(SDNode *N) {
4059 SDValue N0 = N->getOperand(0);
4060 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004061 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4062 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004063 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004064 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004065
Daniel Sandersa1840d22013-11-11 17:23:41 +00004066 // fold vector ops
4067 if (VT.isVector()) {
4068 SDValue FoldedVOp = SimplifyVBinOp(N);
4069 if (FoldedVOp.getNode()) return FoldedVOp;
4070 }
4071
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004072 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004073 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004074 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004075 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004076 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004077 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004078 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004079 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004080 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004081 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004082 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004083 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004084 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004085 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004086 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004087 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4088 // sext_inreg.
4089 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004090 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004091 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4092 if (VT.isVector())
4093 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4094 ExtVT, VT.getVectorNumElements());
4095 if ((!LegalOperations ||
4096 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004097 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004098 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004099 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004100
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004101 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004102 if (N1C && N0.getOpcode() == ISD::SRA) {
4103 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004104 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Dan Gohman1d459e42009-12-11 21:31:27 +00004105 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004106 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0f8a7272006-02-28 06:23:04 +00004107 DAG.getConstant(Sum, N1C->getValueType(0)));
4108 }
4109 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004110
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004111 // fold (sra (shl X, m), (sub result_size, n))
4112 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004113 // result_size - n != m.
4114 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004115 // code.
Christopher Lamb8fe91092008-03-19 08:30:06 +00004116 if (N0.getOpcode() == ISD::SHL) {
4117 // Get the two constanst of the shifts, CN0 = m, CN = n.
4118 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4119 if (N01C && N1C) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004120 // Determine what the truncate's result bitsize and type would be.
Owen Anderson53aa7a92009-08-10 22:56:29 +00004121 EVT TruncVT =
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004122 EVT::getIntegerVT(*DAG.getContext(),
4123 OpSizeInBits - N1C->getZExtValue());
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004124 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004125 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004126
Scott Michelcf0da6c2009-02-17 22:15:04 +00004127 // If the shift is not a no-op (in which case this should be just a sign
4128 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004129 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004130 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004131 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004132 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4133 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004134 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004135
Owen Andersonb2c80da2011-02-25 21:41:48 +00004136 SDValue Amt = DAG.getConstant(ShiftAmt,
4137 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004138 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004139 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004140 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004141 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004142 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004143 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004144 }
4145 }
4146 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004147
Duncan Sands3ed76882009-02-01 18:06:53 +00004148 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004149 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004150 N1.getOperand(0).getOpcode() == ISD::AND) {
4151 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4152 if (NewOp1.getNode())
4153 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004154 }
4155
Benjamin Kramer946e1522011-01-30 16:38:43 +00004156 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4157 // if c1 is equal to the number of bits the trunc removes
4158 if (N0.getOpcode() == ISD::TRUNCATE &&
4159 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4160 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4161 N0.getOperand(0).hasOneUse() &&
4162 N0.getOperand(0).getOperand(1).hasOneUse() &&
4163 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4164 EVT LargeVT = N0.getOperand(0).getValueType();
4165 ConstantSDNode *LargeShiftAmt =
4166 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4167
4168 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4169 LargeShiftAmt->getZExtValue()) {
4170 SDValue Amt =
4171 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00004172 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004173 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
Benjamin Kramer946e1522011-01-30 16:38:43 +00004174 N0.getOperand(0).getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004175 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
Benjamin Kramer946e1522011-01-30 16:38:43 +00004176 }
4177 }
4178
Scott Michelcf0da6c2009-02-17 22:15:04 +00004179 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004180 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4181 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004182
4183
Nate Begeman21158fc2005-09-01 00:19:25 +00004184 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004185 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004186 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004187
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004188 if (N1C) {
4189 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4190 if (NewSRA.getNode())
4191 return NewSRA;
4192 }
4193
Evan Chengf1005572010-04-28 07:10:39 +00004194 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004195}
4196
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004197SDValue DAGCombiner::visitSRL(SDNode *N) {
4198 SDValue N0 = N->getOperand(0);
4199 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004200 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4201 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004202 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004203 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004204
Daniel Sandersa1840d22013-11-11 17:23:41 +00004205 // fold vector ops
4206 if (VT.isVector()) {
4207 SDValue FoldedVOp = SimplifyVBinOp(N);
4208 if (FoldedVOp.getNode()) return FoldedVOp;
4209 }
4210
Nate Begeman21158fc2005-09-01 00:19:25 +00004211 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004212 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004213 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004214 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004215 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004216 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004217 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004218 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004219 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004220 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004221 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004222 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004223 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004224 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004225 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004226 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004227
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004228 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Scott Michelcf0da6c2009-02-17 22:15:04 +00004229 if (N1C && N0.getOpcode() == ISD::SRL &&
Nate Begeman21158fc2005-09-01 00:19:25 +00004230 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004231 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4232 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004233 if (c1 + c2 >= OpSizeInBits)
Nate Begemand23739d2005-09-06 04:43:02 +00004234 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004235 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Nate Begemand23739d2005-09-06 04:43:02 +00004236 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman21158fc2005-09-01 00:19:25 +00004237 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004238
Dale Johannesencd538af2010-12-17 21:45:49 +00004239 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004240 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4241 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004242 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004243 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004244 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4245 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004246 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4247 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004248 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004249 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004250 if (c1 + OpSizeInBits == InnerShiftSize) {
4251 if (c1 + c2 >= InnerShiftSize)
4252 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004253 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4254 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004255 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004256 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004257 }
4258 }
4259
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004260 // fold (srl (shl x, c), c) -> (and x, cst2)
4261 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4262 N0.getValueSizeInBits() <= 64) {
4263 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004264 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004265 DAG.getConstant(~0ULL >> ShAmt, VT));
4266 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004267
Michael Liao62ebfd82013-06-21 18:45:27 +00004268 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004269 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4270 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004271 EVT SmallVT = N0.getOperand(0).getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +00004272 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
Dale Johannesen84935752009-02-06 23:05:02 +00004273 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004274
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004275 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004276 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004277 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004278 N0.getOperand(0),
4279 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004280 AddToWorkList(SmallShift.getNode());
Michael Liao62ebfd82013-06-21 18:45:27 +00004281 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4282 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4283 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4284 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004285 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004286 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004287
Chris Lattner2e33fb42006-10-12 20:23:19 +00004288 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4289 // bit, which is unmodified by sra.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004290 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004291 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004292 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004293 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004294
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004295 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004296 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Duncan Sands13237ac2008-06-06 12:08:01 +00004297 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004298 APInt KnownZero, KnownOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004299 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004300
Chris Lattner49932492006-04-02 06:11:11 +00004301 // If any of the input bits are KnownOne, then the input couldn't be all
4302 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004303 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004304
Chris Lattner49932492006-04-02 06:11:11 +00004305 // If all of the bits input the to ctlz node are known to be zero, then
4306 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004307 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004308 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004309
Chris Lattner49932492006-04-02 06:11:11 +00004310 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004311 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004312 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004313 // could be set on input to the CTLZ node. If this bit is set, the SRL
4314 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4315 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004316 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004317 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004318
Chris Lattner49932492006-04-02 06:11:11 +00004319 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004320 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004321 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004322 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004323 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004324
Andrew Trickef9de2a2013-05-25 02:42:55 +00004325 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004326 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004327 }
4328 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004329
Duncan Sands3ed76882009-02-01 18:06:53 +00004330 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004331 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004332 N1.getOperand(0).getOpcode() == ISD::AND) {
4333 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4334 if (NewOp1.getNode())
4335 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004336 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004337
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004338 // fold operands of srl based on knowledge that the low bits are not
4339 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004340 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4341 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004342
Evan Chengb175de62009-12-18 21:31:31 +00004343 if (N1C) {
4344 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4345 if (NewSRL.getNode())
4346 return NewSRL;
4347 }
4348
Dan Gohman600f62b2010-06-24 14:30:44 +00004349 // Attempt to convert a srl of a load into a narrower zero-extending load.
4350 SDValue NarrowLoad = ReduceLoadWidth(N);
4351 if (NarrowLoad.getNode())
4352 return NarrowLoad;
4353
Evan Chengb175de62009-12-18 21:31:31 +00004354 // Here is a common situation. We want to optimize:
4355 //
4356 // %a = ...
4357 // %b = and i32 %a, 2
4358 // %c = srl i32 %b, 1
4359 // brcond i32 %c ...
4360 //
4361 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004362 //
Evan Chengb175de62009-12-18 21:31:31 +00004363 // %a = ...
4364 // %b = and %a, 2
4365 // %c = setcc eq %b, 0
4366 // brcond %c ...
4367 //
4368 // However when after the source operand of SRL is optimized into AND, the SRL
4369 // itself may not be optimized further. Look for it and add the BRCOND into
4370 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004371 if (N->hasOneUse()) {
4372 SDNode *Use = *N->use_begin();
4373 if (Use->getOpcode() == ISD::BRCOND)
4374 AddToWorkList(Use);
4375 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4376 // Also look pass the truncate.
4377 Use = *Use->use_begin();
4378 if (Use->getOpcode() == ISD::BRCOND)
4379 AddToWorkList(Use);
4380 }
4381 }
Evan Chengb175de62009-12-18 21:31:31 +00004382
Evan Chengf1005572010-04-28 07:10:39 +00004383 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004384}
4385
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004386SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4387 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004388 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004389
4390 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004391 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004392 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004393 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004394}
4395
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004396SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4397 SDValue N0 = N->getOperand(0);
4398 EVT VT = N->getValueType(0);
4399
4400 // fold (ctlz_zero_undef c1) -> c2
4401 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004402 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004403 return SDValue();
4404}
4405
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004406SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4407 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004408 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004409
Nate Begeman21158fc2005-09-01 00:19:25 +00004410 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004411 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004412 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004413 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004414}
4415
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004416SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4417 SDValue N0 = N->getOperand(0);
4418 EVT VT = N->getValueType(0);
4419
4420 // fold (cttz_zero_undef c1) -> c2
4421 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004422 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004423 return SDValue();
4424}
4425
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004426SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4427 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004428 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004429
Nate Begeman21158fc2005-09-01 00:19:25 +00004430 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004431 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004432 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004433 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004434}
4435
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004436SDValue DAGCombiner::visitSELECT(SDNode *N) {
4437 SDValue N0 = N->getOperand(0);
4438 SDValue N1 = N->getOperand(1);
4439 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004440 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4441 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4442 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004443 EVT VT = N->getValueType(0);
4444 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004445
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004446 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004447 if (N1 == N2)
4448 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004449 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004450 if (N0C && !N0C->isNullValue())
4451 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004452 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004453 if (N0C && N0C->isNullValue())
4454 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004455 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004456 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004457 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004458 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004459 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004460 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004461 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004462 TLI.getBooleanContents(false) ==
4463 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004464 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004465 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004466 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004467 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004468 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004469 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004470 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004471 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004472 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004473 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4474 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004475 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004476 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004477 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004478 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004479 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004480 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004481 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004482 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004483 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004484 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004485 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004486 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004487 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004488 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004489 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004490 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004491 // fold (select X, X, Y) -> (or X, Y)
4492 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004493 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004494 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004495 // fold (select X, Y, X) -> (and X, Y)
4496 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004497 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004498 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004499
Chris Lattner6c14c352005-10-18 06:04:22 +00004500 // If we can fold this based on the true/false value, do so.
4501 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004502 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004503
Nate Begemanc760f802005-09-19 22:34:01 +00004504 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004505 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004506 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004507 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004508 // having to say they don't support SELECT_CC on every type the DAG knows
4509 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004510 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004511 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004512 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004513 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004514 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004515 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004516 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004517
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004518 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004519}
4520
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004521static
4522std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4523 SDLoc DL(N);
4524 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004525 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004526
4527 // Split the inputs.
4528 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004529 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4530 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004531
4532 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4533 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4534
4535 return std::make_pair(Lo, Hi);
4536}
4537
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004538SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4539 SDValue N0 = N->getOperand(0);
4540 SDValue N1 = N->getOperand(1);
4541 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004542 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004543
4544 // Canonicalize integer abs.
4545 // vselect (setg[te] X, 0), X, -X ->
4546 // vselect (setgt X, -1), X, -X ->
4547 // vselect (setl[te] X, 0), -X, X ->
4548 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4549 if (N0.getOpcode() == ISD::SETCC) {
4550 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4551 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4552 bool isAbs = false;
4553 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4554
4555 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4556 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4557 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4558 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4559 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4560 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4561 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4562
4563 if (isAbs) {
4564 EVT VT = LHS.getValueType();
4565 SDValue Shift = DAG.getNode(
4566 ISD::SRA, DL, VT, LHS,
4567 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4568 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4569 AddToWorkList(Shift.getNode());
4570 AddToWorkList(Add.getNode());
4571 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4572 }
4573 }
4574
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004575 // If the VSELECT result requires splitting and the mask is provided by a
4576 // SETCC, then split both nodes and its operands before legalization. This
4577 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4578 // and enables future optimizations (e.g. min/max pattern matching on X86).
4579 if (N0.getOpcode() == ISD::SETCC) {
4580 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004581
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004582 // Check if any splitting is required.
4583 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4584 TargetLowering::TypeSplitVector)
4585 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004586
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004587 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004588 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4589 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4590 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004591
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004592 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4593 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004594
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004595 // Add the new VSELECT nodes to the work list in case they need to be split
4596 // again.
4597 AddToWorkList(Lo.getNode());
4598 AddToWorkList(Hi.getNode());
4599
4600 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004601 }
4602
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004603 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4604 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4605 return N1;
4606 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4607 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4608 return N2;
4609
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004610 return SDValue();
4611}
4612
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004613SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4614 SDValue N0 = N->getOperand(0);
4615 SDValue N1 = N->getOperand(1);
4616 SDValue N2 = N->getOperand(2);
4617 SDValue N3 = N->getOperand(3);
4618 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004619 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004620
Nate Begemanc760f802005-09-19 22:34:01 +00004621 // fold select_cc lhs, rhs, x, x, cc -> x
4622 if (N2 == N3)
4623 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004624
Chris Lattner8b68dec2006-09-20 06:19:26 +00004625 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004626 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004627 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004628 if (SCC.getNode()) {
4629 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004630
Stephen Lin605207f2013-06-15 04:03:33 +00004631 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4632 if (!SCCC->isNullValue())
4633 return N2; // cond always true -> true val
4634 else
4635 return N3; // cond always false -> false val
4636 }
4637
4638 // Fold to a simpler select_cc
4639 if (SCC.getOpcode() == ISD::SETCC)
4640 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4641 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4642 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004643 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004644
Chris Lattner6c14c352005-10-18 06:04:22 +00004645 // If we can fold this based on the true/false value, do so.
4646 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004647 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004648
Nate Begemanc760f802005-09-19 22:34:01 +00004649 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004650 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004651}
4652
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004653SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004654 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004655 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004656 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004657}
4658
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004659// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4660// dag node into a ConstantSDNode or a build_vector of constants.
4661// This function is called by the DAGCombiner when visiting sext/zext/aext
4662// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4663// Vector extends are not folded if operations are legal; this is to
4664// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004665static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4666 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004667 bool LegalOperations) {
4668 unsigned Opcode = N->getOpcode();
4669 SDValue N0 = N->getOperand(0);
4670 EVT VT = N->getValueType(0);
4671
4672 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4673 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4674
4675 // fold (sext c1) -> c1
4676 // fold (zext c1) -> c1
4677 // fold (aext c1) -> c1
4678 if (isa<ConstantSDNode>(N0))
4679 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4680
4681 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4682 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4683 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004684 EVT SVT = VT.getScalarType();
4685 if (!(VT.isVector() &&
4686 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004687 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4688 return 0;
4689
4690 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004691 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004692 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4693 unsigned ShAmt = VTBits - EVTBits;
4694 SmallVector<SDValue, 8> Elts;
4695 unsigned NumElts = N0->getNumOperands();
4696 SDLoc DL(N);
4697
4698 for (unsigned i=0; i != NumElts; ++i) {
4699 SDValue Op = N0->getOperand(i);
4700 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004701 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004702 continue;
4703 }
4704
4705 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4706 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4707 if (Opcode == ISD::SIGN_EXTEND)
4708 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004709 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004710 else
4711 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004712 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004713 }
4714
4715 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4716}
4717
Evan Chenge106e2f2007-10-29 19:58:20 +00004718// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004719// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004720// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004721// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004722static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004723 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004724 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004725 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004726 bool HasCopyToRegUses = false;
4727 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004728 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4729 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004730 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004731 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004732 if (User == N)
4733 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004734 if (UI.getUse().getResNo() != N0.getResNo())
4735 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004736 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004737 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004738 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4739 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4740 // Sign bits will be lost after a zext.
4741 return false;
4742 bool Add = false;
4743 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004744 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004745 if (UseOp == N0)
4746 continue;
4747 if (!isa<ConstantSDNode>(UseOp))
4748 return false;
4749 Add = true;
4750 }
4751 if (Add)
4752 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004753 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004754 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004755 // If truncates aren't free and there are users we can't
4756 // extend, it isn't worthwhile.
4757 if (!isTruncFree)
4758 return false;
4759 // Remember if this value is live-out.
4760 if (User->getOpcode() == ISD::CopyToReg)
4761 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004762 }
4763
4764 if (HasCopyToRegUses) {
4765 bool BothLiveOut = false;
4766 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4767 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004768 SDUse &Use = UI.getUse();
4769 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4770 BothLiveOut = true;
4771 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004772 }
4773 }
4774 if (BothLiveOut)
4775 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004776 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004777 return ExtendNodes.size();
4778 }
4779 return true;
4780}
4781
Craig Toppere0b71182013-07-13 07:43:40 +00004782void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004783 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004784 ISD::NodeType ExtType) {
4785 // Extend SetCC uses if necessary.
4786 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4787 SDNode *SetCC = SetCCs[i];
4788 SmallVector<SDValue, 4> Ops;
4789
4790 for (unsigned j = 0; j != 2; ++j) {
4791 SDValue SOp = SetCC->getOperand(j);
4792 if (SOp == Trunc)
4793 Ops.push_back(ExtLoad);
4794 else
4795 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4796 }
4797
4798 Ops.push_back(SetCC->getOperand(2));
4799 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4800 &Ops[0], Ops.size()));
4801 }
4802}
4803
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004804SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4805 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004806 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004807
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004808 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4809 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004810 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004811
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004812 // fold (sext (sext x)) -> (sext x)
4813 // fold (sext (aext x)) -> (sext x)
4814 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004815 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004816 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004817
Chris Lattnerfce448f2007-02-26 03:13:59 +00004818 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004819 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4820 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004821 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4822 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004823 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4824 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004825 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004826 // CombineTo deleted the truncate, if needed, but not what's under it.
4827 AddToWorkList(oye);
4828 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004829 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004830 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004831
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004832 // See if the value being truncated is already sign extended. If so, just
4833 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004834 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004835 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4836 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4837 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004838 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004839
Chris Lattnerfce448f2007-02-26 03:13:59 +00004840 if (OpBits == DestBits) {
4841 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4842 // bits, it is already ready.
4843 if (NumSignBits > DestBits-MidBits)
4844 return Op;
4845 } else if (OpBits < DestBits) {
4846 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4847 // bits, just sext from i32.
4848 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004849 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004850 } else {
4851 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4852 // bits, just truncate to i32.
4853 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004854 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004855 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004856
Chris Lattnerfce448f2007-02-26 03:13:59 +00004857 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004858 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4859 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004860 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004861 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004862 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004863 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4864 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004865 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004866 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004867 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004868
Evan Chengbce7c472005-12-14 02:19:23 +00004869 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004870 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004871 // on vectors in one instruction. We only perform this transformation on
4872 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004873 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004874 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004875 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004876 bool DoXform = true;
4877 SmallVector<SDNode*, 4> SetCCs;
4878 if (!N0.hasOneUse())
4879 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4880 if (DoXform) {
4881 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004882 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004883 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004884 LN0->getBasePtr(), N0.getValueType(),
4885 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004886 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004887 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004888 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004889 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004890 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004891 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004892 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004893 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004894 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004895
4896 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4897 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004898 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4899 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004900 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004901 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004902 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004903 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004904 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004905 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004906 LN0->getBasePtr(), MemVT,
4907 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004908 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004909 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004910 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004911 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004912 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004914 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004915 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004916
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004917 // fold (sext (and/or/xor (load x), cst)) ->
4918 // (and/or/xor (sextload x), (sext cst))
4919 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4920 N0.getOpcode() == ISD::XOR) &&
4921 isa<LoadSDNode>(N0.getOperand(0)) &&
4922 N0.getOperand(1).getOpcode() == ISD::Constant &&
4923 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4924 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4925 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4926 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4927 bool DoXform = true;
4928 SmallVector<SDNode*, 4> SetCCs;
4929 if (!N0.hasOneUse())
4930 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4931 SetCCs, TLI);
4932 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004933 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004934 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004935 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004936 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004937 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4938 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004939 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004940 ExtLoad, DAG.getConstant(Mask, VT));
4941 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004942 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004943 N0.getOperand(0).getValueType(), ExtLoad);
4944 CombineTo(N, And);
4945 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004946 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004947 ISD::SIGN_EXTEND);
4948 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4949 }
4950 }
4951 }
4952
Chris Lattner65786b02007-04-11 05:32:27 +00004953 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00004954 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00004955 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00004956 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00004957 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00004958 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00004959 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00004960 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4961 // of the same size as the compared operands. Only optimize sext(setcc())
4962 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00004963 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00004964
4965 // We know that the # elements of the results is the same as the
4966 // # elements of the compare (and the # elements of the compare result
4967 // for that matter). Check to see that they are the same size. If so,
4968 // we know that the element size of the sext'd result matches the
4969 // element size of the compare operands.
4970 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004971 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00004972 N0.getOperand(1),
4973 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00004974
Dan Gohmane82c25e2010-04-30 17:19:19 +00004975 // If the desired elements are smaller or larger than the source
4976 // elements we can use a matching integer vector type and then
4977 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00004978 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00004979 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004980 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00004981 N0.getOperand(0), N0.getOperand(1),
4982 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004983 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00004984 }
Chris Lattner4ac60732009-07-08 00:31:33 +00004985 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00004986
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00004987 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00004988 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004989 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00004990 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004991 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00004992 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004993 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00004994 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004995 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00004996
4997 if (!VT.isVector()) {
4998 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
4999 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5000 SDLoc DL(N);
5001 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5002 SDValue SetCC = DAG.getSetCC(DL,
5003 SetCCVT,
5004 N0.getOperand(0), N0.getOperand(1), CC);
5005 EVT SelectVT = getSetCCResultType(VT);
5006 return DAG.getSelect(DL, VT,
5007 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5008 NegOne, DAG.getConstant(0, VT));
5009
5010 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005011 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005012 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005013
Dan Gohman3eb10f72008-04-28 16:58:24 +00005014 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005015 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005016 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005017 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005018
Evan Chengf1005572010-04-28 07:10:39 +00005019 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005020}
5021
Rafael Espindola8f62b322012-04-09 16:06:03 +00005022// isTruncateOf - If N is a truncate of some other value, return true, record
5023// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5024// This function computes KnownZero to avoid a duplicated call to
5025// ComputeMaskedBits in the caller.
5026static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5027 APInt &KnownZero) {
5028 APInt KnownOne;
5029 if (N->getOpcode() == ISD::TRUNCATE) {
5030 Op = N->getOperand(0);
5031 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5032 return true;
5033 }
5034
5035 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5036 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5037 return false;
5038
5039 SDValue Op0 = N->getOperand(0);
5040 SDValue Op1 = N->getOperand(1);
5041 assert(Op0.getValueType() == Op1.getValueType());
5042
5043 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5044 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005045 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005046 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005047 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005048 Op = Op0;
5049 else
5050 return false;
5051
5052 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5053
5054 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5055 return false;
5056
5057 return true;
5058}
5059
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005060SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5061 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005062 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005063
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005064 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5065 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005066 return SDValue(Res, 0);
5067
Nate Begeman21158fc2005-09-01 00:19:25 +00005068 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005069 // fold (zext (aext x)) -> (zext x)
5070 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005071 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005072 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005073
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005074 // fold (zext (truncate x)) -> (zext x) or
5075 // (zext (truncate x)) -> (truncate x)
5076 // This is valid when the truncated bits of x are already zero.
5077 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005078 SDValue Op;
5079 APInt KnownZero;
5080 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5081 APInt TruncatedBits =
5082 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5083 APInt(Op.getValueSizeInBits(), 0) :
5084 APInt::getBitsSet(Op.getValueSizeInBits(),
5085 N0.getValueSizeInBits(),
5086 std::min(Op.getValueSizeInBits(),
5087 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005088 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005089 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005090 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005091 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005092 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005093
5094 return Op;
5095 }
5096 }
5097
Evan Cheng464dc9b2007-03-22 01:54:19 +00005098 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5099 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005100 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005101 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5102 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005103 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5104 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005105 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005106 // CombineTo deleted the truncate, if needed, but not what's under it.
5107 AddToWorkList(oye);
5108 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005109 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005110 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005111 }
5112
Chris Lattnera31f0a62006-09-21 06:00:20 +00005113 // fold (zext (truncate x)) -> (and x, mask)
5114 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005115 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005116
5117 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5118 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5119 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5120 if (NarrowLoad.getNode()) {
5121 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5122 if (NarrowLoad.getNode() != N0.getNode()) {
5123 CombineTo(N0.getNode(), NarrowLoad);
5124 // CombineTo deleted the truncate, if needed, but not what's under it.
5125 AddToWorkList(oye);
5126 }
5127 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5128 }
5129
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005130 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005131 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005132 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005133 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005134 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005135 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005136 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005137 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005138 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005139 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005140 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005141
Dan Gohmanad3e5492009-04-08 00:15:30 +00005142 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5143 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005144 if (N0.getOpcode() == ISD::AND &&
5145 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005146 N0.getOperand(1).getOpcode() == ISD::Constant &&
5147 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5148 N0.getValueType()) ||
5149 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005150 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005151 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005152 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005153 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005154 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005155 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005156 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005157 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005158 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005159 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005160 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005161
Evan Chengbce7c472005-12-14 02:19:23 +00005162 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005163 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005164 // on vectors in one instruction. We only perform this transformation on
5165 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005166 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005167 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005168 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005169 bool DoXform = true;
5170 SmallVector<SDNode*, 4> SetCCs;
5171 if (!N0.hasOneUse())
5172 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5173 if (DoXform) {
5174 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005175 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005176 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005177 LN0->getBasePtr(), N0.getValueType(),
5178 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005179 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005180 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005181 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005182 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005183
Andrew Trickef9de2a2013-05-25 02:42:55 +00005184 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005185 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005186 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005187 }
Evan Chengbce7c472005-12-14 02:19:23 +00005188 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005189
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005190 // fold (zext (and/or/xor (load x), cst)) ->
5191 // (and/or/xor (zextload x), (zext cst))
5192 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5193 N0.getOpcode() == ISD::XOR) &&
5194 isa<LoadSDNode>(N0.getOperand(0)) &&
5195 N0.getOperand(1).getOpcode() == ISD::Constant &&
5196 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5197 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5198 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5199 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5200 bool DoXform = true;
5201 SmallVector<SDNode*, 4> SetCCs;
5202 if (!N0.hasOneUse())
5203 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5204 SetCCs, TLI);
5205 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005206 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005207 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005208 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005209 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005210 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5211 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005212 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005213 ExtLoad, DAG.getConstant(Mask, VT));
5214 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005215 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005216 N0.getOperand(0).getValueType(), ExtLoad);
5217 CombineTo(N, And);
5218 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005219 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005220 ISD::ZERO_EXTEND);
5221 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5222 }
5223 }
5224 }
5225
Chris Lattner7dac1082005-12-14 19:05:06 +00005226 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5227 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005228 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5229 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005230 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005231 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005232 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005233 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005234 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005235 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005236 LN0->getBasePtr(), MemVT,
5237 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005238 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005239 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005240 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005241 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005242 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005243 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005244 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005245 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005246
Chris Lattner65786b02007-04-11 05:32:27 +00005247 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005248 if (!LegalOperations && VT.isVector() &&
5249 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005250 EVT N0VT = N0.getOperand(0).getValueType();
5251 if (getSetCCResultType(N0VT) == N0.getValueType())
5252 return SDValue();
5253
Evan Chengabd0ad52010-05-19 01:08:17 +00005254 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5255 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005256 EVT EltVT = VT.getVectorElementType();
5257 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5258 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005259 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005260 // We know that the # elements of the results is the same as the
5261 // # elements of the compare (and the # elements of the compare result
5262 // for that matter). Check to see that they are the same size. If so,
5263 // we know that the element size of the sext'd result matches the
5264 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005265 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5266 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005267 N0.getOperand(1),
5268 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005269 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Chengabd0ad52010-05-19 01:08:17 +00005270 &OneOps[0], OneOps.size()));
Dan Gohman4298df62011-05-17 22:20:36 +00005271
5272 // If the desired elements are smaller or larger than the source
5273 // elements we can use a matching integer vector type and then
5274 // truncate/sign extend
5275 EVT MatchingElementType =
5276 EVT::getIntegerVT(*DAG.getContext(),
5277 N0VT.getScalarType().getSizeInBits());
5278 EVT MatchingVectorType =
5279 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5280 N0VT.getVectorNumElements());
5281 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005282 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005283 N0.getOperand(1),
5284 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005285 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5286 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5287 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman4298df62011-05-17 22:20:36 +00005288 &OneOps[0], OneOps.size()));
Evan Chengabd0ad52010-05-19 01:08:17 +00005289 }
5290
5291 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005292 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005293 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005294 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005295 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005296 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005297 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005298
Evan Cheng852c4862009-12-15 03:00:32 +00005299 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005300 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005301 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005302 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5303 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005304 SDValue ShAmt = N0.getOperand(1);
5305 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005306 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005307 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005308 // If the original shl may be shifting out bits, do not perform this
5309 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005310 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5311 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5312 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005313 return SDValue();
5314 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005315
Andrew Trickef9de2a2013-05-25 02:42:55 +00005316 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005317
5318 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005319 if (VT.getSizeInBits() >= 256)
5320 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005321
Chris Lattnere95d1952011-02-13 19:09:16 +00005322 return DAG.getNode(N0.getOpcode(), DL, VT,
5323 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5324 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005325 }
5326
Evan Chengf1005572010-04-28 07:10:39 +00005327 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005328}
5329
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005330SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5331 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005332 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005333
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005334 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5335 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005336 return SDValue(Res, 0);
5337
Chris Lattner812646a2006-05-05 05:58:59 +00005338 // fold (aext (aext x)) -> (aext x)
5339 // fold (aext (zext x)) -> (zext x)
5340 // fold (aext (sext x)) -> (sext x)
5341 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5342 N0.getOpcode() == ISD::ZERO_EXTEND ||
5343 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005344 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005345
Evan Cheng464dc9b2007-03-22 01:54:19 +00005346 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5347 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5348 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005349 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5350 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005351 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5352 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005353 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005354 // CombineTo deleted the truncate, if needed, but not what's under it.
5355 AddToWorkList(oye);
5356 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005357 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005358 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005359 }
5360
Chris Lattner8746e2c2006-09-20 06:29:17 +00005361 // fold (aext (truncate x))
5362 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005363 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005364 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005365 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005366 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005367 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5368 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005370
Dan Gohmanad3e5492009-04-08 00:15:30 +00005371 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5372 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005373 if (N0.getOpcode() == ISD::AND &&
5374 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005375 N0.getOperand(1).getOpcode() == ISD::Constant &&
5376 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5377 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005378 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005379 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005380 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005381 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005382 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005383 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005384 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005385 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005386 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005387 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005388 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005389
Chris Lattner812646a2006-05-05 05:58:59 +00005390 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005391 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005392 // on vectors in one instruction. We only perform this transformation on
5393 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005394 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005395 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005396 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005397 bool DoXform = true;
5398 SmallVector<SDNode*, 4> SetCCs;
5399 if (!N0.hasOneUse())
5400 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5401 if (DoXform) {
5402 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005403 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005404 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005405 LN0->getBasePtr(), N0.getValueType(),
5406 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005407 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005408 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005409 N0.getValueType(), ExtLoad);
5410 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005411 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005412 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005413 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5414 }
Chris Lattner812646a2006-05-05 05:58:59 +00005415 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005416
Chris Lattner812646a2006-05-05 05:58:59 +00005417 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5418 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5419 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005420 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005421 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005422 N0.hasOneUse()) {
5423 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005424 EVT MemVT = LN0->getMemoryVT();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005425 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
Stuart Hastings81c43062011-02-16 16:23:55 +00005426 VT, LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005427 MemVT, LN0->getMemOperand());
Chris Lattner812646a2006-05-05 05:58:59 +00005428 CombineTo(N, ExtLoad);
Evan Cheng894be332008-08-29 23:20:46 +00005429 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005430 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005431 N0.getValueType(), ExtLoad),
Chris Lattner812646a2006-05-05 05:58:59 +00005432 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005433 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner812646a2006-05-05 05:58:59 +00005434 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005435
Chris Lattner65786b02007-04-11 05:32:27 +00005436 if (N0.getOpcode() == ISD::SETCC) {
Evan Chengabd0ad52010-05-19 01:08:17 +00005437 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5438 // Only do this before legalize for now.
5439 if (VT.isVector() && !LegalOperations) {
5440 EVT N0VT = N0.getOperand(0).getValueType();
5441 // We know that the # elements of the results is the same as the
5442 // # elements of the compare (and the # elements of the compare result
5443 // for that matter). Check to see that they are the same size. If so,
5444 // we know that the element size of the sext'd result matches the
5445 // element size of the compare operands.
5446 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005447 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005448 N0.getOperand(1),
5449 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005450 // If the desired elements are smaller or larger than the source
5451 // elements we can use a matching integer vector type and then
5452 // truncate/sign extend
5453 else {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005454 EVT MatchingElementType =
5455 EVT::getIntegerVT(*DAG.getContext(),
5456 N0VT.getScalarType().getSizeInBits());
5457 EVT MatchingVectorType =
5458 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5459 N0VT.getVectorNumElements());
5460 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005461 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005462 N0.getOperand(1),
5463 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005464 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005465 }
5466 }
5467
5468 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005469 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005470 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005471 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005472 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005473 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005474 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005475 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005476
Evan Chengf1005572010-04-28 07:10:39 +00005477 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005478}
5479
Chris Lattner5e6fe052007-10-13 06:35:54 +00005480/// GetDemandedBits - See if the specified operand can be simplified with the
5481/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005482/// simpler operand, otherwise return a null SDValue.
5483SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005484 switch (V.getOpcode()) {
5485 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005486 case ISD::Constant: {
5487 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5488 assert(CV != 0 && "Const value should be ConstSDNode.");
5489 const APInt &CVal = CV->getAPIntValue();
5490 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005491 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005492 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005493 break;
5494 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005495 case ISD::OR:
5496 case ISD::XOR:
5497 // If the LHS or RHS don't contribute bits to the or, drop them.
5498 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5499 return V.getOperand(1);
5500 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5501 return V.getOperand(0);
5502 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005503 case ISD::SRL:
5504 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005505 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005506 break;
5507 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5508 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005509 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005510
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005511 // Watch out for shift count overflow though.
5512 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005513 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005514 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005515 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005516 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005517 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005518 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005519 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005520 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005521}
5522
Evan Cheng464dc9b2007-03-22 01:54:19 +00005523/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5524/// bits and then truncated to a narrower type and where N is a multiple
5525/// of number of bits of the narrower type, transform it to a narrower load
5526/// from address + N / num of bits of new type. If the result is to be
5527/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005528SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005529 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005530
Evan Cheng464dc9b2007-03-22 01:54:19 +00005531 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005532 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005533 EVT VT = N->getValueType(0);
5534 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005535
Dan Gohman550c9af2008-08-14 20:04:46 +00005536 // This transformation isn't valid for vector loads.
5537 if (VT.isVector())
5538 return SDValue();
5539
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005540 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005541 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005542 if (Opc == ISD::SIGN_EXTEND_INREG) {
5543 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005544 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005545 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005546 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005547 ExtType = ISD::ZEXTLOAD;
5548 N0 = SDValue(N, 0);
5549 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5550 if (!N01) return SDValue();
5551 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5552 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005553 }
Richard Osborne272e0842011-01-31 17:41:44 +00005554 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5555 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005556
Owen Anderson53aa7a92009-08-10 22:56:29 +00005557 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005558
Chris Lattner9a499e92010-12-22 08:01:44 +00005559 // Do not generate loads of non-round integer types since these can
5560 // be expensive (and would be wrong if the type is not byte sized).
5561 if (!ExtVT.isRound())
5562 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005563
Evan Cheng464dc9b2007-03-22 01:54:19 +00005564 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005565 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005566 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005567 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005568 // Is the shift amount a multiple of size of VT?
5569 if ((ShAmt & (EVTBits-1)) == 0) {
5570 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005571 // Is the load width a multiple of size of VT?
5572 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005573 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005574 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005575
Chris Lattnercafc1e62010-12-22 08:02:57 +00005576 // At this point, we must have a load or else we can't do the transform.
5577 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005578
Chandler Carruthb27041c2012-12-11 00:36:57 +00005579 // Because a SRL must be assumed to *need* to zero-extend the high bits
5580 // (as opposed to anyext the high bits), we can't combine the zextload
5581 // lowering of SRL and an sextload.
5582 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5583 return SDValue();
5584
Chris Lattnera2050552010-10-01 05:36:09 +00005585 // If the shift amount is larger than the input type then we're not
5586 // accessing any of the loaded bytes. If the load was a zextload/extload
5587 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005588 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005589 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005590 }
5591 }
5592
Dan Gohman68fb0042010-11-03 01:47:46 +00005593 // If the load is shifted left (and the result isn't shifted back right),
5594 // we can fold the truncate through the shift.
5595 unsigned ShLeftAmt = 0;
5596 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005597 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005598 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5599 ShLeftAmt = N01->getZExtValue();
5600 N0 = N0.getOperand(0);
5601 }
5602 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005603
Chris Lattner222374d2010-12-22 07:36:50 +00005604 // If we haven't found a load, we can't narrow it. Don't transform one with
5605 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005606 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5607 return SDValue();
5608
5609 // Don't change the width of a volatile load.
5610 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5611 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005612 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005613
Chris Lattner9a499e92010-12-22 08:01:44 +00005614 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005615 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005616 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005617
Bill Schmidtd006c692013-01-14 22:04:38 +00005618 // For the transform to be legal, the load must produce only two values
5619 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005620 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005621 // transformation is not equivalent, and the downstream logic to replace
5622 // uses gets things wrong.
5623 if (LN0->getNumValues() > 2)
5624 return SDValue();
5625
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005626 // If the load that we're shrinking is an extload and we're not just
5627 // discarding the extension we can't simply shrink the load. Bail.
5628 // TODO: It would be possible to merge the extensions in some cases.
5629 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5630 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5631 return SDValue();
5632
Chris Lattner222374d2010-12-22 07:36:50 +00005633 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005634
Evan Cheng4c6f9172012-06-26 01:19:33 +00005635 if (PtrType == MVT::Untyped || PtrType.isExtended())
5636 // It's not possible to generate a constant of extended or untyped type.
5637 return SDValue();
5638
Chris Lattner222374d2010-12-22 07:36:50 +00005639 // For big endian targets, we need to adjust the offset to the pointer to
5640 // load the correct bytes.
5641 if (TLI.isBigEndian()) {
5642 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5643 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5644 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005645 }
5646
Chris Lattner222374d2010-12-22 07:36:50 +00005647 uint64_t PtrOff = ShAmt / 8;
5648 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005649 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005650 PtrType, LN0->getBasePtr(),
5651 DAG.getConstant(PtrOff, PtrType));
5652 AddToWorkList(NewPtr.getNode());
5653
Chris Lattner9a499e92010-12-22 08:01:44 +00005654 SDValue Load;
5655 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005656 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005657 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005658 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005659 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005660 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005661 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005662 LN0->getPointerInfo().getWithOffset(PtrOff),
5663 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005664 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005665
5666 // Replace the old load's chain with the new load's chain.
5667 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005668 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005669
5670 // Shift the result left, if we've swallowed a left shift.
5671 SDValue Result = Load;
5672 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005673 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005674 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5675 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005676 // If the shift amount is as large as the result size (but, presumably,
5677 // no larger than the source) then the useful bits of the result are
5678 // zero; we can't simply return the shortened shift, because the result
5679 // of that operation is undefined.
5680 if (ShLeftAmt >= VT.getSizeInBits())
5681 Result = DAG.getConstant(0, VT);
5682 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005683 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005684 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005685 }
5686
5687 // Return the new loaded value.
5688 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005689}
5690
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005691SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5692 SDValue N0 = N->getOperand(0);
5693 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005694 EVT VT = N->getValueType(0);
5695 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005696 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005697 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005698
Nate Begeman21158fc2005-09-01 00:19:25 +00005699 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005700 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005701 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005702
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005703 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005704 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005705 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005706
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005707 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5708 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005709 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005710 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005711 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005712
Dan Gohman345d63c2008-07-31 00:50:31 +00005713 // fold (sext_in_reg (sext x)) -> (sext x)
5714 // fold (sext_in_reg (aext x)) -> (sext x)
5715 // if x is small enough.
5716 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5717 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005718 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5719 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005720 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005721 }
5722
Chris Lattner9ad59152007-04-17 19:03:21 +00005723 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005724 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005725 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005726
Chris Lattner9ad59152007-04-17 19:03:21 +00005727 // fold operands of sext_in_reg based on knowledge that the top bits are not
5728 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005729 if (SimplifyDemandedBits(SDValue(N, 0)))
5730 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005731
Evan Cheng464dc9b2007-03-22 01:54:19 +00005732 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5733 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005734 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005735 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005736 return NarrowLoad;
5737
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005738 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005739 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005740 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5741 if (N0.getOpcode() == ISD::SRL) {
5742 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005743 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005744 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005745 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005746 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005747 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005748 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005749 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005750 }
5751 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005752
Nate Begeman02b23c62005-10-13 03:11:28 +00005753 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005754 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005755 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005756 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005757 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005758 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005759 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005760 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005761 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005762 LN0->getBasePtr(), EVT,
5763 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005764 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005765 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005766 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005767 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005768 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005769 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005770 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005771 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005772 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005773 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005774 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005775 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005776 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005777 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005778 LN0->getBasePtr(), EVT,
5779 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005780 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005781 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005782 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005783 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005784
5785 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5786 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5787 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5788 N0.getOperand(1), false);
5789 if (BSwap.getNode() != 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005790 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005791 BSwap, N1);
5792 }
5793
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005794 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5795 // into a build_vector.
5796 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5797 SmallVector<SDValue, 8> Elts;
5798 unsigned NumElts = N0->getNumOperands();
5799 unsigned ShAmt = VTBits - EVTBits;
5800
5801 for (unsigned i = 0; i != NumElts; ++i) {
5802 SDValue Op = N0->getOperand(i);
5803 if (Op->getOpcode() == ISD::UNDEF) {
5804 Elts.push_back(Op);
5805 continue;
5806 }
5807
5808 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005809 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5810 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005811 Op.getValueType()));
5812 }
5813
5814 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5815 }
5816
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005817 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005818}
5819
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005820SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5821 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005822 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005823 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005824
5825 // noop truncate
5826 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005827 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005828 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005829 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005830 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005831 // fold (truncate (truncate x)) -> (truncate x)
5832 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005833 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005834 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005835 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5836 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005837 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005838 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005839 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005840 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005841 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005842 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005843 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005844 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005845 // if the source and dest are the same type, we can drop both the extend
5846 // and the truncate.
5847 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005848 }
Evan Chengd63baea2007-03-21 20:14:05 +00005849
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005850 // Fold extract-and-trunc into a narrow extract. For example:
5851 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5852 // i32 y = TRUNCATE(i64 x)
5853 // -- becomes --
5854 // v16i8 b = BITCAST (v2i64 val)
5855 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5856 //
5857 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005858 // creates this pattern) and before operation legalization after which
5859 // we need to be more careful about the vector instructions that we generate.
5860 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005861 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005862
5863 EVT VecTy = N0.getOperand(0).getValueType();
5864 EVT ExTy = N0.getValueType();
5865 EVT TrTy = N->getValueType(0);
5866
5867 unsigned NumElem = VecTy.getVectorNumElements();
5868 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5869
5870 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5871 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5872
5873 SDValue EltNo = N0->getOperand(1);
5874 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5875 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005876 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005877 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5878
Andrew Trickef9de2a2013-05-25 02:42:55 +00005879 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005880 NVT, N0.getOperand(0));
5881
5882 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005883 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005884 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005885 }
5886 }
5887
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005888 // Fold a series of buildvector, bitcast, and truncate if possible.
5889 // For example fold
5890 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5891 // (2xi32 (buildvector x, y)).
5892 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5893 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5894 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5895 N0.getOperand(0).hasOneUse()) {
5896
5897 SDValue BuildVect = N0.getOperand(0);
5898 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5899 EVT TruncVecEltTy = VT.getVectorElementType();
5900
5901 // Check that the element types match.
5902 if (BuildVectEltTy == TruncVecEltTy) {
5903 // Now we only need to compute the offset of the truncated elements.
5904 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5905 unsigned TruncVecNumElts = VT.getVectorNumElements();
5906 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5907
5908 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5909 "Invalid number of elements");
5910
5911 SmallVector<SDValue, 8> Opnds;
5912 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5913 Opnds.push_back(BuildVect.getOperand(i));
5914
Andrew Trickef9de2a2013-05-25 02:42:55 +00005915 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005916 Opnds.size());
5917 }
5918 }
5919
Chris Lattner5e6fe052007-10-13 06:35:54 +00005920 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00005921 // only the low bits are being used.
5922 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00005923 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00005924 // may have different active low bits.
5925 if (!VT.isVector()) {
5926 SDValue Shorter =
5927 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5928 VT.getSizeInBits()));
5929 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005930 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00005931 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005932 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00005933 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00005934 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5935 SDValue Reduced = ReduceLoadWidth(N);
5936 if (Reduced.getNode())
5937 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00005938 // Handle the case where the load remains an extending load even
5939 // after truncation.
5940 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5941 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5942 if (!LN0->isVolatile() &&
5943 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5944 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5945 VT, LN0->getChain(), LN0->getBasePtr(),
5946 LN0->getMemoryVT(),
5947 LN0->getMemOperand());
5948 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5949 return NewLoad;
5950 }
5951 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005952 }
Michael Liao3ac82012012-10-17 23:45:54 +00005953 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5954 // where ... are all 'undef'.
5955 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5956 SmallVector<EVT, 8> VTs;
5957 SDValue V;
5958 unsigned Idx = 0;
5959 unsigned NumDefs = 0;
5960
5961 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5962 SDValue X = N0.getOperand(i);
5963 if (X.getOpcode() != ISD::UNDEF) {
5964 V = X;
5965 Idx = i;
5966 NumDefs++;
5967 }
5968 // Stop if more than one members are non-undef.
5969 if (NumDefs > 1)
5970 break;
5971 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5972 VT.getVectorElementType(),
5973 X.getValueType().getVectorNumElements()));
5974 }
5975
5976 if (NumDefs == 0)
5977 return DAG.getUNDEF(VT);
5978
5979 if (NumDefs == 1) {
5980 assert(V.getNode() && "The single defined operand is empty!");
5981 SmallVector<SDValue, 8> Opnds;
5982 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5983 if (i != Idx) {
5984 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5985 continue;
5986 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005987 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00005988 AddToWorkList(NV.getNode());
5989 Opnds.push_back(NV);
5990 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005991 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao3ac82012012-10-17 23:45:54 +00005992 &Opnds[0], Opnds.size());
5993 }
5994 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005995
5996 // Simplify the operands using demanded-bits information.
5997 if (!VT.isVector() &&
5998 SimplifyDemandedBits(SDValue(N, 0)))
5999 return SDValue(N, 0);
6000
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006001 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006002}
6003
Evan Chengb980f6f2008-05-12 23:04:07 +00006004static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006005 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006006 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006007 return Elt.getNode();
6008 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006009}
6010
6011/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006012/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006013SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006014 assert(N->getOpcode() == ISD::BUILD_PAIR);
6015
Nate Begeman624690c2009-06-05 21:37:30 +00006016 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6017 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006018 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006019 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006020 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006021 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006022
Evan Chengb980f6f2008-05-12 23:04:07 +00006023 if (ISD::isNON_EXTLoad(LD2) &&
6024 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006025 // If both are volatile this would reduce the number of volatile loads.
6026 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006027 !LD1->isVolatile() &&
6028 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006029 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006030 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006031 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006032 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006033
Duncan Sands8651e9c2008-06-13 19:07:40 +00006034 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006035 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006036 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006037 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006038 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006039 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006040
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006041 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006042}
6043
Wesley Peck527da1b2010-11-23 03:31:01 +00006044SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006045 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006046 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006047
Dan Gohmana8665142007-06-25 16:23:39 +00006048 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6049 // Only do this before legalize, since afterward the target may be depending
6050 // on the bitconvert.
6051 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006052 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006053 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006054 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006055 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006056
Owen Anderson53aa7a92009-08-10 22:56:29 +00006057 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006058 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006059 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006060 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006061 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006062 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006063
Dan Gohman921ddd62008-09-05 01:58:21 +00006064 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006065 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006066 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006067 if (Res.getNode() != N) {
6068 if (!LegalOperations ||
6069 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6070 return Res;
6071
6072 // Folding it resulted in an illegal node, and it's too late to
6073 // do that. Clean up the old node and forego the transformation.
6074 // Ideally this won't happen very often, because instcombine
6075 // and the earlier dagcombine runs (where illegal nodes are
6076 // permitted) should have folded most of them already.
6077 DAG.DeleteNode(Res.getNode());
6078 }
Chris Lattnera1874602005-12-23 05:30:37 +00006079 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006080
Bill Wendling4e0a6152009-01-30 22:44:24 +00006081 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006082 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006083 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006084 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006085
Chris Lattner54560f62005-12-23 05:44:41 +00006086 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006087 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006088 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006089 // Do not change the width of a volatile load.
6090 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006091 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6092 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006093 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006094 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006095 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006096 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006097
Evan Chenga4cf58a2007-05-07 21:27:48 +00006098 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006099 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006100 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006101 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006102 LN0->isInvariant(), OrigAlign,
6103 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006104 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006105 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006106 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006107 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006108 Load.getValue(1));
6109 return Load;
6110 }
Chris Lattner54560f62005-12-23 05:44:41 +00006111 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006112
Bill Wendling4e0a6152009-01-30 22:44:24 +00006113 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6114 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006115 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006116 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6117 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006118 N0.getNode()->hasOneUse() && VT.isInteger() &&
6119 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006120 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006121 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006122 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006123
Duncan Sands13237ac2008-06-06 12:08:01 +00006124 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006125 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006126 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006127 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006128 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006129 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006130 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006131 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006132
Bill Wendling4e0a6152009-01-30 22:44:24 +00006133 // fold (bitconvert (fcopysign cst, x)) ->
6134 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6135 // Note that we don't handle (copysign x, cst) because this can always be
6136 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006137 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006138 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006139 VT.isInteger() && !VT.isVector()) {
6140 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006141 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006142 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006143 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006144 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006145 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006146
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006147 // If X has a different width than the result/lhs, sext it or truncate it.
6148 unsigned VTWidth = VT.getSizeInBits();
6149 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006150 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006151 AddToWorkList(X.getNode());
6152 } else if (OrigXWidth > VTWidth) {
6153 // To get the sign bit in the right place, we have to shift it right
6154 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006155 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006156 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006157 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6158 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006159 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006160 AddToWorkList(X.getNode());
6161 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006162
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006163 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006164 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006165 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006166 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006167
Andrew Trickef9de2a2013-05-25 02:42:55 +00006168 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006169 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006170 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006171 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006172 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006173
Andrew Trickef9de2a2013-05-25 02:42:55 +00006174 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006175 }
Chris Lattner888560d2008-01-27 17:42:27 +00006176 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006177
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006178 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006179 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006180 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6181 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006182 return CombineLD;
6183 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006185 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006186}
6187
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006188SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006189 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006190 return CombineConsecutiveLoads(N, VT);
6191}
6192
Wesley Peck527da1b2010-11-23 03:31:01 +00006193/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006194/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006195/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006196SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006197ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006198 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006199
Chris Lattnere4e64b62006-04-02 02:53:43 +00006200 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006201 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006202
Duncan Sands13237ac2008-06-06 12:08:01 +00006203 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6204 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006205
Chris Lattnere4e64b62006-04-02 02:53:43 +00006206 // If this is a conversion of N elements of one type to N elements of another
6207 // type, convert each element. This handles FP<->INT cases.
6208 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006209 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6210 BV->getValueType(0).getVectorNumElements());
6211
6212 // Due to the FP element handling below calling this routine recursively,
6213 // we can end up with a scalar-to-vector node here.
6214 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006215 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6216 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006217 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006218
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006219 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006220 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006221 SDValue Op = BV->getOperand(i);
6222 // If the vector element type is not legal, the BUILD_VECTOR operands
6223 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006224 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006225 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6226 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006227 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006228 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006229 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006230 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006231 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006232 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006233
Chris Lattnere4e64b62006-04-02 02:53:43 +00006234 // Otherwise, we're growing or shrinking the elements. To avoid having to
6235 // handle annoying details of growing/shrinking FP values, we convert them to
6236 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006237 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006238 // Convert the input float vector to a int vector where the elements are the
6239 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006240 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006241 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006242 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006243 SrcEltVT = IntVT;
6244 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006245
Chris Lattnere4e64b62006-04-02 02:53:43 +00006246 // Now we know the input is an integer vector. If the output is a FP type,
6247 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006248 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006249 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006250 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006251 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006252
Chris Lattnere4e64b62006-04-02 02:53:43 +00006253 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006254 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006255 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006256
Chris Lattnere4e64b62006-04-02 02:53:43 +00006257 // Okay, we know the src/dst types are both integers of differing types.
6258 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006259 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006260 if (SrcBitSize < DstBitSize) {
6261 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006262
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006263 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006264 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006265 i += NumInputsPerOutput) {
6266 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006267 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006268 bool EltIsUndef = true;
6269 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6270 // Shift the previously computed bits over.
6271 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006272 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006273 if (Op.getOpcode() == ISD::UNDEF) continue;
6274 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006275
Jay Foad583abbc2010-12-07 08:25:19 +00006276 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006277 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006278 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006279
Chris Lattnere4e64b62006-04-02 02:53:43 +00006280 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006281 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006282 else
6283 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6284 }
6285
Owen Anderson117c9e82009-08-12 00:36:31 +00006286 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006287 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006288 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006289 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006290
Chris Lattnere4e64b62006-04-02 02:53:43 +00006291 // Finally, this must be the case where we are shrinking elements: each input
6292 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006293 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006294 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006295 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6296 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006297 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006298
Dan Gohmana8665142007-06-25 16:23:39 +00006299 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006300 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6301 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006302 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006303 continue;
6304 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006305
Jay Foad583abbc2010-12-07 08:25:19 +00006306 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6307 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006308
Chris Lattnere4e64b62006-04-02 02:53:43 +00006309 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006310 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006311 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006312 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006313 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006314 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006315 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006316 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006317 }
6318
6319 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006320 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006321 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6322 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006323
Andrew Trickef9de2a2013-05-25 02:42:55 +00006324 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006325 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006326}
6327
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006328SDValue DAGCombiner::visitFADD(SDNode *N) {
6329 SDValue N0 = N->getOperand(0);
6330 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006331 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6332 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006333 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006334
Dan Gohmana8665142007-06-25 16:23:39 +00006335 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006336 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006337 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006338 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006339 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006340
Lang Hamesa33db652012-06-14 20:37:15 +00006341 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006342 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006343 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006344 // canonicalize constant to RHS
6345 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006346 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006347 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006348 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6349 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006350 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006351 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006352 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006353 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006354 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006355 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006356 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006357 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006358 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006359 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006360 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006361
Chris Lattner0199fd62007-01-08 23:04:05 +00006362 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006363 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6364 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6365 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006366 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6367 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006368 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006369
Shuxin Yang93b1f122013-03-25 22:52:29 +00006370 // No FP constant should be created after legalization as Instruction
6371 // Selection pass has hard time in dealing with FP constant.
6372 //
6373 // We don't need test this condition for transformation like following, as
6374 // the DAG being transformed implies it is legal to take FP constant as
6375 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006376 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006377 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006378 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006379 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6380
Owen Andersonb351c8d2012-11-01 02:00:53 +00006381 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006382 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006383 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006384 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006385
6386 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006387 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006388 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006389 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006390
Owen Andersoncc61f872012-08-30 23:35:16 +00006391 // In unsafe math mode, we can fold chains of FADD's of the same value
6392 // into multiplications. This transform is not safe in general because
6393 // we are reducing the number of rounding steps.
6394 if (DAG.getTarget().Options.UnsafeFPMath &&
6395 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6396 !N0CFP && !N1CFP) {
6397 if (N0.getOpcode() == ISD::FMUL) {
6398 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6399 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6400
Stephen Line31f2d22013-06-14 18:17:35 +00006401 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006402 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006403 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006404 SDValue(CFP00, 0),
6405 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006406 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006407 N1, NewCFP);
6408 }
6409
Stephen Line31f2d22013-06-14 18:17:35 +00006410 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006411 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006412 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006413 SDValue(CFP01, 0),
6414 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006415 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006416 N1, NewCFP);
6417 }
6418
Stephen Line31f2d22013-06-14 18:17:35 +00006419 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006420 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6421 N1.getOperand(0) == N1.getOperand(1) &&
6422 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006423 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006424 SDValue(CFP00, 0),
6425 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006426 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006427 N0.getOperand(1), NewCFP);
6428 }
6429
Stephen Line31f2d22013-06-14 18:17:35 +00006430 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006431 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6432 N1.getOperand(0) == N1.getOperand(1) &&
6433 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006434 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006435 SDValue(CFP01, 0),
6436 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006437 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006438 N0.getOperand(0), NewCFP);
6439 }
6440 }
6441
6442 if (N1.getOpcode() == ISD::FMUL) {
6443 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6444 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6445
Stephen Line31f2d22013-06-14 18:17:35 +00006446 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006447 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006448 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006449 SDValue(CFP10, 0),
6450 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006451 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006452 N0, NewCFP);
6453 }
6454
Stephen Line31f2d22013-06-14 18:17:35 +00006455 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006456 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006457 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006458 SDValue(CFP11, 0),
6459 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006460 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006461 N0, NewCFP);
6462 }
6463
Owen Andersoncc61f872012-08-30 23:35:16 +00006464
Stephen Line31f2d22013-06-14 18:17:35 +00006465 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6466 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6467 N0.getOperand(0) == N0.getOperand(1) &&
6468 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006469 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006470 SDValue(CFP10, 0),
6471 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006472 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006473 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006474 }
6475
Stephen Line31f2d22013-06-14 18:17:35 +00006476 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6477 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6478 N0.getOperand(0) == N0.getOperand(1) &&
6479 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006480 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006481 SDValue(CFP11, 0),
6482 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006483 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006484 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006485 }
6486 }
6487
Shuxin Yang93b1f122013-03-25 22:52:29 +00006488 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006489 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006490 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006491 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006492 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006493 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006494 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006495 }
6496
Shuxin Yang93b1f122013-03-25 22:52:29 +00006497 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006498 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006499 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006500 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006501 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006502 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006503 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006504 }
6505
Stephen Lin4e69d012013-06-14 21:33:58 +00006506 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006507 if (AllowNewFpConst &&
6508 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006509 N0.getOperand(0) == N0.getOperand(1) &&
6510 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006511 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006512 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006513 N0.getOperand(0),
6514 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006515 }
6516
Lang Hames39fb1d02012-06-19 22:51:23 +00006517 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006518 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006519 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006520 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6521 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006522
6523 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006524 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006525 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006526 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006527
Michael Liaoec3850122012-09-01 04:09:16 +00006528 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006529 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006530 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006531 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006532 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006533 }
6534
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006535 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006536}
6537
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006538SDValue DAGCombiner::visitFSUB(SDNode *N) {
6539 SDValue N0 = N->getOperand(0);
6540 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006541 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6542 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006543 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006544 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006545
Dan Gohmana8665142007-06-25 16:23:39 +00006546 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006547 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006548 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006549 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006550 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006551
Nate Begeman418c6e42005-10-18 00:28:13 +00006552 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006553 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006554 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006555 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006556 if (DAG.getTarget().Options.UnsafeFPMath &&
6557 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006558 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006559 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006560 if (DAG.getTarget().Options.UnsafeFPMath &&
6561 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006562 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006563 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006564 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006565 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006566 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006567 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006568 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006569 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006570 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006571
Bill Wendlingdf170db2012-03-15 05:12:00 +00006572 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006573 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006574 // (fsub x, (fadd x, y)) -> (fneg y) &
6575 // (fsub x, (fadd y, x)) -> (fneg y)
6576 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006577 if (N0 == N1)
6578 return DAG.getConstantFP(0.0f, VT);
6579
Bill Wendlingdf170db2012-03-15 05:12:00 +00006580 if (N1.getOpcode() == ISD::FADD) {
6581 SDValue N10 = N1->getOperand(0);
6582 SDValue N11 = N1->getOperand(1);
6583
6584 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6585 &DAG.getTarget().Options))
6586 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006587
Stephen Lin8e8424e2013-07-09 00:44:49 +00006588 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6589 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006590 return GetNegatedExpression(N10, DAG, LegalOperations);
6591 }
6592 }
6593
Lang Hames39fb1d02012-06-19 22:51:23 +00006594 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006595 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006596 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006597 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6598 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006599
6600 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006601 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006602 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006603 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006604 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006605
6606 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6607 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006608 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006609 return DAG.getNode(ISD::FMA, dl, VT,
6610 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006611 N1.getOperand(0)),
6612 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006613
Stephen Lin8e8424e2013-07-09 00:44:49 +00006614 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006615 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006616 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6617 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6618 SDValue N00 = N0.getOperand(0).getOperand(0);
6619 SDValue N01 = N0.getOperand(0).getOperand(1);
6620 return DAG.getNode(ISD::FMA, dl, VT,
6621 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6622 DAG.getNode(ISD::FNEG, dl, VT, N1));
6623 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006624 }
6625
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006626 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006627}
6628
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006629SDValue DAGCombiner::visitFMUL(SDNode *N) {
6630 SDValue N0 = N->getOperand(0);
6631 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006632 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6633 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006634 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006635 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006636
Dan Gohmana8665142007-06-25 16:23:39 +00006637 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006638 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006639 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006640 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006641 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006642
Nate Begemanec48a1b2005-10-17 20:40:11 +00006643 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006644 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006645 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006646 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006647 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006648 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006649 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006650 if (DAG.getTarget().Options.UnsafeFPMath &&
6651 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006652 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006653 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006654 if (DAG.getTarget().Options.UnsafeFPMath &&
6655 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006656 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006657 // fold (fmul A, 1.0) -> A
6658 if (N1CFP && N1CFP->isExactlyValue(1.0))
6659 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006660 // fold (fmul X, 2.0) -> (fadd X, X)
6661 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006662 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006663 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006664 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006665 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006666 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006667
Bill Wendling3dc5d242009-01-30 22:57:07 +00006668 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006669 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006670 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006671 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006672 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006673 // Both can be negated for free, check to see if at least one is cheaper
6674 // negated.
6675 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006676 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006677 GetNegatedExpression(N0, DAG, LegalOperations),
6678 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006679 }
6680 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006681
Chris Lattner0199fd62007-01-08 23:04:05 +00006682 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006683 if (DAG.getTarget().Options.UnsafeFPMath &&
6684 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006685 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006686 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6687 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006688 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006689
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006690 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006691}
6692
Owen Anderson41b06652012-05-02 22:17:40 +00006693SDValue DAGCombiner::visitFMA(SDNode *N) {
6694 SDValue N0 = N->getOperand(0);
6695 SDValue N1 = N->getOperand(1);
6696 SDValue N2 = N->getOperand(2);
6697 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6698 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6699 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006700 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006701
Owen Andersonb351c8d2012-11-01 02:00:53 +00006702 if (DAG.getTarget().Options.UnsafeFPMath) {
6703 if (N0CFP && N0CFP->isZero())
6704 return N2;
6705 if (N1CFP && N1CFP->isZero())
6706 return N2;
6707 }
Owen Anderson41b06652012-05-02 22:17:40 +00006708 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006709 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006710 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006711 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006712
Owen Andersonc7aaf522012-05-30 18:50:39 +00006713 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006714 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006715 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006716
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006717 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6718 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6719 N2.getOpcode() == ISD::FMUL &&
6720 N0 == N2.getOperand(0) &&
6721 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6722 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6723 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6724 }
6725
6726
6727 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6728 if (DAG.getTarget().Options.UnsafeFPMath &&
6729 N0.getOpcode() == ISD::FMUL && N1CFP &&
6730 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6731 return DAG.getNode(ISD::FMA, dl, VT,
6732 N0.getOperand(0),
6733 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6734 N2);
6735 }
6736
6737 // (fma x, 1, y) -> (fadd x, y)
6738 // (fma x, -1, y) -> (fadd (fneg x), y)
6739 if (N1CFP) {
6740 if (N1CFP->isExactlyValue(1.0))
6741 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6742
6743 if (N1CFP->isExactlyValue(-1.0) &&
6744 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6745 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6746 AddToWorkList(RHSNeg.getNode());
6747 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6748 }
6749 }
6750
6751 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006752 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6753 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006754 DAG.getNode(ISD::FADD, dl, VT,
6755 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006756
6757 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6758 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006759 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6760 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006761 DAG.getNode(ISD::FADD, dl, VT,
6762 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006763
6764
Owen Anderson41b06652012-05-02 22:17:40 +00006765 return SDValue();
6766}
6767
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006768SDValue DAGCombiner::visitFDIV(SDNode *N) {
6769 SDValue N0 = N->getOperand(0);
6770 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006771 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6772 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006773 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006774 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006775
Dan Gohmana8665142007-06-25 16:23:39 +00006776 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006777 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006778 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006779 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006780 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006781
Nate Begeman569c4392006-01-18 22:35:16 +00006782 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006783 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006784 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006785
Duncan Sands2f1dc382012-04-08 18:08:12 +00006786 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006787 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006788 // Compute the reciprocal 1.0 / c2.
6789 APFloat N1APF = N1CFP->getValueAPF();
6790 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6791 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006792 // Only do the transform if the reciprocal is a legal fp immediate that
6793 // isn't too nasty (eg NaN, denormal, ...).
6794 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006795 (!LegalOperations ||
6796 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6797 // backend)... we should handle this gracefully after Legalize.
6798 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6799 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6800 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006801 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006802 DAG.getConstantFP(Recip, VT));
6803 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006804
Bill Wendling3dc5d242009-01-30 22:57:07 +00006805 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006806 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006807 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006808 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006809 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006810 // Both can be negated for free, check to see if at least one is cheaper
6811 // negated.
6812 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006813 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006814 GetNegatedExpression(N0, DAG, LegalOperations),
6815 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006816 }
6817 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006818
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006819 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006820}
6821
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006822SDValue DAGCombiner::visitFREM(SDNode *N) {
6823 SDValue N0 = N->getOperand(0);
6824 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006825 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6826 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006827 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006828
Nate Begeman569c4392006-01-18 22:35:16 +00006829 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006830 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006831 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006832
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006833 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006834}
6835
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006836SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6837 SDValue N0 = N->getOperand(0);
6838 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006839 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6840 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006841 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006842
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006843 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006844 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006845
Chris Lattner3bc40502006-03-05 05:30:57 +00006846 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006847 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006848 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6849 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006850 if (!V.isNegative()) {
6851 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006852 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006853 } else {
6854 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006855 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6856 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006857 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006858 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006859
Chris Lattner3bc40502006-03-05 05:30:57 +00006860 // copysign(fabs(x), y) -> copysign(x, y)
6861 // copysign(fneg(x), y) -> copysign(x, y)
6862 // copysign(copysign(x,z), y) -> copysign(x, y)
6863 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6864 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006865 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006866 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006867
6868 // copysign(x, abs(y)) -> abs(x)
6869 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006870 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006871
Chris Lattner3bc40502006-03-05 05:30:57 +00006872 // copysign(x, copysign(y,z)) -> copysign(x, z)
6873 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006874 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006875 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006876
Chris Lattner3bc40502006-03-05 05:30:57 +00006877 // copysign(x, fp_extend(y)) -> copysign(x, y)
6878 // copysign(x, fp_round(y)) -> copysign(x, y)
6879 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006880 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006881 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006882
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006883 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006884}
6885
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006886SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6887 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006888 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006889 EVT VT = N->getValueType(0);
6890 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006891
Nate Begeman21158fc2005-09-01 00:19:25 +00006892 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006893 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006894 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006895 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006896 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006897 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006898
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006899 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6900 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006901 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6902 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006903 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006904 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006905 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006906 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006907
Alp Tokercb402912014-01-24 17:20:08 +00006908 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006909 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6910 // having to say they don't support SELECT_CC on every type the DAG knows
6911 // about, since there is no way to mark an opcode illegal at all value types
6912 // (See also visitSELECT)
6913 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6914 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6915 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6916 !VT.isVector() &&
6917 (!LegalOperations ||
6918 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6919 SDValue Ops[] =
6920 { N0.getOperand(0), N0.getOperand(1),
6921 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6922 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006923 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006924 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006925
Nadav Rotem90560762012-07-23 07:59:50 +00006926 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6927 // (select_cc x, y, 1.0, 0.0,, cc)
6928 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6929 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6930 (!LegalOperations ||
6931 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6932 SDValue Ops[] =
6933 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6934 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6935 N0.getOperand(0).getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006936 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006937 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006938 }
6939
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006940 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006941}
6942
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006943SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6944 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006945 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006946 EVT VT = N->getValueType(0);
6947 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00006948
Nate Begeman21158fc2005-09-01 00:19:25 +00006949 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006950 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006951 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006952 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006953 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006954 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006955
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006956 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6957 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006958 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6959 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006960 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006961 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006962 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006963 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006964
Alp Tokercb402912014-01-24 17:20:08 +00006965 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006966 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6967 // having to say they don't support SELECT_CC on every type the DAG knows
6968 // about, since there is no way to mark an opcode illegal at all value types
6969 // (See also visitSELECT)
6970 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6971 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00006972
Nadav Rotem90560762012-07-23 07:59:50 +00006973 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6974 (!LegalOperations ||
6975 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6976 SDValue Ops[] =
6977 { N0.getOperand(0), N0.getOperand(1),
6978 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6979 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006980 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006981 }
6982 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006983
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006984 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006985}
6986
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006987SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6988 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006989 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006990 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006991
Nate Begeman21158fc2005-09-01 00:19:25 +00006992 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006993 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006994 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00006995
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006996 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006997}
6998
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006999SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7000 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007001 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007002 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007003
Nate Begeman21158fc2005-09-01 00:19:25 +00007004 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007005 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007006 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
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_ROUND(SDNode *N) {
7012 SDValue N0 = N->getOperand(0);
7013 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007014 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007015 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007016
Nate Begeman21158fc2005-09-01 00:19:25 +00007017 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007018 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007019 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007020
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007021 // fold (fp_round (fp_extend x)) -> x
7022 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7023 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007024
Chris Lattner0feb1b02008-01-24 06:45:35 +00007025 // fold (fp_round (fp_round x)) -> (fp_round x)
7026 if (N0.getOpcode() == ISD::FP_ROUND) {
7027 // This is a value preserving truncation if both round's are.
7028 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007029 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007030 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007031 DAG.getIntPtrConstant(IsTrunc));
7032 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007033
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007034 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007035 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007036 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007037 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007038 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007039 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007040 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007041 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007042
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007043 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007044}
7045
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007046SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7047 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007048 EVT VT = N->getValueType(0);
7049 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007050 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007051
Nate Begeman21158fc2005-09-01 00:19:25 +00007052 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007053 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007054 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007055 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007056 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007057
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007058 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007059}
7060
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007061SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7062 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007063 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007064 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007065
Chris Lattner5919b482007-12-29 06:55:23 +00007066 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007067 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007068 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007069 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007070
Nate Begeman21158fc2005-09-01 00:19:25 +00007071 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007072 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007073 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007074
7075 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7076 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007077 if (N0.getOpcode() == ISD::FP_ROUND
7078 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007079 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007080 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007081 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007082 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007083 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007084 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007085 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007086
Chris Lattner72733e52008-01-17 07:00:52 +00007087 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007088 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007089 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007090 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007091 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007092 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007093 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007094 LN0->getBasePtr(), N0.getValueType(),
7095 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007096 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007097 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007098 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007099 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007100 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007101 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007102 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007103
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007104 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007105}
7106
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007107SDValue DAGCombiner::visitFNEG(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007109 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007110
Craig Topper82384612012-09-11 01:45:21 +00007111 if (VT.isVector()) {
7112 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7113 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007114 }
7115
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007116 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7117 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007118 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007119
Chris Lattner888560d2008-01-27 17:42:27 +00007120 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7121 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007122 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007123 !VT.isVector() &&
7124 N0.getNode()->hasOneUse() &&
7125 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007126 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007127 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007128 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007129 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007130 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007131 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007132 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007133 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007134 }
7135 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007136
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007137 // (fneg (fmul c, x)) -> (fmul -c, x)
7138 if (N0.getOpcode() == ISD::FMUL) {
7139 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Lin8e8424e2013-07-09 00:44:49 +00007140 if (CFP1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007141 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007142 N0.getOperand(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007143 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007144 N0.getOperand(1)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007145 }
7146
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007147 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007148}
7149
Owen Andersona40319b2012-08-13 23:32:49 +00007150SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7151 SDValue N0 = N->getOperand(0);
7152 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7153 EVT VT = N->getValueType(0);
7154
7155 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007156 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007157 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007158
7159 return SDValue();
7160}
7161
7162SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7163 SDValue N0 = N->getOperand(0);
7164 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7165 EVT VT = N->getValueType(0);
7166
7167 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007168 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007169 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007170
7171 return SDValue();
7172}
7173
7174SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7175 SDValue N0 = N->getOperand(0);
7176 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7177 EVT VT = N->getValueType(0);
7178
7179 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007180 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007181 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007182
7183 return SDValue();
7184}
7185
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007186SDValue DAGCombiner::visitFABS(SDNode *N) {
7187 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007188 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007189 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007190
Craig Topper82384612012-09-11 01:45:21 +00007191 if (VT.isVector()) {
7192 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7193 if (FoldedVOp.getNode()) return FoldedVOp;
7194 }
7195
Nate Begeman21158fc2005-09-01 00:19:25 +00007196 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007197 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007198 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007199 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007200 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007201 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007202 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007203 // fold (fabs (fcopysign x, y)) -> (fabs x)
7204 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007205 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007206
Chris Lattner888560d2008-01-27 17:42:27 +00007207 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7208 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007209 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007210 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007211 N0.getOperand(0).getValueType().isInteger() &&
7212 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007213 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007214 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007215 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007216 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007217 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007218 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007219 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007220 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007221 }
7222 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007223
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007224 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007225}
7226
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007227SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7228 SDValue Chain = N->getOperand(0);
7229 SDValue N1 = N->getOperand(1);
7230 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007231
Dan Gohman82e80012009-11-17 00:47:23 +00007232 // If N is a constant we could fold this into a fallthrough or unconditional
7233 // branch. However that doesn't happen very often in normal code, because
7234 // Instcombine/SimplifyCFG should have handled the available opportunities.
7235 // If we did this folding here, it would be necessary to update the
7236 // MachineBasicBlock CFG, which is awkward.
7237
Nate Begeman7e7f4392006-02-01 07:19:44 +00007238 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7239 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007240 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007241 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7242 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007243 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007244 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007245 N1.getOperand(0), N1.getOperand(1), N2);
7246 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007247
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007248 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7249 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7250 (N1.getOperand(0).hasOneUse() &&
7251 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7252 SDNode *Trunc = 0;
7253 if (N1.getOpcode() == ISD::TRUNCATE) {
7254 // Look pass the truncate.
7255 Trunc = N1.getNode();
7256 N1 = N1.getOperand(0);
7257 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007258
Bill Wendlingaa28be62009-03-26 06:14:09 +00007259 // Match this pattern so that we can generate simpler code:
7260 //
7261 // %a = ...
7262 // %b = and i32 %a, 2
7263 // %c = srl i32 %b, 1
7264 // brcond i32 %c ...
7265 //
7266 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007267 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007268 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007269 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007270 // %c = setcc eq %b, 0
7271 // brcond %c ...
7272 //
7273 // This applies only when the AND constant value has one bit set and the
7274 // SRL constant is equal to the log2 of the AND constant. The back-end is
7275 // smart enough to convert the result into a TEST/JMP sequence.
7276 SDValue Op0 = N1.getOperand(0);
7277 SDValue Op1 = N1.getOperand(1);
7278
7279 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007280 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007281 SDValue AndOp1 = Op0.getOperand(1);
7282
7283 if (AndOp1.getOpcode() == ISD::Constant) {
7284 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7285
7286 if (AndConst.isPowerOf2() &&
7287 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7288 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007289 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007290 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007291 Op0, DAG.getConstant(0, Op0.getValueType()),
7292 ISD::SETNE);
7293
Andrew Trickef9de2a2013-05-25 02:42:55 +00007294 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007295 MVT::Other, Chain, SetCC, N2);
7296 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7297 // will convert it back to (X & C1) >> C2.
7298 CombineTo(N, NewBRCond, false);
7299 // Truncate is dead.
7300 if (Trunc) {
7301 removeFromWorkList(Trunc);
7302 DAG.DeleteNode(Trunc);
7303 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007304 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007305 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007306 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007307 removeFromWorkList(N1.getNode());
7308 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007309 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007310 }
7311 }
7312 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007313
7314 if (Trunc)
7315 // Restore N1 if the above transformation doesn't match.
7316 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007317 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007318
Evan Cheng228c31f2010-02-27 07:36:59 +00007319 // Transform br(xor(x, y)) -> br(x != y)
7320 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7321 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7322 SDNode *TheXor = N1.getNode();
7323 SDValue Op0 = TheXor->getOperand(0);
7324 SDValue Op1 = TheXor->getOperand(1);
7325 if (Op0.getOpcode() == Op1.getOpcode()) {
7326 // Avoid missing important xor optimizations.
7327 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007328 if (Tmp.getNode()) {
7329 if (Tmp.getNode() != TheXor) {
7330 DEBUG(dbgs() << "\nReplacing.8 ";
7331 TheXor->dump(&DAG);
7332 dbgs() << "\nWith: ";
7333 Tmp.getNode()->dump(&DAG);
7334 dbgs() << '\n');
7335 WorkListRemover DeadNodes(*this);
7336 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7337 removeFromWorkList(TheXor);
7338 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007339 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007340 MVT::Other, Chain, Tmp, N2);
7341 }
7342
Benjamin Kramer93354432013-03-30 21:28:18 +00007343 // visitXOR has changed XOR's operands or replaced the XOR completely,
7344 // bail out.
7345 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007346 }
7347 }
7348
7349 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7350 bool Equal = false;
7351 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7352 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7353 Op0.getOpcode() == ISD::XOR) {
7354 TheXor = Op0.getNode();
7355 Equal = true;
7356 }
7357
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007358 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007359 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007360 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007361 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007362 SetCCVT,
7363 Op0, Op1,
7364 Equal ? ISD::SETEQ : ISD::SETNE);
7365 // Replace the uses of XOR with SETCC
7366 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007367 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007368 removeFromWorkList(N1.getNode());
7369 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007370 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007371 MVT::Other, Chain, SetCC, N2);
7372 }
7373 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007374
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007375 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007376}
7377
Chris Lattnera49e16f2005-10-05 06:47:48 +00007378// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7379//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007380SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007381 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007382 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007383
Dan Gohman82e80012009-11-17 00:47:23 +00007384 // If N is a constant we could fold this into a fallthrough or unconditional
7385 // branch. However that doesn't happen very often in normal code, because
7386 // Instcombine/SimplifyCFG should have handled the available opportunities.
7387 // If we did this folding here, it would be necessary to update the
7388 // MachineBasicBlock CFG, which is awkward.
7389
Duncan Sands93b66092008-06-09 11:32:28 +00007390 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007391 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007392 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007393 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007394 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007395
Nate Begemanbd7df032005-10-05 21:43:42 +00007396 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007397 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007398 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007399 N->getOperand(0), Simp.getOperand(2),
7400 Simp.getOperand(0), Simp.getOperand(1),
7401 N->getOperand(4));
7402
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007403 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007404}
7405
Evan Chengfa832632012-01-13 01:37:24 +00007406/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7407/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007408/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007409static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7410 SelectionDAG &DAG,
7411 const TargetLowering &TLI) {
7412 EVT VT;
7413 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7414 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7415 return false;
7416 VT = Use->getValueType(0);
7417 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7418 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7419 return false;
7420 VT = ST->getValue().getValueType();
7421 } else
7422 return false;
7423
Chandler Carruth95f83e02013-01-07 15:14:13 +00007424 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007425 if (N->getOpcode() == ISD::ADD) {
7426 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7427 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007428 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007429 AM.BaseOffs = Offset->getSExtValue();
7430 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007431 // [reg +/- reg]
7432 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007433 } else if (N->getOpcode() == ISD::SUB) {
7434 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7435 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007436 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007437 AM.BaseOffs = -Offset->getSExtValue();
7438 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007439 // [reg +/- reg]
7440 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007441 } else
7442 return false;
7443
7444 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7445}
7446
Duncan Sands075293f2008-06-15 20:12:31 +00007447/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7448/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007449/// and it has other uses besides the load / store. After the
7450/// transformation, the new indexed load / store has effectively folded
7451/// the add / subtract in and all of its other uses are redirected to the
7452/// new load / store.
7453bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007454 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007455 return false;
7456
7457 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007458 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007459 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007460 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007461 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007462 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007463 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007464 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007465 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7466 return false;
7467 Ptr = LD->getBasePtr();
7468 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007469 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007470 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007471 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007472 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7473 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7474 return false;
7475 Ptr = ST->getBasePtr();
7476 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007477 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007478 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007479 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007480
Chris Lattnereabc15c2006-11-11 00:56:29 +00007481 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7482 // out. There is no reason to make this a preinc/predec.
7483 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007484 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007485 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007486
Chris Lattnereabc15c2006-11-11 00:56:29 +00007487 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007488 SDValue BasePtr;
7489 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007490 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7491 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7492 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007493
7494 // Backends without true r+i pre-indexed forms may need to pass a
7495 // constant base with a variable offset so that constant coercion
7496 // will work with the patterns in canonical form.
7497 bool Swapped = false;
7498 if (isa<ConstantSDNode>(BasePtr)) {
7499 std::swap(BasePtr, Offset);
7500 Swapped = true;
7501 }
7502
Evan Cheng044a0a82007-05-03 23:52:19 +00007503 // Don't create a indexed load / store with zero offset.
7504 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007505 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007506 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007507
Chris Lattnera0a80032006-11-11 01:00:15 +00007508 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007509 // 1) The new base ptr is a frame index.
7510 // 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 +00007511 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007512 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007513 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007514 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007515
Chris Lattnera0a80032006-11-11 01:00:15 +00007516 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7517 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007518 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007519 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007520
Chris Lattnera0a80032006-11-11 01:00:15 +00007521 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007522 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007523 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007524 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007525 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007526 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007527
Hal Finkel25819052013-02-08 21:35:47 +00007528 // If the offset is a constant, there may be other adds of constants that
7529 // can be folded with this one. We should do this to avoid having to keep
7530 // a copy of the original base pointer.
7531 SmallVector<SDNode *, 16> OtherUses;
7532 if (isa<ConstantSDNode>(Offset))
7533 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7534 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7535 SDNode *Use = *I;
7536 if (Use == Ptr.getNode())
7537 continue;
7538
7539 if (Use->isPredecessorOf(N))
7540 continue;
7541
7542 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7543 OtherUses.clear();
7544 break;
7545 }
7546
7547 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7548 if (Op1.getNode() == BasePtr.getNode())
7549 std::swap(Op0, Op1);
7550 assert(Op0.getNode() == BasePtr.getNode() &&
7551 "Use of ADD/SUB but not an operand");
7552
7553 if (!isa<ConstantSDNode>(Op1)) {
7554 OtherUses.clear();
7555 break;
7556 }
7557
7558 // FIXME: In some cases, we can be smarter about this.
7559 if (Op1.getValueType() != Offset.getValueType()) {
7560 OtherUses.clear();
7561 break;
7562 }
7563
7564 OtherUses.push_back(Use);
7565 }
7566
7567 if (Swapped)
7568 std::swap(BasePtr, Offset);
7569
Evan Chenga4d187b2007-05-24 02:35:39 +00007570 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007571 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007572
7573 // Caches for hasPredecessorHelper
7574 SmallPtrSet<const SDNode *, 32> Visited;
7575 SmallVector<const SDNode *, 16> Worklist;
7576
Gabor Greiff304a7a2008-08-28 21:40:38 +00007577 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7578 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007579 SDNode *Use = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007580 if (Use == N)
7581 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007582 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007583 return false;
7584
Evan Chengfa832632012-01-13 01:37:24 +00007585 // If Ptr may be folded in addressing mode of other use, then it's
7586 // not profitable to do this transformation.
7587 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007588 RealUse = true;
7589 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007590
Chris Lattnereabc15c2006-11-11 00:56:29 +00007591 if (!RealUse)
7592 return false;
7593
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007594 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007595 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007596 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007597 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007598 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007599 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007600 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007601 ++PreIndexedNodes;
7602 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007603 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007604 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007605 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007606 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007607 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007608 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007609 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007610 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7611 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007612 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007613 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007614 }
7615
Chris Lattnereabc15c2006-11-11 00:56:29 +00007616 // Finally, since the node is now dead, remove it from the graph.
7617 DAG.DeleteNode(N);
7618
Hal Finkel25819052013-02-08 21:35:47 +00007619 if (Swapped)
7620 std::swap(BasePtr, Offset);
7621
7622 // Replace other uses of BasePtr that can be updated to use Ptr
7623 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7624 unsigned OffsetIdx = 1;
7625 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7626 OffsetIdx = 0;
7627 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7628 BasePtr.getNode() && "Expected BasePtr operand");
7629
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007630 // We need to replace ptr0 in the following expression:
7631 // x0 * offset0 + y0 * ptr0 = t0
7632 // knowing that
7633 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007634 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007635 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7636 // indexed load/store and the expresion that needs to be re-written.
7637 //
7638 // Therefore, we have:
7639 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007640
7641 ConstantSDNode *CN =
7642 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007643 int X0, X1, Y0, Y1;
7644 APInt Offset0 = CN->getAPIntValue();
7645 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007646
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007647 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7648 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7649 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7650 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007651
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007652 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7653
7654 APInt CNV = Offset0;
7655 if (X0 < 0) CNV = -CNV;
7656 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7657 else CNV = CNV - Offset1;
7658
7659 // We can now generate the new expression.
7660 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7661 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7662
7663 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007664 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007665 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7666 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7667 removeFromWorkList(OtherUses[i]);
7668 DAG.DeleteNode(OtherUses[i]);
7669 }
7670
Chris Lattnereabc15c2006-11-11 00:56:29 +00007671 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007672 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007673 removeFromWorkList(Ptr.getNode());
7674 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007675
7676 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007677}
7678
Duncan Sands075293f2008-06-15 20:12:31 +00007679/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007680/// add / sub of the base pointer node into a post-indexed load / store.
7681/// The transformation folded the add / subtract into the new indexed
7682/// load / store effectively and all of its uses are redirected to the
7683/// new load / store.
7684bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007685 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007686 return false;
7687
7688 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007689 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007690 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007691 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007692 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007693 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007694 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007695 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7696 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7697 return false;
7698 Ptr = LD->getBasePtr();
7699 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007700 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007701 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007702 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007703 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7704 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7705 return false;
7706 Ptr = ST->getBasePtr();
7707 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007708 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007709 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007710 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007711
Gabor Greiff304a7a2008-08-28 21:40:38 +00007712 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007713 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007714
Gabor Greiff304a7a2008-08-28 21:40:38 +00007715 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7716 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007717 SDNode *Op = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007718 if (Op == N ||
7719 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7720 continue;
7721
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007722 SDValue BasePtr;
7723 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007724 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7725 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007726 // Don't create a indexed load / store with zero offset.
7727 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007728 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007729 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007730
Chris Lattnereabc15c2006-11-11 00:56:29 +00007731 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007732 // 1) All uses are load / store ops that use it as base ptr (and
7733 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007734 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7735 // nor a successor of N. Otherwise, if Op is folded that would
7736 // create a cycle.
7737
Evan Chengcfc05132009-05-06 18:25:01 +00007738 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7739 continue;
7740
Chris Lattnereabc15c2006-11-11 00:56:29 +00007741 // Check for #1.
7742 bool TryNext = false;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007743 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7744 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007745 SDNode *Use = *II;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007746 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007747 continue;
7748
Chris Lattnereabc15c2006-11-11 00:56:29 +00007749 // If all the uses are load / store addresses, then don't do the
7750 // transformation.
7751 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7752 bool RealUse = false;
7753 for (SDNode::use_iterator III = Use->use_begin(),
7754 EEE = Use->use_end(); III != EEE; ++III) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007755 SDNode *UseUse = *III;
Stephen Lincfe7f352013-07-08 00:37:03 +00007756 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007757 RealUse = true;
7758 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007759
Chris Lattnereabc15c2006-11-11 00:56:29 +00007760 if (!RealUse) {
7761 TryNext = true;
7762 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007763 }
7764 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007765 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007766
Chris Lattnereabc15c2006-11-11 00:56:29 +00007767 if (TryNext)
7768 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007769
Chris Lattnereabc15c2006-11-11 00:56:29 +00007770 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007771 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007772 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007773 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007774 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007775 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007776 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007777 ++PostIndexedNodes;
7778 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007779 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007780 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007781 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007782 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007783 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007784 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007785 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007786 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7787 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007788 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007789 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007790 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007791
Chris Lattnereabc15c2006-11-11 00:56:29 +00007792 // Finally, since the node is now dead, remove it from the graph.
7793 DAG.DeleteNode(N);
7794
7795 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007796 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007797 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007798 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007799 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007800 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007801 }
7802 }
7803 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007804
Chris Lattnerffad2162006-11-11 00:39:41 +00007805 return false;
7806}
7807
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007808SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007809 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007810 SDValue Chain = LD->getChain();
7811 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007812
Evan Chenga684cd22007-05-01 00:38:21 +00007813 // If load is not volatile and there are no uses of the loaded value (and
7814 // the updated indexed value in case of indexed loads), change uses of the
7815 // chain value into uses of the chain input (i.e. delete the dead load).
7816 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007817 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007818 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007819 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007820 // It's not safe to use the two value CombineTo variant here. e.g.
7821 // v1, chain2 = load chain1, loc
7822 // v2, chain3 = load chain2, loc
7823 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007824 // Now we replace use of chain2 with chain1. This makes the second load
7825 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007826 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007827 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007828 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007829 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007830 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007831 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007832 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007833
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007834 if (N->use_empty()) {
7835 removeFromWorkList(N);
7836 DAG.DeleteNode(N);
7837 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007838
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007839 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007840 }
Evan Chengb68343c2007-05-01 08:53:39 +00007841 } else {
7842 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007843 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper0515cd42012-01-07 18:31:09 +00007844 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007845 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007846 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007847 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007848 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007849 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007850 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007851 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007852 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007853 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007854 DAG.getUNDEF(N->getValueType(1)));
7855 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007856 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007857 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007858 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007859 }
Evan Chenga684cd22007-05-01 00:38:21 +00007860 }
7861 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007862
Chris Lattnere260ed82005-10-10 22:04:48 +00007863 // If this load is directly stored, replace the load value with the stored
7864 // value.
7865 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007866 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007867 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007868 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007869 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7870 if (PrevST->getBasePtr() == Ptr &&
7871 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007872 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007873 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007874 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007875
Evan Cheng43cd9e32010-04-01 06:04:33 +00007876 // Try to infer better alignment information than the load already has.
7877 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007878 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007879 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7880 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007881 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007882 LD->getValueType(0),
7883 Chain, Ptr, LD->getPointerInfo(),
7884 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007885 LD->isVolatile(), LD->isNonTemporal(), Align,
7886 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007887 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7888 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007889 }
7890 }
7891
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007892 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7893 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00007894#ifndef NDEBUG
7895 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7896 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7897 UseAA = false;
7898#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00007899 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007900 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007901 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007902
Jim Laskey708d0db2006-10-04 16:53:27 +00007903 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007904 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007905 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007906
Jim Laskeyd07be232006-09-25 16:29:54 +00007907 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007908 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007909 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007910 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007911 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007912 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007913 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007914 BetterChain, Ptr, LD->getMemoryVT(),
7915 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007916 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007917
Jim Laskey708d0db2006-10-04 16:53:27 +00007918 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007919 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007920 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007921
Nate Begeman879d8f12009-09-15 00:18:30 +00007922 // Make sure the new and old chains are cleaned up.
7923 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007924
Jim Laskeydcf983c2006-10-13 23:32:28 +00007925 // Replace uses with load result and token factor. Don't add users
7926 // to work list.
7927 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00007928 }
7929 }
7930
Evan Cheng357017f2006-11-03 03:06:21 +00007931 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00007932 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007933 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00007934
Quentin Colombetde0e0622013-10-11 18:29:42 +00007935 // Try to slice up N to more direct loads if the slices are mapped to
7936 // different register banks or pairing can take place.
7937 if (SliceUpLoad(N))
7938 return SDValue(N, 0);
7939
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007940 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00007941}
7942
Quentin Colombetde0e0622013-10-11 18:29:42 +00007943namespace {
7944/// \brief Helper structure used to slice a load in smaller loads.
7945/// Basically a slice is obtained from the following sequence:
7946/// Origin = load Ty1, Base
7947/// Shift = srl Ty1 Origin, CstTy Amount
7948/// Inst = trunc Shift to Ty2
7949///
7950/// Then, it will be rewriten into:
7951/// Slice = load SliceTy, Base + SliceOffset
7952/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7953///
7954/// SliceTy is deduced from the number of bits that are actually used to
7955/// build Inst.
7956struct LoadedSlice {
7957 /// \brief Helper structure used to compute the cost of a slice.
7958 struct Cost {
7959 /// Are we optimizing for code size.
7960 bool ForCodeSize;
7961 /// Various cost.
7962 unsigned Loads;
7963 unsigned Truncates;
7964 unsigned CrossRegisterBanksCopies;
7965 unsigned ZExts;
7966 unsigned Shift;
7967
7968 Cost(bool ForCodeSize = false)
7969 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7970 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7971
7972 /// \brief Get the cost of one isolated slice.
7973 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7974 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7975 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7976 EVT TruncType = LS.Inst->getValueType(0);
7977 EVT LoadedType = LS.getLoadedType();
7978 if (TruncType != LoadedType &&
7979 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7980 ZExts = 1;
7981 }
7982
7983 /// \brief Account for slicing gain in the current cost.
7984 /// Slicing provide a few gains like removing a shift or a
7985 /// truncate. This method allows to grow the cost of the original
7986 /// load with the gain from this slice.
7987 void addSliceGain(const LoadedSlice &LS) {
7988 // Each slice saves a truncate.
7989 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7990 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7991 LS.Inst->getOperand(0).getValueType()))
7992 ++Truncates;
7993 // If there is a shift amount, this slice gets rid of it.
7994 if (LS.Shift)
7995 ++Shift;
7996 // If this slice can merge a cross register bank copy, account for it.
7997 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7998 ++CrossRegisterBanksCopies;
7999 }
8000
8001 Cost &operator+=(const Cost &RHS) {
8002 Loads += RHS.Loads;
8003 Truncates += RHS.Truncates;
8004 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8005 ZExts += RHS.ZExts;
8006 Shift += RHS.Shift;
8007 return *this;
8008 }
8009
8010 bool operator==(const Cost &RHS) const {
8011 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8012 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8013 ZExts == RHS.ZExts && Shift == RHS.Shift;
8014 }
8015
8016 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8017
8018 bool operator<(const Cost &RHS) const {
8019 // Assume cross register banks copies are as expensive as loads.
8020 // FIXME: Do we want some more target hooks?
8021 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8022 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8023 // Unless we are optimizing for code size, consider the
8024 // expensive operation first.
8025 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8026 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8027 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8028 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8029 }
8030
8031 bool operator>(const Cost &RHS) const { return RHS < *this; }
8032
8033 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8034
8035 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8036 };
8037 // The last instruction that represent the slice. This should be a
8038 // truncate instruction.
8039 SDNode *Inst;
8040 // The original load instruction.
8041 LoadSDNode *Origin;
8042 // The right shift amount in bits from the original load.
8043 unsigned Shift;
8044 // The DAG from which Origin came from.
8045 // This is used to get some contextual information about legal types, etc.
8046 SelectionDAG *DAG;
8047
8048 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8049 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8050 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8051
8052 LoadedSlice(const LoadedSlice &LS)
8053 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8054
8055 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8056 /// \return Result is \p BitWidth and has used bits set to 1 and
8057 /// not used bits set to 0.
8058 APInt getUsedBits() const {
8059 // Reproduce the trunc(lshr) sequence:
8060 // - Start from the truncated value.
8061 // - Zero extend to the desired bit width.
8062 // - Shift left.
8063 assert(Origin && "No original load to compare against.");
8064 unsigned BitWidth = Origin->getValueSizeInBits(0);
8065 assert(Inst && "This slice is not bound to an instruction");
8066 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8067 "Extracted slice is bigger than the whole type!");
8068 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8069 UsedBits.setAllBits();
8070 UsedBits = UsedBits.zext(BitWidth);
8071 UsedBits <<= Shift;
8072 return UsedBits;
8073 }
8074
8075 /// \brief Get the size of the slice to be loaded in bytes.
8076 unsigned getLoadedSize() const {
8077 unsigned SliceSize = getUsedBits().countPopulation();
8078 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8079 return SliceSize / 8;
8080 }
8081
8082 /// \brief Get the type that will be loaded for this slice.
8083 /// Note: This may not be the final type for the slice.
8084 EVT getLoadedType() const {
8085 assert(DAG && "Missing context");
8086 LLVMContext &Ctxt = *DAG->getContext();
8087 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8088 }
8089
8090 /// \brief Get the alignment of the load used for this slice.
8091 unsigned getAlignment() const {
8092 unsigned Alignment = Origin->getAlignment();
8093 unsigned Offset = getOffsetFromBase();
8094 if (Offset != 0)
8095 Alignment = MinAlign(Alignment, Alignment + Offset);
8096 return Alignment;
8097 }
8098
8099 /// \brief Check if this slice can be rewritten with legal operations.
8100 bool isLegal() const {
8101 // An invalid slice is not legal.
8102 if (!Origin || !Inst || !DAG)
8103 return false;
8104
8105 // Offsets are for indexed load only, we do not handle that.
8106 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8107 return false;
8108
8109 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8110
8111 // Check that the type is legal.
8112 EVT SliceType = getLoadedType();
8113 if (!TLI.isTypeLegal(SliceType))
8114 return false;
8115
8116 // Check that the load is legal for this type.
8117 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8118 return false;
8119
8120 // Check that the offset can be computed.
8121 // 1. Check its type.
8122 EVT PtrType = Origin->getBasePtr().getValueType();
8123 if (PtrType == MVT::Untyped || PtrType.isExtended())
8124 return false;
8125
8126 // 2. Check that it fits in the immediate.
8127 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8128 return false;
8129
8130 // 3. Check that the computation is legal.
8131 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8132 return false;
8133
8134 // Check that the zext is legal if it needs one.
8135 EVT TruncateType = Inst->getValueType(0);
8136 if (TruncateType != SliceType &&
8137 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8138 return false;
8139
8140 return true;
8141 }
8142
8143 /// \brief Get the offset in bytes of this slice in the original chunk of
8144 /// bits.
8145 /// \pre DAG != NULL.
8146 uint64_t getOffsetFromBase() const {
8147 assert(DAG && "Missing context.");
8148 bool IsBigEndian =
8149 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8150 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8151 uint64_t Offset = Shift / 8;
8152 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8153 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8154 "The size of the original loaded type is not a multiple of a"
8155 " byte.");
8156 // If Offset is bigger than TySizeInBytes, it means we are loading all
8157 // zeros. This should have been optimized before in the process.
8158 assert(TySizeInBytes > Offset &&
8159 "Invalid shift amount for given loaded size");
8160 if (IsBigEndian)
8161 Offset = TySizeInBytes - Offset - getLoadedSize();
8162 return Offset;
8163 }
8164
8165 /// \brief Generate the sequence of instructions to load the slice
8166 /// represented by this object and redirect the uses of this slice to
8167 /// this new sequence of instructions.
8168 /// \pre this->Inst && this->Origin are valid Instructions and this
8169 /// object passed the legal check: LoadedSlice::isLegal returned true.
8170 /// \return The last instruction of the sequence used to load the slice.
8171 SDValue loadSlice() const {
8172 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8173 const SDValue &OldBaseAddr = Origin->getBasePtr();
8174 SDValue BaseAddr = OldBaseAddr;
8175 // Get the offset in that chunk of bytes w.r.t. the endianess.
8176 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8177 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8178 if (Offset) {
8179 // BaseAddr = BaseAddr + Offset.
8180 EVT ArithType = BaseAddr.getValueType();
8181 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8182 DAG->getConstant(Offset, ArithType));
8183 }
8184
8185 // Create the type of the loaded slice according to its size.
8186 EVT SliceType = getLoadedType();
8187
8188 // Create the load for the slice.
8189 SDValue LastInst = DAG->getLoad(
8190 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8191 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8192 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8193 // If the final type is not the same as the loaded type, this means that
8194 // we have to pad with zero. Create a zero extend for that.
8195 EVT FinalType = Inst->getValueType(0);
8196 if (SliceType != FinalType)
8197 LastInst =
8198 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8199 return LastInst;
8200 }
8201
8202 /// \brief Check if this slice can be merged with an expensive cross register
8203 /// bank copy. E.g.,
8204 /// i = load i32
8205 /// f = bitcast i32 i to float
8206 bool canMergeExpensiveCrossRegisterBankCopy() const {
8207 if (!Inst || !Inst->hasOneUse())
8208 return false;
8209 SDNode *Use = *Inst->use_begin();
8210 if (Use->getOpcode() != ISD::BITCAST)
8211 return false;
8212 assert(DAG && "Missing context");
8213 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8214 EVT ResVT = Use->getValueType(0);
8215 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8216 const TargetRegisterClass *ArgRC =
8217 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8218 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8219 return false;
8220
8221 // At this point, we know that we perform a cross-register-bank copy.
8222 // Check if it is expensive.
8223 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8224 // Assume bitcasts are cheap, unless both register classes do not
8225 // explicitly share a common sub class.
8226 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8227 return false;
8228
8229 // Check if it will be merged with the load.
8230 // 1. Check the alignment constraint.
8231 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8232 ResVT.getTypeForEVT(*DAG->getContext()));
8233
8234 if (RequiredAlignment > getAlignment())
8235 return false;
8236
8237 // 2. Check that the load is a legal operation for that type.
8238 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8239 return false;
8240
8241 // 3. Check that we do not have a zext in the way.
8242 if (Inst->getValueType(0) != getLoadedType())
8243 return false;
8244
8245 return true;
8246 }
8247};
8248}
8249
Quentin Colombetde0e0622013-10-11 18:29:42 +00008250/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8251/// \p UsedBits looks like 0..0 1..1 0..0.
8252static bool areUsedBitsDense(const APInt &UsedBits) {
8253 // If all the bits are one, this is dense!
8254 if (UsedBits.isAllOnesValue())
8255 return true;
8256
8257 // Get rid of the unused bits on the right.
8258 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8259 // Get rid of the unused bits on the left.
8260 if (NarrowedUsedBits.countLeadingZeros())
8261 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8262 // Check that the chunk of bits is completely used.
8263 return NarrowedUsedBits.isAllOnesValue();
8264}
8265
8266/// \brief Check whether or not \p First and \p Second are next to each other
8267/// in memory. This means that there is no hole between the bits loaded
8268/// by \p First and the bits loaded by \p Second.
8269static bool areSlicesNextToEachOther(const LoadedSlice &First,
8270 const LoadedSlice &Second) {
8271 assert(First.Origin == Second.Origin && First.Origin &&
8272 "Unable to match different memory origins.");
8273 APInt UsedBits = First.getUsedBits();
8274 assert((UsedBits & Second.getUsedBits()) == 0 &&
8275 "Slices are not supposed to overlap.");
8276 UsedBits |= Second.getUsedBits();
8277 return areUsedBitsDense(UsedBits);
8278}
8279
8280/// \brief Adjust the \p GlobalLSCost according to the target
8281/// paring capabilities and the layout of the slices.
8282/// \pre \p GlobalLSCost should account for at least as many loads as
8283/// there is in the slices in \p LoadedSlices.
8284static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8285 LoadedSlice::Cost &GlobalLSCost) {
8286 unsigned NumberOfSlices = LoadedSlices.size();
8287 // If there is less than 2 elements, no pairing is possible.
8288 if (NumberOfSlices < 2)
8289 return;
8290
8291 // Sort the slices so that elements that are likely to be next to each
8292 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008293 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8294 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8295 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8296 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8297 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008298 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8299 // First (resp. Second) is the first (resp. Second) potentially candidate
8300 // to be placed in a paired load.
8301 const LoadedSlice *First = NULL;
8302 const LoadedSlice *Second = NULL;
8303 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8304 // Set the beginning of the pair.
8305 First = Second) {
8306
8307 Second = &LoadedSlices[CurrSlice];
8308
8309 // If First is NULL, it means we start a new pair.
8310 // Get to the next slice.
8311 if (!First)
8312 continue;
8313
8314 EVT LoadedType = First->getLoadedType();
8315
8316 // If the types of the slices are different, we cannot pair them.
8317 if (LoadedType != Second->getLoadedType())
8318 continue;
8319
8320 // Check if the target supplies paired loads for this type.
8321 unsigned RequiredAlignment = 0;
8322 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8323 // move to the next pair, this type is hopeless.
8324 Second = NULL;
8325 continue;
8326 }
8327 // Check if we meet the alignment requirement.
8328 if (RequiredAlignment > First->getAlignment())
8329 continue;
8330
8331 // Check that both loads are next to each other in memory.
8332 if (!areSlicesNextToEachOther(*First, *Second))
8333 continue;
8334
8335 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8336 --GlobalLSCost.Loads;
8337 // Move to the next pair.
8338 Second = NULL;
8339 }
8340}
8341
8342/// \brief Check the profitability of all involved LoadedSlice.
8343/// Currently, it is considered profitable if there is exactly two
8344/// involved slices (1) which are (2) next to each other in memory, and
8345/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8346///
8347/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8348/// the elements themselves.
8349///
8350/// FIXME: When the cost model will be mature enough, we can relax
8351/// constraints (1) and (2).
8352static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8353 const APInt &UsedBits, bool ForCodeSize) {
8354 unsigned NumberOfSlices = LoadedSlices.size();
8355 if (StressLoadSlicing)
8356 return NumberOfSlices > 1;
8357
8358 // Check (1).
8359 if (NumberOfSlices != 2)
8360 return false;
8361
8362 // Check (2).
8363 if (!areUsedBitsDense(UsedBits))
8364 return false;
8365
8366 // Check (3).
8367 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8368 // The original code has one big load.
8369 OrigCost.Loads = 1;
8370 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8371 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8372 // Accumulate the cost of all the slices.
8373 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8374 GlobalSlicingCost += SliceCost;
8375
8376 // Account as cost in the original configuration the gain obtained
8377 // with the current slices.
8378 OrigCost.addSliceGain(LS);
8379 }
8380
8381 // If the target supports paired load, adjust the cost accordingly.
8382 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8383 return OrigCost > GlobalSlicingCost;
8384}
8385
8386/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8387/// operations, split it in the various pieces being extracted.
8388///
8389/// This sort of thing is introduced by SROA.
8390/// This slicing takes care not to insert overlapping loads.
8391/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8392bool DAGCombiner::SliceUpLoad(SDNode *N) {
8393 if (Level < AfterLegalizeDAG)
8394 return false;
8395
8396 LoadSDNode *LD = cast<LoadSDNode>(N);
8397 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8398 !LD->getValueType(0).isInteger())
8399 return false;
8400
8401 // Keep track of already used bits to detect overlapping values.
8402 // In that case, we will just abort the transformation.
8403 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8404
8405 SmallVector<LoadedSlice, 4> LoadedSlices;
8406
8407 // Check if this load is used as several smaller chunks of bits.
8408 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8409 // of computation for each trunc.
8410 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8411 UI != UIEnd; ++UI) {
8412 // Skip the uses of the chain.
8413 if (UI.getUse().getResNo() != 0)
8414 continue;
8415
8416 SDNode *User = *UI;
8417 unsigned Shift = 0;
8418
8419 // Check if this is a trunc(lshr).
8420 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8421 isa<ConstantSDNode>(User->getOperand(1))) {
8422 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8423 User = *User->use_begin();
8424 }
8425
8426 // At this point, User is a Truncate, iff we encountered, trunc or
8427 // trunc(lshr).
8428 if (User->getOpcode() != ISD::TRUNCATE)
8429 return false;
8430
8431 // The width of the type must be a power of 2 and greater than 8-bits.
8432 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008433 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008434 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008435 unsigned Width = User->getValueSizeInBits(0);
8436 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8437 return 0;
8438
8439 // Build the slice for this chain of computations.
8440 LoadedSlice LS(User, LD, Shift, &DAG);
8441 APInt CurrentUsedBits = LS.getUsedBits();
8442
8443 // Check if this slice overlaps with another.
8444 if ((CurrentUsedBits & UsedBits) != 0)
8445 return false;
8446 // Update the bits used globally.
8447 UsedBits |= CurrentUsedBits;
8448
8449 // Check if the new slice would be legal.
8450 if (!LS.isLegal())
8451 return false;
8452
8453 // Record the slice.
8454 LoadedSlices.push_back(LS);
8455 }
8456
8457 // Abort slicing if it does not seem to be profitable.
8458 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8459 return false;
8460
8461 ++SlicedLoads;
8462
8463 // Rewrite each chain to use an independent load.
8464 // By construction, each chain can be represented by a unique load.
8465
8466 // Prepare the argument for the new token factor for all the slices.
8467 SmallVector<SDValue, 8> ArgChains;
8468 for (SmallVectorImpl<LoadedSlice>::const_iterator
8469 LSIt = LoadedSlices.begin(),
8470 LSItEnd = LoadedSlices.end();
8471 LSIt != LSItEnd; ++LSIt) {
8472 SDValue SliceInst = LSIt->loadSlice();
8473 CombineTo(LSIt->Inst, SliceInst, true);
8474 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8475 SliceInst = SliceInst.getOperand(0);
8476 assert(SliceInst->getOpcode() == ISD::LOAD &&
8477 "It takes more than a zext to get to the loaded slice!!");
8478 ArgChains.push_back(SliceInst.getValue(1));
8479 }
8480
8481 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8482 &ArgChains[0], ArgChains.size());
8483 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8484 return true;
8485}
8486
Chris Lattner4041ab62010-04-15 04:48:01 +00008487/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8488/// load is having specific bytes cleared out. If so, return the byte size
8489/// being masked out and the shift amount.
8490static std::pair<unsigned, unsigned>
8491CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8492 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008493
Chris Lattner4041ab62010-04-15 04:48:01 +00008494 // Check for the structure we're looking for.
8495 if (V->getOpcode() != ISD::AND ||
8496 !isa<ConstantSDNode>(V->getOperand(1)) ||
8497 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8498 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008499
Chris Lattner3245afd2010-04-15 06:10:49 +00008500 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008501 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008502 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008503
Chris Lattner3245afd2010-04-15 06:10:49 +00008504 // The store should be chained directly to the load or be an operand of a
8505 // tokenfactor.
8506 if (LD == Chain.getNode())
8507 ; // ok.
8508 else if (Chain->getOpcode() != ISD::TokenFactor)
8509 return Result; // Fail.
8510 else {
8511 bool isOk = false;
8512 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8513 if (Chain->getOperand(i).getNode() == LD) {
8514 isOk = true;
8515 break;
8516 }
8517 if (!isOk) return Result;
8518 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008519
Chris Lattner4041ab62010-04-15 04:48:01 +00008520 // This only handles simple types.
8521 if (V.getValueType() != MVT::i16 &&
8522 V.getValueType() != MVT::i32 &&
8523 V.getValueType() != MVT::i64)
8524 return Result;
8525
8526 // Check the constant mask. Invert it so that the bits being masked out are
8527 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8528 // follow the sign bit for uniformity.
8529 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008530 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008531 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008532 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008533 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8534 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008535
Chris Lattner4041ab62010-04-15 04:48:01 +00008536 // See if we have a continuous run of bits. If so, we have 0*1+0*
8537 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8538 return Result;
8539
8540 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8541 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8542 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008543
Chris Lattner4041ab62010-04-15 04:48:01 +00008544 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8545 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008546 case 1:
8547 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008548 case 4: break;
8549 default: return Result; // All one mask, or 5-byte mask.
8550 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008551
Chris Lattner4041ab62010-04-15 04:48:01 +00008552 // Verify that the first bit starts at a multiple of mask so that the access
8553 // is aligned the same as the access width.
8554 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008555
Chris Lattner4041ab62010-04-15 04:48:01 +00008556 Result.first = MaskedBytes;
8557 Result.second = NotMaskTZ/8;
8558 return Result;
8559}
8560
8561
8562/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8563/// provides a value as specified by MaskInfo. If so, replace the specified
8564/// store with a narrower store of truncated IVal.
8565static SDNode *
8566ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8567 SDValue IVal, StoreSDNode *St,
8568 DAGCombiner *DC) {
8569 unsigned NumBytes = MaskInfo.first;
8570 unsigned ByteShift = MaskInfo.second;
8571 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008572
Chris Lattner4041ab62010-04-15 04:48:01 +00008573 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8574 // that uses this. If not, this is not a replacement.
8575 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8576 ByteShift*8, (ByteShift+NumBytes)*8);
8577 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008578
Chris Lattner4041ab62010-04-15 04:48:01 +00008579 // Check that it is legal on the target to do this. It is legal if the new
8580 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8581 // legalization.
8582 MVT VT = MVT::getIntegerVT(NumBytes*8);
8583 if (!DC->isTypeLegal(VT))
8584 return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008585
Chris Lattner4041ab62010-04-15 04:48:01 +00008586 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8587 // shifted by ByteShift and truncated down to NumBytes.
8588 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008589 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008590 DAG.getConstant(ByteShift*8,
8591 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008592
8593 // Figure out the offset for the store and the alignment of the access.
8594 unsigned StOffset;
8595 unsigned NewAlign = St->getAlignment();
8596
8597 if (DAG.getTargetLoweringInfo().isLittleEndian())
8598 StOffset = ByteShift;
8599 else
8600 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008601
Chris Lattner4041ab62010-04-15 04:48:01 +00008602 SDValue Ptr = St->getBasePtr();
8603 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008604 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008605 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8606 NewAlign = MinAlign(NewAlign, StOffset);
8607 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008608
Chris Lattner4041ab62010-04-15 04:48:01 +00008609 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008610 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008611
Chris Lattner4041ab62010-04-15 04:48:01 +00008612 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008613 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008614 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008615 false, false, NewAlign).getNode();
8616}
8617
Evan Chenga9cda8a2009-05-28 00:35:15 +00008618
8619/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8620/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8621/// of the loaded bits, try narrowing the load and store if it would end up
8622/// being a win for performance or code size.
8623SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8624 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008625 if (ST->isVolatile())
8626 return SDValue();
8627
Evan Chenga9cda8a2009-05-28 00:35:15 +00008628 SDValue Chain = ST->getChain();
8629 SDValue Value = ST->getValue();
8630 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008631 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008632
8633 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008634 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008635
8636 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008637
Chris Lattner4041ab62010-04-15 04:48:01 +00008638 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8639 // is a byte mask indicating a consecutive number of bytes, check to see if
8640 // Y is known to provide just those bytes. If so, we try to replace the
8641 // load + replace + store sequence with a single (narrower) store, which makes
8642 // the load dead.
8643 if (Opc == ISD::OR) {
8644 std::pair<unsigned, unsigned> MaskedLoad;
8645 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8646 if (MaskedLoad.first)
8647 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8648 Value.getOperand(1), ST,this))
8649 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008650
Chris Lattner4041ab62010-04-15 04:48:01 +00008651 // Or is commutative, so try swapping X and Y.
8652 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8653 if (MaskedLoad.first)
8654 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8655 Value.getOperand(0), ST,this))
8656 return SDValue(NewST, 0);
8657 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008658
Evan Chenga9cda8a2009-05-28 00:35:15 +00008659 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8660 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008661 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008662
8663 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008664 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8665 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008666 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008667 if (LD->getBasePtr() != Ptr ||
8668 LD->getPointerInfo().getAddrSpace() !=
8669 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008670 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008671
8672 // Find the type to narrow it the load / op / store to.
8673 SDValue N1 = Value.getOperand(1);
8674 unsigned BitWidth = N1.getValueSizeInBits();
8675 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8676 if (Opc == ISD::AND)
8677 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008678 if (Imm == 0 || Imm.isAllOnesValue())
8679 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008680 unsigned ShAmt = Imm.countTrailingZeros();
8681 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8682 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008683 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008684 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008685 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008686 TLI.isNarrowingProfitable(VT, NewVT))) {
8687 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008688 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008689 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008690 if (NewBW >= BitWidth)
8691 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008692
8693 // If the lsb changed does not start at the type bitwidth boundary,
8694 // start at the previous one.
8695 if (ShAmt % NewBW)
8696 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008697 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8698 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008699 if ((Imm & Mask) == Imm) {
8700 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8701 if (Opc == ISD::AND)
8702 NewImm ^= APInt::getAllOnesValue(NewBW);
8703 uint64_t PtrOff = ShAmt / 8;
8704 // For big endian targets, we need to adjust the offset to the pointer to
8705 // load the correct bytes.
8706 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008707 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008708
8709 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008710 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008711 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008712 return SDValue();
8713
Andrew Trickef9de2a2013-05-25 02:42:55 +00008714 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008715 Ptr.getValueType(), Ptr,
8716 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008717 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008718 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008719 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008720 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008721 LD->isInvariant(), NewAlign,
8722 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008723 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008724 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008725 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008726 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008727 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008728 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008729
8730 AddToWorkList(NewPtr.getNode());
8731 AddToWorkList(NewLD.getNode());
8732 AddToWorkList(NewVal.getNode());
8733 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008734 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008735 ++OpsNarrowed;
8736 return NewST;
8737 }
8738 }
8739
Evan Cheng6673ff02009-05-28 18:41:02 +00008740 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008741}
8742
Evan Chengd42641c2011-02-02 01:06:55 +00008743/// TransformFPLoadStorePair - For a given floating point load / store pair,
8744/// if the load value isn't used by any other operations, then consider
8745/// transforming the pair to integer load / store operations if the target
8746/// deems the transformation profitable.
8747SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8748 StoreSDNode *ST = cast<StoreSDNode>(N);
8749 SDValue Chain = ST->getChain();
8750 SDValue Value = ST->getValue();
8751 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8752 Value.hasOneUse() &&
8753 Chain == SDValue(Value.getNode(), 1)) {
8754 LoadSDNode *LD = cast<LoadSDNode>(Value);
8755 EVT VT = LD->getMemoryVT();
8756 if (!VT.isFloatingPoint() ||
8757 VT != ST->getMemoryVT() ||
8758 LD->isNonTemporal() ||
8759 ST->isNonTemporal() ||
8760 LD->getPointerInfo().getAddrSpace() != 0 ||
8761 ST->getPointerInfo().getAddrSpace() != 0)
8762 return SDValue();
8763
8764 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8765 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8766 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8767 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8768 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8769 return SDValue();
8770
8771 unsigned LDAlign = LD->getAlignment();
8772 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008773 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008774 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008775 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8776 return SDValue();
8777
Andrew Trickef9de2a2013-05-25 02:42:55 +00008778 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008779 LD->getChain(), LD->getBasePtr(),
8780 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008781 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008782
Andrew Trickef9de2a2013-05-25 02:42:55 +00008783 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008784 NewLD, ST->getBasePtr(),
8785 ST->getPointerInfo(),
8786 false, false, STAlign);
8787
8788 AddToWorkList(NewLD.getNode());
8789 AddToWorkList(NewST.getNode());
8790 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008791 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008792 ++LdStFP2Int;
8793 return NewST;
8794 }
8795
8796 return SDValue();
8797}
8798
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008799/// Helper struct to parse and store a memory address as base + index + offset.
8800/// We ignore sign extensions when it is safe to do so.
8801/// The following two expressions are not equivalent. To differentiate we need
8802/// to store whether there was a sign extension involved in the index
8803/// computation.
8804/// (load (i64 add (i64 copyfromreg %c)
8805/// (i64 signextend (add (i8 load %index)
8806/// (i8 1))))
8807/// vs
8808///
8809/// (load (i64 add (i64 copyfromreg %c)
8810/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8811/// (i32 1)))))
8812struct BaseIndexOffset {
8813 SDValue Base;
8814 SDValue Index;
8815 int64_t Offset;
8816 bool IsIndexSignExt;
8817
8818 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8819
8820 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8821 bool IsIndexSignExt) :
8822 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8823
8824 bool equalBaseIndex(const BaseIndexOffset &Other) {
8825 return Other.Base == Base && Other.Index == Index &&
8826 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008827 }
8828
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008829 /// Parses tree in Ptr for base, index, offset addresses.
8830 static BaseIndexOffset match(SDValue Ptr) {
8831 bool IsIndexSignExt = false;
8832
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008833 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8834 // instruction, then it could be just the BASE or everything else we don't
8835 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008836 if (Ptr->getOpcode() != ISD::ADD)
8837 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8838
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008839 // We know that we have at least an ADD instruction. Try to pattern match
8840 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008841 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8842 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8843 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8844 IsIndexSignExt);
8845 }
8846
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008847 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008848 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008849 // (i64 add (i64 %array_ptr)
8850 // (i64 mul (i64 %induction_var)
8851 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008852 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008853 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008854
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008855 // Look at Base + Index + Offset cases.
8856 SDValue Base = Ptr->getOperand(0);
8857 SDValue IndexOffset = Ptr->getOperand(1);
8858
8859 // Skip signextends.
8860 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8861 IndexOffset = IndexOffset->getOperand(0);
8862 IsIndexSignExt = true;
8863 }
8864
8865 // Either the case of Base + Index (no offset) or something else.
8866 if (IndexOffset->getOpcode() != ISD::ADD)
8867 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8868
8869 // Now we have the case of Base + Index + offset.
8870 SDValue Index = IndexOffset->getOperand(0);
8871 SDValue Offset = IndexOffset->getOperand(1);
8872
8873 if (!isa<ConstantSDNode>(Offset))
8874 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8875
8876 // Ignore signextends.
8877 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8878 Index = Index->getOperand(0);
8879 IsIndexSignExt = true;
8880 } else IsIndexSignExt = false;
8881
8882 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8883 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8884 }
8885};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008886
8887/// Holds a pointer to an LSBaseSDNode as well as information on where it
8888/// is located in a sequence of memory operations connected by a chain.
8889struct MemOpLink {
8890 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8891 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8892 // Ptr to the mem node.
8893 LSBaseSDNode *MemNode;
8894 // Offset from the base ptr.
8895 int64_t OffsetFromBase;
8896 // What is the sequence number of this mem node.
8897 // Lowest mem operand in the DAG starts at zero.
8898 unsigned SequenceNum;
8899};
8900
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008901bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8902 EVT MemVT = St->getMemoryVT();
8903 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008904 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8905 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008906
8907 // Don't merge vectors into wider inputs.
8908 if (MemVT.isVector() || !MemVT.isSimple())
8909 return false;
8910
8911 // Perform an early exit check. Do not bother looking at stored values that
8912 // are not constants or loads.
8913 SDValue StoredVal = St->getValue();
8914 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8915 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8916 !IsLoadSrc)
8917 return false;
8918
8919 // Only look at ends of store sequences.
8920 SDValue Chain = SDValue(St, 1);
8921 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8922 return false;
8923
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008924 // This holds the base pointer, index, and the offset in bytes from the base
8925 // pointer.
8926 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008927
8928 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008929 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008930 return false;
8931
8932 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008933 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008934 return false;
8935
Nadav Rotem307d7672012-11-29 00:00:08 +00008936 // Save the LoadSDNodes that we find in the chain.
8937 // We need to make sure that these nodes do not interfere with
8938 // any of the store nodes.
8939 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8940
8941 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008942 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00008943
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008944 // Walk up the chain and look for nodes with offsets from the same
8945 // base pointer. Stop when reaching an instruction with a different kind
8946 // or instruction which has a different base pointer.
8947 unsigned Seq = 0;
8948 StoreSDNode *Index = St;
8949 while (Index) {
8950 // If the chain has more than one use, then we can't reorder the mem ops.
8951 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8952 break;
8953
8954 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008955 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008956
8957 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008958 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008959 break;
8960
8961 // Check that the alignment is the same.
8962 if (Index->getAlignment() != St->getAlignment())
8963 break;
8964
8965 // The memory operands must not be volatile.
8966 if (Index->isVolatile() || Index->isIndexed())
8967 break;
8968
8969 // No truncation.
8970 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8971 if (St->isTruncatingStore())
8972 break;
8973
8974 // The stored memory type must be the same.
8975 if (Index->getMemoryVT() != MemVT)
8976 break;
8977
8978 // We do not allow unaligned stores because we want to prevent overriding
8979 // stores.
8980 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8981 break;
8982
8983 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008984 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008985
Nadav Rotem307d7672012-11-29 00:00:08 +00008986 // Find the next memory operand in the chain. If the next operand in the
8987 // chain is a store then move up and continue the scan with the next
8988 // memory operand. If the next operand is a load save it and use alias
8989 // information to check if it interferes with anything.
8990 SDNode *NextInChain = Index->getChain().getNode();
8991 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00008992 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00008993 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00008994 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00008995 break;
8996 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00008997 if (Ldn->isVolatile()) {
8998 Index = NULL;
8999 break;
9000 }
9001
Nadav Rotem307d7672012-11-29 00:00:08 +00009002 // Save the load node for later. Continue the scan.
9003 AliasLoadNodes.push_back(Ldn);
9004 NextInChain = Ldn->getChain().getNode();
9005 continue;
9006 } else {
9007 Index = NULL;
9008 break;
9009 }
9010 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009011 }
9012
9013 // Check if there is anything to merge.
9014 if (StoreNodes.size() < 2)
9015 return false;
9016
9017 // Sort the memory operands according to their distance from the base pointer.
9018 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009019 [](MemOpLink LHS, MemOpLink RHS) {
9020 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9021 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9022 LHS.SequenceNum > RHS.SequenceNum);
9023 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009024
9025 // Scan the memory operations on the chain and find the first non-consecutive
9026 // store memory address.
9027 unsigned LastConsecutiveStore = 0;
9028 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009029 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9030
9031 // Check that the addresses are consecutive starting from the second
9032 // element in the list of stores.
9033 if (i > 0) {
9034 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9035 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9036 break;
9037 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009038
Nadav Rotem307d7672012-11-29 00:00:08 +00009039 bool Alias = false;
9040 // Check if this store interferes with any of the loads that we found.
9041 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9042 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9043 Alias = true;
9044 break;
9045 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009046 // We found a load that alias with this store. Stop the sequence.
9047 if (Alias)
9048 break;
9049
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009050 // Mark this node as useful.
9051 LastConsecutiveStore = i;
9052 }
9053
9054 // The node with the lowest store address.
9055 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9056
9057 // Store the constants into memory as one consecutive store.
9058 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009059 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009060 unsigned LastLegalVectorType = 0;
9061 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009062 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9063 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9064 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009065
9066 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009067 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009068 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009069 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009070 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009071 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009072 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009073 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009074
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009075 // Find a legal type for the constant store.
9076 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9077 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9078 if (TLI.isTypeLegal(StoreTy))
9079 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009080 // Or check whether a truncstore is legal.
9081 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9082 TargetLowering::TypePromoteInteger) {
9083 EVT LegalizedStoredValueTy =
9084 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9085 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9086 LastLegalType = i+1;
9087 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009088
9089 // Find a legal type for the vector store.
9090 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9091 if (TLI.isTypeLegal(Ty))
9092 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009093 }
9094
Bob Wilson3365b802012-12-20 01:36:20 +00009095 // We only use vectors if the constant is known to be zero and the
9096 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009097 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009098 LastLegalVectorType = 0;
9099
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009100 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009101 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009102 return false;
9103
Nadav Rotem495b1a42013-02-14 18:28:52 +00009104 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009105 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9106
9107 // Make sure we have something to merge.
9108 if (NumElem < 2)
9109 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009110
9111 unsigned EarliestNodeUsed = 0;
9112 for (unsigned i=0; i < NumElem; ++i) {
9113 // Find a chain for the new wide-store operand. Notice that some
9114 // of the store nodes that we found may not be selected for inclusion
9115 // in the wide store. The chain we use needs to be the chain of the
9116 // earliest store node which is *used* and replaced by the wide store.
9117 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9118 EarliestNodeUsed = i;
9119 }
9120
9121 // The earliest Node in the DAG.
9122 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009123 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009124
Nadav Rotemb27777f2012-10-04 22:35:15 +00009125 SDValue StoredVal;
9126 if (UseVector) {
9127 // Find a legal type for the vector store.
9128 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9129 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9130 StoredVal = DAG.getConstant(0, Ty);
9131 } else {
9132 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9133 APInt StoreInt(StoreBW, 0);
9134
9135 // Construct a single integer constant which is made of the smaller
9136 // constant inputs.
9137 bool IsLE = TLI.isLittleEndian();
9138 for (unsigned i = 0; i < NumElem ; ++i) {
9139 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9140 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9141 SDValue Val = St->getValue();
9142 StoreInt<<=ElementSizeBytes*8;
9143 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9144 StoreInt|=C->getAPIntValue().zext(StoreBW);
9145 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9146 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9147 } else {
9148 assert(false && "Invalid constant element type");
9149 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009150 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009151
9152 // Create the new Load and Store operations.
9153 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9154 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009155 }
9156
Nadav Rotemb27777f2012-10-04 22:35:15 +00009157 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009158 FirstInChain->getBasePtr(),
9159 FirstInChain->getPointerInfo(),
9160 false, false,
9161 FirstInChain->getAlignment());
9162
9163 // Replace the first store with the new store
9164 CombineTo(EarliestOp, NewStore);
9165 // Erase all other stores.
9166 for (unsigned i = 0; i < NumElem ; ++i) {
9167 if (StoreNodes[i].MemNode == EarliestOp)
9168 continue;
9169 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009170 // ReplaceAllUsesWith will replace all uses that existed when it was
9171 // called, but graph optimizations may cause new ones to appear. For
9172 // example, the case in pr14333 looks like
9173 //
9174 // St's chain -> St -> another store -> X
9175 //
9176 // And the only difference from St to the other store is the chain.
9177 // When we change it's chain to be St's chain they become identical,
9178 // get CSEed and the net result is that X is now a use of St.
9179 // Since we know that St is redundant, just iterate.
9180 while (!St->use_empty())
9181 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009182 removeFromWorkList(St);
9183 DAG.DeleteNode(St);
9184 }
9185
9186 return true;
9187 }
9188
9189 // Below we handle the case of multiple consecutive stores that
9190 // come from multiple consecutive loads. We merge them into a single
9191 // wide load and a single wide store.
9192
9193 // Look for load nodes which are used by the stored values.
9194 SmallVector<MemOpLink, 8> LoadNodes;
9195
9196 // Find acceptable loads. Loads need to have the same chain (token factor),
9197 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009198 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009199 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9200 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9201 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9202 if (!Ld) break;
9203
9204 // Loads must only have one use.
9205 if (!Ld->hasNUsesOfValue(1, 0))
9206 break;
9207
9208 // Check that the alignment is the same as the stores.
9209 if (Ld->getAlignment() != St->getAlignment())
9210 break;
9211
9212 // The memory operands must not be volatile.
9213 if (Ld->isVolatile() || Ld->isIndexed())
9214 break;
9215
9216 // We do not accept ext loads.
9217 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9218 break;
9219
9220 // The stored memory type must be the same.
9221 if (Ld->getMemoryVT() != MemVT)
9222 break;
9223
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009224 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009225 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009226 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009227 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009228 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009229 break;
9230 } else {
9231 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009232 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009233 }
9234
9235 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009236 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009237 }
9238
9239 if (LoadNodes.size() < 2)
9240 return false;
9241
9242 // Scan the memory operations on the chain and find the first non-consecutive
9243 // load memory address. These variables hold the index in the store node
9244 // array.
9245 unsigned LastConsecutiveLoad = 0;
9246 // This variable refers to the size and not index in the array.
9247 unsigned LastLegalVectorType = 0;
9248 unsigned LastLegalIntegerType = 0;
9249 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009250 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9251 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9252 // All loads much share the same chain.
9253 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9254 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009255
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009256 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9257 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9258 break;
9259 LastConsecutiveLoad = i;
9260
9261 // Find a legal type for the vector store.
9262 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9263 if (TLI.isTypeLegal(StoreTy))
9264 LastLegalVectorType = i + 1;
9265
9266 // Find a legal type for the integer store.
9267 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9268 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9269 if (TLI.isTypeLegal(StoreTy))
9270 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009271 // Or check whether a truncstore and extload is legal.
9272 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9273 TargetLowering::TypePromoteInteger) {
9274 EVT LegalizedStoredValueTy =
9275 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9276 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9277 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9278 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9279 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9280 LastLegalIntegerType = i+1;
9281 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009282 }
9283
9284 // Only use vector types if the vector type is larger than the integer type.
9285 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009286 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009287 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9288
9289 // We add +1 here because the LastXXX variables refer to location while
9290 // the NumElem refers to array/index size.
9291 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9292 NumElem = std::min(LastLegalType, NumElem);
9293
9294 if (NumElem < 2)
9295 return false;
9296
9297 // The earliest Node in the DAG.
9298 unsigned EarliestNodeUsed = 0;
9299 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9300 for (unsigned i=1; i<NumElem; ++i) {
9301 // Find a chain for the new wide-store operand. Notice that some
9302 // of the store nodes that we found may not be selected for inclusion
9303 // in the wide store. The chain we use needs to be the chain of the
9304 // earliest store node which is *used* and replaced by the wide store.
9305 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9306 EarliestNodeUsed = i;
9307 }
9308
9309 // Find if it is better to use vectors or integers to load and store
9310 // to memory.
9311 EVT JointMemOpVT;
9312 if (UseVectorTy) {
9313 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9314 } else {
9315 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9316 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9317 }
9318
Andrew Trickef9de2a2013-05-25 02:42:55 +00009319 SDLoc LoadDL(LoadNodes[0].MemNode);
9320 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009321
9322 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9323 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9324 FirstLoad->getChain(),
9325 FirstLoad->getBasePtr(),
9326 FirstLoad->getPointerInfo(),
9327 false, false, false,
9328 FirstLoad->getAlignment());
9329
9330 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9331 FirstInChain->getBasePtr(),
9332 FirstInChain->getPointerInfo(), false, false,
9333 FirstInChain->getAlignment());
9334
Nadav Rotemac920662012-10-03 19:30:31 +00009335 // Replace one of the loads with the new load.
9336 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9337 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9338 SDValue(NewLoad.getNode(), 1));
9339
9340 // Remove the rest of the load chains.
9341 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009342 // Replace all chain users of the old load nodes with the chain of the new
9343 // load node.
9344 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009345 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9346 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009347
Nadav Rotemac920662012-10-03 19:30:31 +00009348 // Replace the first store with the new store.
9349 CombineTo(EarliestOp, NewStore);
9350 // Erase all other stores.
9351 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009352 // Remove all Store nodes.
9353 if (StoreNodes[i].MemNode == EarliestOp)
9354 continue;
9355 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9356 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9357 removeFromWorkList(St);
9358 DAG.DeleteNode(St);
9359 }
9360
9361 return true;
9362}
9363
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009364SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009365 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009366 SDValue Chain = ST->getChain();
9367 SDValue Value = ST->getValue();
9368 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009369
Evan Chenga4cf58a2007-05-07 21:27:48 +00009370 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009371 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009372 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009373 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009374 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009375 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009376 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009377 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009378 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009379 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009380 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009381 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009382 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009383 ST->isNonTemporal(), OrigAlign,
9384 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009385 }
Owen Andersona5192842011-04-14 17:30:49 +00009386
Chris Lattner41c80e82011-04-09 02:32:02 +00009387 // Turn 'store undef, Ptr' -> nothing.
9388 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9389 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009390
Nate Begeman8e20c762006-12-11 02:23:46 +00009391 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009392 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009393 // NOTE: If the original store is volatile, this transform must not increase
9394 // the number of stores. For example, on x86-32 an f64 can be stored in one
9395 // processor operation but an i64 (which is not legal) requires two. So the
9396 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009397 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009398 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009399 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009400 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009401 case MVT::f16: // We don't do this for these yet.
9402 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009403 case MVT::f128:
9404 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009405 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009406 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009407 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009408 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009409 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009410 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009411 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009412 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009413 }
9414 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009415 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009416 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009417 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009418 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009419 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009420 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009421 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009422 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009423 }
Owen Andersona5192842011-04-14 17:30:49 +00009424
Chris Lattner41c80e82011-04-09 02:32:02 +00009425 if (!ST->isVolatile() &&
9426 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009427 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009428 // argument passing. Since this is so common, custom legalize the
9429 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009430 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009431 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9432 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009433 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009434
Dan Gohman2af30632007-07-09 22:18:38 +00009435 unsigned Alignment = ST->getAlignment();
9436 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009437 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009438 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009439
Andrew Trickef9de2a2013-05-25 02:42:55 +00009440 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009441 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009442 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009443 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009444 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009445 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009446 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009447 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009448 Ptr, ST->getPointerInfo().getWithOffset(4),
9449 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009450 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009451 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009452 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009453 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009454
Chris Lattnerb7524b62006-12-12 04:16:14 +00009455 break;
Evan Cheng21836982006-12-11 17:25:19 +00009456 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009457 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009458 }
9459
Evan Cheng43cd9e32010-04-01 06:04:33 +00009460 // Try to infer better alignment information than the store already has.
9461 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009462 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9463 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009464 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009465 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009466 ST->isVolatile(), ST->isNonTemporal(), Align,
9467 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009468 }
9469 }
9470
Evan Chengd42641c2011-02-02 01:06:55 +00009471 // Try transforming a pair floating point load / store ops to integer
9472 // load / store ops.
9473 SDValue NewST = TransformFPLoadStorePair(N);
9474 if (NewST.getNode())
9475 return NewST;
9476
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009477 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9478 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009479#ifndef NDEBUG
9480 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9481 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9482 UseAA = false;
9483#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009484 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009485 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009486 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009487
Jim Laskey708d0db2006-10-04 16:53:27 +00009488 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009489 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009490 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009491
9492 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009493 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009494 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009495 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009496 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009497 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009498 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009499 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009500
Jim Laskeyd07be232006-09-25 16:29:54 +00009501 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009502 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009503 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009504
Nate Begeman879d8f12009-09-15 00:18:30 +00009505 // Make sure the new and old chains are cleaned up.
9506 AddToWorkList(Token.getNode());
9507
Jim Laskeydcf983c2006-10-13 23:32:28 +00009508 // Don't add users to work list.
9509 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009510 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009511 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009512
Evan Cheng33157702006-11-05 09:31:14 +00009513 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009514 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009515 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009516
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009517 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009518 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009519 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009520 // See if we can simplify the input to this truncstore with knowledge that
9521 // only the low bits are being used. For example:
9522 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009523 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009524 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009525 APInt::getLowBitsSet(
9526 Value.getValueType().getScalarType().getSizeInBits(),
9527 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009528 AddToWorkList(Value.getNode());
9529 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009530 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009531 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009532
Chris Lattnerf47e3062007-10-13 06:58:48 +00009533 // Otherwise, see if we can simplify the operation with
9534 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009535 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009536 APInt::getLowBitsSet(
9537 Value.getValueType().getScalarType().getSizeInBits(),
9538 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009539 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009540 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009541
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009542 // If this is a load followed by a store to the same location, then the store
9543 // is dead/noop.
9544 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009545 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009546 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009547 // There can't be any side effects between the load and store, such as
9548 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009549 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009550 // The store is dead, remove it.
9551 return Chain;
9552 }
9553 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009554
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009555 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9556 // truncating store. We can do this even if this is already a truncstore.
9557 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009558 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009559 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009560 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009561 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009562 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009563 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009564
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009565 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009566 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009567 if (!LegalTypes) {
9568 bool EverChanged = false;
9569
9570 do {
9571 // There can be multiple store sequences on the same chain.
9572 // Keep trying to merge store sequences until we are unable to do so
9573 // or until we merge the last store on the chain.
9574 bool Changed = MergeConsecutiveStores(ST);
9575 EverChanged |= Changed;
9576 if (!Changed) break;
9577 } while (ST->getOpcode() != ISD::DELETED_NODE);
9578
9579 if (EverChanged)
9580 return SDValue(N, 0);
9581 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009582
Evan Chenga9cda8a2009-05-28 00:35:15 +00009583 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009584}
9585
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009586SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9587 SDValue InVec = N->getOperand(0);
9588 SDValue InVal = N->getOperand(1);
9589 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009590 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009591
Bob Wilson42603952010-05-19 23:42:58 +00009592 // If the inserted element is an UNDEF, just use the input vector.
9593 if (InVal.getOpcode() == ISD::UNDEF)
9594 return InVec;
9595
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009596 EVT VT = InVec.getValueType();
9597
Owen Andersonb2c80da2011-02-25 21:41:48 +00009598 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009599 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9600 return SDValue();
9601
Eli Friedmanb7910b72011-09-09 21:04:06 +00009602 // Check that we know which element is being inserted
9603 if (!isa<ConstantSDNode>(EltNo))
9604 return SDValue();
9605 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009606
Eli Friedmanb7910b72011-09-09 21:04:06 +00009607 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9608 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9609 // vector elements.
9610 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009611 // Do not combine these two vectors if the output vector will not replace
9612 // the input vector.
9613 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009614 Ops.append(InVec.getNode()->op_begin(),
9615 InVec.getNode()->op_end());
9616 } else if (InVec.getOpcode() == ISD::UNDEF) {
9617 unsigned NElts = VT.getVectorNumElements();
9618 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9619 } else {
9620 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009621 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009622
9623 // Insert the element
9624 if (Elt < Ops.size()) {
9625 // All the operands of BUILD_VECTOR must have the same type;
9626 // we enforce that here.
9627 EVT OpVT = Ops[0].getValueType();
9628 if (InVal.getValueType() != OpVT)
9629 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9630 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9631 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9632 Ops[Elt] = InVal;
9633 }
9634
9635 // Return the new vector
9636 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9637 VT, &Ops[0], Ops.size());
Chris Lattner5336a592006-03-19 01:27:56 +00009638}
9639
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009640SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009641 // (vextract (scalar_to_vector val, 0) -> val
9642 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009643 EVT VT = InVec.getValueType();
9644 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009645
Duncan Sands6be291a2011-05-09 08:03:33 +00009646 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9647 // Check if the result type doesn't match the inserted element type. A
9648 // SCALAR_TO_VECTOR may truncate the inserted element and the
9649 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9650 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009651 if (InOp.getValueType() != NVT) {
9652 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009653 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009654 }
9655 return InOp;
9656 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009657
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009658 SDValue EltNo = N->getOperand(1);
9659 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9660
9661 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9662 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009663 // we may introduce new vector instructions which are not backed by TD
9664 // patterns. For example on AVX, extracting elements from a wide vector
9665 // without using extract_subvector.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009666 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9667 && ConstEltNo && !LegalOperations) {
9668 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9669 int NumElem = VT.getVectorNumElements();
9670 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9671 // Find the new index to extract from.
9672 int OrigElt = SVOp->getMaskElt(Elt);
9673
9674 // Extracting an undef index is undef.
9675 if (OrigElt == -1)
9676 return DAG.getUNDEF(NVT);
9677
9678 // Select the right vector half to extract from.
9679 if (OrigElt < NumElem) {
9680 InVec = InVec->getOperand(0);
9681 } else {
9682 InVec = InVec->getOperand(1);
9683 OrigElt -= NumElem;
9684 }
9685
Tom Stellardd42c5942013-08-05 22:22:01 +00009686 EVT IndexTy = TLI.getVectorIdxTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009687 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00009688 InVec, DAG.getConstant(OrigElt, IndexTy));
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009689 }
9690
Evan Cheng1120279a2008-05-13 08:35:03 +00009691 // Perform only after legalization to ensure build_vector / vector_shuffle
9692 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009693 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009694
Mon P Wangca6d6de2009-01-17 00:07:25 +00009695 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9696 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9697 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009698
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009699 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009700 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009701 bool NewLoad = false;
Mon P Wangb5eb7202008-12-11 00:26:16 +00009702 bool BCNumEltsChanged = false;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009703 EVT ExtVT = VT.getVectorElementType();
9704 EVT LVT = ExtVT;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009705
Evan Cheng7bf83092012-03-13 22:00:52 +00009706 // If the result of load has to be truncated, then it's not necessarily
9707 // profitable.
Evan Chengd5f8e572012-03-13 22:16:11 +00009708 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng7bf83092012-03-13 22:00:52 +00009709 return SDValue();
9710
Wesley Peck527da1b2010-11-23 03:31:01 +00009711 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009712 // Don't duplicate a load with other uses.
9713 if (!InVec.hasOneUse())
9714 return SDValue();
9715
Owen Anderson53aa7a92009-08-10 22:56:29 +00009716 EVT BCVT = InVec.getOperand(0).getValueType();
9717 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009718 return SDValue();
Mon P Wangb5eb7202008-12-11 00:26:16 +00009719 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9720 BCNumEltsChanged = true;
Evan Cheng1120279a2008-05-13 08:35:03 +00009721 InVec = InVec.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009722 ExtVT = BCVT.getVectorElementType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009723 NewLoad = true;
9724 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009725
Evan Cheng1120279a2008-05-13 08:35:03 +00009726 LoadSDNode *LN0 = NULL;
Nate Begeman5f829d82009-04-29 05:20:52 +00009727 const ShuffleVectorSDNode *SVN = NULL;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009728 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009729 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009730 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009731 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009732 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009733 // Don't duplicate a load with other uses.
9734 if (!InVec.hasOneUse())
9735 return SDValue();
9736
Evan Cheng1120279a2008-05-13 08:35:03 +00009737 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009738 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009739 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9740 // =>
9741 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009742
Eli Friedmane96286c2011-12-26 22:49:32 +00009743 // Don't duplicate a load with other uses.
9744 if (!InVec.hasOneUse())
9745 return SDValue();
9746
Mon P Wangb5eb7202008-12-11 00:26:16 +00009747 // If the bit convert changed the number of elements, it is unsafe
9748 // to examine the mask.
9749 if (BCNumEltsChanged)
9750 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009751
9752 // Select the input vector, guarding against out of range extract vector.
9753 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009754 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009755 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9756
Eli Friedmane96286c2011-12-26 22:49:32 +00009757 if (InVec.getOpcode() == ISD::BITCAST) {
9758 // Don't duplicate a load with other uses.
9759 if (!InVec.hasOneUse())
9760 return SDValue();
9761
Evan Cheng1120279a2008-05-13 08:35:03 +00009762 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009763 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009764 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009765 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009766 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009767 }
9768 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009769
Eli Friedmane96286c2011-12-26 22:49:32 +00009770 // Make sure we found a non-volatile load and the extractelement is
9771 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009772 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009773 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009774
Eric Christopherc6418b12010-11-03 20:44:42 +00009775 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9776 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009777 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009778
Evan Cheng1120279a2008-05-13 08:35:03 +00009779 unsigned Align = LN0->getAlignment();
9780 if (NewLoad) {
9781 // Check the resultant load doesn't need a higher alignment than the
9782 // original load.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009783 unsigned NewAlign =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009784 TLI.getDataLayout()
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009785 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendling27d9dd42009-01-30 23:36:47 +00009786
Dan Gohman4aa18462009-01-28 17:46:25 +00009787 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009788 return SDValue();
Bill Wendling27d9dd42009-01-30 23:36:47 +00009789
Evan Cheng1120279a2008-05-13 08:35:03 +00009790 Align = NewAlign;
9791 }
9792
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009793 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009794 unsigned PtrOff = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00009795
Eric Christopherc6418b12010-11-03 20:44:42 +00009796 if (Elt) {
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009797 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009798 EVT PtrType = NewPtr.getValueType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009799 if (TLI.isBigEndian())
Duncan Sands13237ac2008-06-06 12:08:01 +00009800 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009801 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng1120279a2008-05-13 08:35:03 +00009802 DAG.getConstant(PtrOff, PtrType));
9803 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009804
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009805 // The replacement we need to do here is a little tricky: we need to
9806 // replace an extractelement of a load with a load.
9807 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmane96286c2011-12-26 22:49:32 +00009808 // Note that this replacement assumes that the extractvalue is the only
9809 // use of the load; that's okay because we don't want to perform this
9810 // transformation in other cases anyway.
Evan Cheng7bf83092012-03-13 22:00:52 +00009811 SDValue Load;
Evan Chengd5f8e572012-03-13 22:16:11 +00009812 SDValue Chain;
Evan Cheng7bf83092012-03-13 22:00:52 +00009813 if (NVT.bitsGT(LVT)) {
9814 // If the result type of vextract is wider than the load, then issue an
9815 // extending load instead.
9816 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9817 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009818 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng7bf83092012-03-13 22:00:52 +00009819 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009820 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9821 Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009822 Chain = Load.getValue(1);
9823 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009824 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng7bf83092012-03-13 22:00:52 +00009825 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lincfe7f352013-07-08 00:37:03 +00009826 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009827 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009828 Chain = Load.getValue(1);
9829 if (NVT.bitsLT(LVT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009830 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009831 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009832 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009833 }
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009834 WorkListRemover DeadNodes(*this);
9835 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chengd5f8e572012-03-13 22:16:11 +00009836 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009837 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009838 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9839 // worklist explicitly as well.
9840 AddToWorkList(Load.getNode());
Craig Topperaaeae982012-03-20 05:28:39 +00009841 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009842 // Make sure to revisit this node to clean it up; it will usually be dead.
9843 AddToWorkList(N);
9844 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009845 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009846
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009847 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009848}
Evan Cheng0de312d2007-10-06 08:19:55 +00009849
Michael Liao6d106b72012-10-23 23:06:52 +00009850// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9851SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9852 // We perform this optimization post type-legalization because
9853 // the type-legalizer often scalarizes integer-promoted vectors.
9854 // Performing this optimization before may create bit-casts which
9855 // will be type-legalized to complex code sequences.
9856 // We perform this optimization only before the operation legalizer because we
9857 // may introduce illegal operations.
9858 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9859 return SDValue();
9860
Dan Gohmana8665142007-06-25 16:23:39 +00009861 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009862 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009863 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009864
Nadav Rotembf6568b2011-10-29 21:23:04 +00009865 // Check to see if this is a BUILD_VECTOR of a bunch of values
9866 // which come from any_extend or zero_extend nodes. If so, we can create
9867 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009868 // optimizations. We do not handle sign-extend because we can't fill the sign
9869 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009870 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009871 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009872
Craig Topper02cb0fb2012-01-17 09:09:48 +00009873 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009874 SDValue In = N->getOperand(i);
9875 // Ignore undef inputs.
9876 if (In.getOpcode() == ISD::UNDEF) continue;
9877
9878 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9879 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9880
Nadav Rotemf3103612011-10-31 20:08:25 +00009881 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009882 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009883 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009884 break;
9885 }
9886
9887 // The input is a ZeroExt or AnyExt. Check the original type.
9888 EVT InTy = In.getOperand(0).getValueType();
9889
9890 // Check that all of the widened source types are the same.
9891 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009892 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009893 SourceType = InTy;
9894 else if (InTy != SourceType) {
9895 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009896 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009897 break;
9898 }
9899
9900 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009901 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009902 }
9903
Nadav Rotemf3103612011-10-31 20:08:25 +00009904 // In order to have valid types, all of the inputs must be extended from the
9905 // same source type and all of the inputs must be any or zero extend.
9906 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009907 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009908 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +00009909 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9910 isPowerOf2_32(SourceType.getSizeInBits());
9911
Nadav Rotem6fd1d322012-03-15 08:49:06 +00009912 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9913 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +00009914 if (!ValidTypes)
9915 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +00009916
Michael Liao6d106b72012-10-23 23:06:52 +00009917 bool isLE = TLI.isLittleEndian();
9918 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9919 assert(ElemRatio > 1 && "Invalid element size ratio");
9920 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9921 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009922
Michael Liao6d106b72012-10-23 23:06:52 +00009923 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9924 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009925
Michael Liao6d106b72012-10-23 23:06:52 +00009926 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +00009927 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +00009928 SDValue Cast = N->getOperand(i);
9929 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9930 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9931 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9932 SDValue In;
9933 if (Cast.getOpcode() == ISD::UNDEF)
9934 In = DAG.getUNDEF(SourceType);
9935 else
9936 In = Cast->getOperand(0);
9937 unsigned Index = isLE ? (i * ElemRatio) :
9938 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +00009939
Michael Liao6d106b72012-10-23 23:06:52 +00009940 assert(Index < Ops.size() && "Invalid index");
9941 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009942 }
Chris Lattner5336a592006-03-19 01:27:56 +00009943
Michael Liao6d106b72012-10-23 23:06:52 +00009944 // The type of the new BUILD_VECTOR node.
9945 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9946 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9947 "Invalid vector size");
9948 // Check if the new vector type is legal.
9949 if (!isTypeLegal(VecVT)) return SDValue();
9950
9951 // Make the new BUILD_VECTOR.
9952 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9953
9954 // The new BUILD_VECTOR node has the potential to be further optimized.
9955 AddToWorkList(BV.getNode());
9956 // Bitcast to the desired type.
9957 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9958}
9959
Michael Liao59229792012-10-24 04:14:18 +00009960SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9961 EVT VT = N->getValueType(0);
9962
9963 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009964 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +00009965
9966 EVT SrcVT = MVT::Other;
9967 unsigned Opcode = ISD::DELETED_NODE;
9968 unsigned NumDefs = 0;
9969
9970 for (unsigned i = 0; i != NumInScalars; ++i) {
9971 SDValue In = N->getOperand(i);
9972 unsigned Opc = In.getOpcode();
9973
9974 if (Opc == ISD::UNDEF)
9975 continue;
9976
9977 // If all scalar values are floats and converted from integers.
9978 if (Opcode == ISD::DELETED_NODE &&
9979 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9980 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +00009981 }
Tom Stellard567f8862013-01-02 22:13:01 +00009982
Michael Liao59229792012-10-24 04:14:18 +00009983 if (Opc != Opcode)
9984 return SDValue();
9985
9986 EVT InVT = In.getOperand(0).getValueType();
9987
9988 // If all scalar values are typed differently, bail out. It's chosen to
9989 // simplify BUILD_VECTOR of integer types.
9990 if (SrcVT == MVT::Other)
9991 SrcVT = InVT;
9992 if (SrcVT != InVT)
9993 return SDValue();
9994 NumDefs++;
9995 }
9996
9997 // If the vector has just one element defined, it's not worth to fold it into
9998 // a vectorized one.
9999 if (NumDefs < 2)
10000 return SDValue();
10001
10002 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10003 && "Should only handle conversion from integer to float.");
10004 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10005
10006 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010007
10008 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10009 return SDValue();
10010
Michael Liao59229792012-10-24 04:14:18 +000010011 SmallVector<SDValue, 8> Opnds;
10012 for (unsigned i = 0; i != NumInScalars; ++i) {
10013 SDValue In = N->getOperand(i);
10014
10015 if (In.getOpcode() == ISD::UNDEF)
10016 Opnds.push_back(DAG.getUNDEF(SrcVT));
10017 else
10018 Opnds.push_back(In.getOperand(0));
10019 }
10020 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10021 &Opnds[0], Opnds.size());
10022 AddToWorkList(BV.getNode());
10023
10024 return DAG.getNode(Opcode, dl, VT, BV);
10025}
10026
Michael Liao6d106b72012-10-23 23:06:52 +000010027SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10028 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010029 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010030 EVT VT = N->getValueType(0);
10031
10032 // A vector built entirely of undefs is undef.
10033 if (ISD::allOperandsUndef(N))
10034 return DAG.getUNDEF(VT);
10035
10036 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10037 if (V.getNode())
10038 return V;
10039
Michael Liao59229792012-10-24 04:14:18 +000010040 V = reduceBuildVecConvertToConvertBuildVec(N);
10041 if (V.getNode())
10042 return V;
10043
Dan Gohmana8665142007-06-25 16:23:39 +000010044 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10045 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10046 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010047
10048 // May only combine to shuffle after legalize if shuffle is legal.
10049 if (LegalOperations &&
10050 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10051 return SDValue();
10052
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010053 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010054 for (unsigned i = 0; i != NumInScalars; ++i) {
10055 // Ignore undef inputs.
10056 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010057
Dan Gohmana8665142007-06-25 16:23:39 +000010058 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010059 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010060 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010061 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010062 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010063 break;
10064 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010065
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010066 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010067 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010068 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10069 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010070
Gabor Greiff304a7a2008-08-28 21:40:38 +000010071 if (VecIn1.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010072 VecIn1 = ExtractedFromVec;
Gabor Greiff304a7a2008-08-28 21:40:38 +000010073 } else if (VecIn2.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010074 VecIn2 = ExtractedFromVec;
10075 } else {
10076 // Too many inputs.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010077 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010078 break;
10079 }
10080 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010081
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010082 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010083 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010084 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010085 for (unsigned i = 0; i != NumInScalars; ++i) {
10086 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010087 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010088 continue;
10089 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010090
Rafael Espindolab93db662009-04-24 12:40:33 +000010091 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010092 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010093 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010094 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010095 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10096 if (ExtIndex > VT.getVectorNumElements())
10097 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010098
Nate Begeman5f829d82009-04-29 05:20:52 +000010099 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010100 continue;
10101 }
10102
10103 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010104 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010105 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010106 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010107
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010108 // We can't generate a shuffle node with mismatched input and output types.
10109 // Attempt to transform a single input vector to the correct type.
10110 if ((VT != VecIn1.getValueType())) {
10111 // We don't support shuffeling between TWO values of different types.
10112 if (VecIn2.getNode() != 0)
10113 return SDValue();
10114
10115 // We only support widening of vectors which are half the size of the
10116 // output registers. For example XMM->YMM widening on X86 with AVX.
10117 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10118 return SDValue();
10119
James Molloy1e5c6112012-09-10 14:01:21 +000010120 // If the input vector type has a different base type to the output
10121 // vector type, bail out.
10122 if (VecIn1.getValueType().getVectorElementType() !=
10123 VT.getVectorElementType())
10124 return SDValue();
10125
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010126 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010127 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010128 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010129 }
10130
10131 // If VecIn2 is unused then change it to undef.
10132 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10133
Nadav Rotem841c9a82012-09-20 08:53:31 +000010134 // Check that we were able to transform all incoming values to the same
10135 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010136 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10137 VecIn1.getValueType() != VT)
10138 return SDValue();
10139
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010140 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010141 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010142 return SDValue();
10143
Dan Gohmana8665142007-06-25 16:23:39 +000010144 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010145 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010146 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010147 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010148 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010149 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010150
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010151 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010152}
10153
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010154SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010155 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10156 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10157 // inputs come from at most two distinct vectors, turn this into a shuffle
10158 // node.
10159
10160 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010161 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010162 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010163
Nadav Rotem01892102012-07-14 21:30:27 +000010164 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010165 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010166 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010167 return DAG.getUNDEF(VT);
10168
10169 // Optimize concat_vectors where one of the vectors is undef.
10170 if (N->getNumOperands() == 2 &&
10171 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10172 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010173 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010174
10175 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10176 if (In->getOpcode() == ISD::BITCAST &&
10177 !In->getOperand(0)->getValueType(0).isVector()) {
10178 SDValue Scalar = In->getOperand(0);
10179 EVT SclTy = Scalar->getValueType(0);
10180
10181 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10182 return SDValue();
10183
10184 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10185 VT.getSizeInBits() / SclTy.getSizeInBits());
10186 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10187 return SDValue();
10188
10189 SDLoc dl = SDLoc(N);
10190 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10191 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10192 }
10193 }
Nadav Rotem01892102012-07-14 21:30:27 +000010194
Robert Lougher7d9084f2014-02-11 15:42:46 +000010195 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10196 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10197 if (N->getNumOperands() == 2 &&
10198 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10199 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10200 EVT VT = N->getValueType(0);
10201 SDValue N0 = N->getOperand(0);
10202 SDValue N1 = N->getOperand(1);
10203 SmallVector<SDValue, 8> Opnds;
10204 unsigned BuildVecNumElts = N0.getNumOperands();
10205
10206 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10207 Opnds.push_back(N0.getOperand(i));
10208 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10209 Opnds.push_back(N1.getOperand(i));
10210
10211 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10212 Opnds.size());
10213 }
10214
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010215 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10216 // nodes often generate nop CONCAT_VECTOR nodes.
10217 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10218 // place the incoming vectors at the exact same location.
10219 SDValue SingleSource = SDValue();
10220 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10221
10222 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10223 SDValue Op = N->getOperand(i);
10224
10225 if (Op.getOpcode() == ISD::UNDEF)
10226 continue;
10227
10228 // Check if this is the identity extract:
10229 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10230 return SDValue();
10231
10232 // Find the single incoming vector for the extract_subvector.
10233 if (SingleSource.getNode()) {
10234 if (Op.getOperand(0) != SingleSource)
10235 return SDValue();
10236 } else {
10237 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010238
10239 // Check the source type is the same as the type of the result.
10240 // If not, this concat may extend the vector, so we can not
10241 // optimize it away.
10242 if (SingleSource.getValueType() != N->getValueType(0))
10243 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010244 }
10245
10246 unsigned IdentityIndex = i * PartNumElem;
10247 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10248 // The extract index must be constant.
10249 if (!CS)
10250 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010251
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010252 // Check that we are reading from the identity index.
10253 if (CS->getZExtValue() != IdentityIndex)
10254 return SDValue();
10255 }
10256
10257 if (SingleSource.getNode())
10258 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010259
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010260 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010261}
10262
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010263SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10264 EVT NVT = N->getValueType(0);
10265 SDValue V = N->getOperand(0);
10266
Michael Liao7a442c802012-10-17 20:48:33 +000010267 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10268 // Combine:
10269 // (extract_subvec (concat V1, V2, ...), i)
10270 // Into:
10271 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010272 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10273 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010274 if (V->getOperand(0).getValueType() != NVT)
10275 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010276 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10277 unsigned NumElems = NVT.getVectorNumElements();
10278 assert((Idx % NumElems) == 0 &&
10279 "IDX in concat is not a multiple of the result vector length.");
10280 return V->getOperand(Idx / NumElems);
10281 }
10282
Michael Liaobb05a1d2013-03-25 23:47:35 +000010283 // Skip bitcasting
10284 if (V->getOpcode() == ISD::BITCAST)
10285 V = V.getOperand(0);
10286
10287 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010288 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010289 // Handle only simple case where vector being inserted and vector
10290 // being extracted are of same type, and are half size of larger vectors.
10291 EVT BigVT = V->getOperand(0).getValueType();
10292 EVT SmallVT = V->getOperand(1).getValueType();
10293 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10294 return SDValue();
10295
10296 // Only handle cases where both indexes are constants with the same type.
10297 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10298 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10299
10300 if (InsIdx && ExtIdx &&
10301 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10302 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10303 // Combine:
10304 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10305 // Into:
10306 // indices are equal or bit offsets are equal => V1
10307 // otherwise => (extract_subvec V1, ExtIdx)
10308 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10309 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10310 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10311 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10312 DAG.getNode(ISD::BITCAST, dl,
10313 N->getOperand(0).getValueType(),
10314 V->getOperand(0)), N->getOperand(1));
10315 }
10316 }
10317
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010318 return SDValue();
10319}
10320
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010321// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10322static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10323 EVT VT = N->getValueType(0);
10324 unsigned NumElts = VT.getVectorNumElements();
10325
10326 SDValue N0 = N->getOperand(0);
10327 SDValue N1 = N->getOperand(1);
10328 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10329
10330 SmallVector<SDValue, 4> Ops;
10331 EVT ConcatVT = N0.getOperand(0).getValueType();
10332 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10333 unsigned NumConcats = NumElts / NumElemsPerConcat;
10334
10335 // Look at every vector that's inserted. We're looking for exact
10336 // subvector-sized copies from a concatenated vector
10337 for (unsigned I = 0; I != NumConcats; ++I) {
10338 // Make sure we're dealing with a copy.
10339 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010340 bool AllUndef = true, NoUndef = true;
10341 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10342 if (SVN->getMaskElt(J) >= 0)
10343 AllUndef = false;
10344 else
10345 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010346 }
10347
Hao Liubc601962013-05-13 02:07:05 +000010348 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010349 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10350 return SDValue();
10351
10352 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10353 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10354 return SDValue();
10355
10356 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10357 if (FirstElt < N0.getNumOperands())
10358 Ops.push_back(N0.getOperand(FirstElt));
10359 else
10360 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10361
10362 } else if (AllUndef) {
10363 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10364 } else { // Mixed with general masks and undefs, can't do optimization.
10365 return SDValue();
10366 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010367 }
10368
Andrew Trickef9de2a2013-05-25 02:42:55 +000010369 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010370 Ops.size());
10371}
10372
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010373SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010374 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010375 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010376
Mon P Wang25f01062008-11-10 04:46:22 +000010377 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010378 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010379
Craig Topper5894fe42012-04-09 05:16:56 +000010380 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010381
Craig Topper279c77b2012-01-04 08:07:43 +000010382 // Canonicalize shuffle undef, undef -> undef
10383 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10384 return DAG.getUNDEF(VT);
10385
10386 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10387
10388 // Canonicalize shuffle v, v -> v, undef
10389 if (N0 == N1) {
10390 SmallVector<int, 8> NewMask;
10391 for (unsigned i = 0; i != NumElts; ++i) {
10392 int Idx = SVN->getMaskElt(i);
10393 if (Idx >= (int)NumElts) Idx -= NumElts;
10394 NewMask.push_back(Idx);
10395 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010396 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010397 &NewMask[0]);
10398 }
10399
10400 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10401 if (N0.getOpcode() == ISD::UNDEF) {
10402 SmallVector<int, 8> NewMask;
10403 for (unsigned i = 0; i != NumElts; ++i) {
10404 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010405 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010406 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010407 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010408 else
10409 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010410 }
10411 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010412 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010413 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010414 &NewMask[0]);
10415 }
10416
10417 // Remove references to rhs if it is undef
10418 if (N1.getOpcode() == ISD::UNDEF) {
10419 bool Changed = false;
10420 SmallVector<int, 8> NewMask;
10421 for (unsigned i = 0; i != NumElts; ++i) {
10422 int Idx = SVN->getMaskElt(i);
10423 if (Idx >= (int)NumElts) {
10424 Idx = -1;
10425 Changed = true;
10426 }
10427 NewMask.push_back(Idx);
10428 }
10429 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010430 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010431 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010432
Bob Wilsonf63da122010-10-28 17:06:14 +000010433 // If it is a splat, check if the argument vector is another splat or a
10434 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010435 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010436 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010437
Dan Gohmana8665142007-06-25 16:23:39 +000010438 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010439 // not the number of vector elements, look through it. Be careful not to
10440 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010441 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010442 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010443 if (ConvInput.getValueType().isVector() &&
10444 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010445 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010446 }
10447
Dan Gohmana8665142007-06-25 16:23:39 +000010448 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010449 assert(V->getNumOperands() == NumElts &&
10450 "BUILD_VECTOR has wrong number of operands");
10451 SDValue Base;
10452 bool AllSame = true;
10453 for (unsigned i = 0; i != NumElts; ++i) {
10454 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10455 Base = V->getOperand(i);
10456 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010457 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010458 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010459 // Splat of <u, u, u, u>, return <u, u, u, u>
10460 if (!Base.getNode())
10461 return N0;
10462 for (unsigned i = 0; i != NumElts; ++i) {
10463 if (V->getOperand(i) != Base) {
10464 AllSame = false;
10465 break;
10466 }
10467 }
10468 // Splat of <x, x, x, x>, return <x, x, x, x>
10469 if (AllSame)
10470 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010471 }
10472 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010473
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010474 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10475 Level < AfterLegalizeVectorOps &&
10476 (N1.getOpcode() == ISD::UNDEF ||
10477 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10478 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10479 SDValue V = partitionShuffleOfConcats(N, DAG);
10480
10481 if (V.getNode())
10482 return V;
10483 }
10484
Nadav Rotemb0783502012-04-01 19:31:22 +000010485 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010486 // and it reverses the swizzle of the previous shuffle then we can
10487 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010488 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10489 N1.getOpcode() == ISD::UNDEF) {
10490
Nadav Rotemb0783502012-04-01 19:31:22 +000010491 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10492
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010493 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10494 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10495 return SDValue();
10496
Craig Topper5894fe42012-04-09 05:16:56 +000010497 // The incoming shuffle must be of the same type as the result of the
10498 // current shuffle.
10499 assert(OtherSV->getOperand(0).getValueType() == VT &&
10500 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010501
10502 for (unsigned i = 0; i != NumElts; ++i) {
10503 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010504 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010505 // Next, this index comes from the first value, which is the incoming
10506 // shuffle. Adopt the incoming index.
10507 if (Idx >= 0)
10508 Idx = OtherSV->getMaskElt(Idx);
10509
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010510 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010511 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010512 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010513 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010514
10515 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010516 }
10517
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010518 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010519}
10520
Manman Ren413a6cb2014-01-31 01:10:35 +000010521SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10522 SDValue N0 = N->getOperand(0);
10523 SDValue N2 = N->getOperand(2);
10524
10525 // If the input vector is a concatenation, and the insert replaces
10526 // one of the halves, we can optimize into a single concat_vectors.
10527 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10528 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10529 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10530 EVT VT = N->getValueType(0);
10531
10532 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10533 // (concat_vectors Z, Y)
10534 if (InsIdx == 0)
10535 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10536 N->getOperand(1), N0.getOperand(1));
10537
10538 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10539 // (concat_vectors X, Z)
10540 if (InsIdx == VT.getVectorNumElements()/2)
10541 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10542 N0.getOperand(0), N->getOperand(1));
10543 }
10544
10545 return SDValue();
10546}
10547
Evan Chenga320abc2006-04-20 08:56:16 +000010548/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010549/// an AND to a vector_shuffle with the destination vector and a zero vector.
10550/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010551/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010552SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010553 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010554 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010555 SDValue LHS = N->getOperand(0);
10556 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010557 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010558 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010559 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010560 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010561 SmallVector<int, 8> Indices;
10562 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010563 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010564 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010565 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010566 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010567
10568 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010569 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010570 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010571 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010572 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010573 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010574 }
10575
10576 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010577 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010578 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010579 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010580
Dan Gohmana8665142007-06-25 16:23:39 +000010581 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010582 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010583 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010584 DAG.getConstant(0, EltVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010585 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010586 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peck527da1b2010-11-23 03:31:01 +000010587 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010588 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010589 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010590 }
10591 }
Bill Wendling31b50992009-01-30 23:59:18 +000010592
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010593 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010594}
10595
Dan Gohmana8665142007-06-25 16:23:39 +000010596/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010597SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010598 assert(N->getValueType(0).isVector() &&
10599 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010600
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010601 SDValue LHS = N->getOperand(0);
10602 SDValue RHS = N->getOperand(1);
10603 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010604 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010605
Dan Gohmana8665142007-06-25 16:23:39 +000010606 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010607 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010608 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010609 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010610 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010611 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10612 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010613 return SDValue();
10614
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010615 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010616 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010617 SDValue LHSOp = LHS.getOperand(i);
10618 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010619
Evan Cheng64d28462006-05-31 06:08:35 +000010620 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010621 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10622 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010623 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010624 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010625 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010626 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010627 break;
10628 }
Bill Wendling31b50992009-01-30 23:59:18 +000010629
Bob Wilson54081442010-12-17 23:06:49 +000010630 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010631 EVT RVT = RHSOp.getValueType();
10632 if (RVT != VT) {
10633 // Integer BUILD_VECTOR operands may have types larger than the element
10634 // size (e.g., when the element type is not legal). Prior to type
10635 // legalization, the types may not match between the two BUILD_VECTORS.
10636 // Truncate one of the operands to make them match.
10637 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010638 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010639 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010640 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010641 VT = RVT;
10642 }
10643 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010644 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010645 LHSOp, RHSOp);
10646 if (FoldOp.getOpcode() != ISD::UNDEF &&
10647 FoldOp.getOpcode() != ISD::Constant &&
10648 FoldOp.getOpcode() != ISD::ConstantFP)
10649 break;
10650 Ops.push_back(FoldOp);
10651 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010652 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010653
Bob Wilson54081442010-12-17 23:06:49 +000010654 if (Ops.size() == LHS.getNumOperands())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010655 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilson54081442010-12-17 23:06:49 +000010656 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattner0442a182006-04-02 03:25:57 +000010657 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010658
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010659 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010660}
10661
Craig Topper82384612012-09-11 01:45:21 +000010662/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10663SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010664 assert(N->getValueType(0).isVector() &&
10665 "SimplifyVUnaryOp only works on vectors!");
10666
10667 SDValue N0 = N->getOperand(0);
10668
10669 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10670 return SDValue();
10671
10672 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10673 SmallVector<SDValue, 8> Ops;
10674 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10675 SDValue Op = N0.getOperand(i);
10676 if (Op.getOpcode() != ISD::UNDEF &&
10677 Op.getOpcode() != ISD::ConstantFP)
10678 break;
10679 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010680 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010681 if (FoldOp.getOpcode() != ISD::UNDEF &&
10682 FoldOp.getOpcode() != ISD::ConstantFP)
10683 break;
10684 Ops.push_back(FoldOp);
10685 AddToWorkList(FoldOp.getNode());
10686 }
10687
10688 if (Ops.size() != N0.getNumOperands())
10689 return SDValue();
10690
Andrew Trickef9de2a2013-05-25 02:42:55 +000010691 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topper82384612012-09-11 01:45:21 +000010692 N0.getValueType(), &Ops[0], Ops.size());
10693}
10694
Andrew Trickef9de2a2013-05-25 02:42:55 +000010695SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010696 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010697 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010698
Bill Wendling31b50992009-01-30 23:59:18 +000010699 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010700 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010701
Nate Begeman2042aa52005-10-08 00:29:44 +000010702 // If we got a simplified select_cc node back from SimplifySelectCC, then
10703 // break it down into a new SETCC node, and a new SELECT node, and then return
10704 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010705 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010706 // Check to see if we got a select_cc back (to turn into setcc/select).
10707 // Otherwise, just return whatever node we got back, like fabs.
10708 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010709 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010710 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010711 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010712 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010713 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010714 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10715 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010716 }
Bill Wendling31b50992009-01-30 23:59:18 +000010717
Nate Begeman2042aa52005-10-08 00:29:44 +000010718 return SCC;
10719 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010720 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010721}
10722
Chris Lattner6c14c352005-10-18 06:04:22 +000010723/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10724/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010725/// select. Callers of this should assume that TheSelect is deleted if this
10726/// returns true. As such, they should return the appropriate thing (e.g. the
10727/// node) back to the top-level of the DAG combiner loop to avoid it being
10728/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010729bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010730 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010731
Nadav Rotema49a02a2011-02-11 19:57:47 +000010732 // Cannot simplify select with vector condition
10733 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10734
Chris Lattner6c14c352005-10-18 06:04:22 +000010735 // If this is a select from two identical things, try to pull the operation
10736 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010737 if (LHS.getOpcode() != RHS.getOpcode() ||
10738 !LHS.hasOneUse() || !RHS.hasOneUse())
10739 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010740
Chris Lattner254c4452010-09-21 15:46:59 +000010741 // If this is a load and the token chain is identical, replace the select
10742 // of two loads with a load through a select of the address to load from.
10743 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10744 // constants have been dropped into the constant pool.
10745 if (LHS.getOpcode() == ISD::LOAD) {
10746 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10747 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010748
Chris Lattner254c4452010-09-21 15:46:59 +000010749 // Token chains must be identical.
10750 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010751 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010752 LLD->isVolatile() || RLD->isVolatile() ||
10753 // If this is an EXTLOAD, the VT's must match.
10754 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010755 // If this is an EXTLOAD, the kind of extension must match.
10756 (LLD->getExtensionType() != RLD->getExtensionType() &&
10757 // The only exception is if one of the extensions is anyext.
10758 LLD->getExtensionType() != ISD::EXTLOAD &&
10759 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010760 // FIXME: this discards src value information. This is
10761 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010762 // both potential memory locations. Since we are discarding
10763 // src value info, don't do the transformation if the memory
10764 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010765 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010766 RLD->getPointerInfo().getAddrSpace() != 0 ||
10767 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10768 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010769 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010770
Chris Lattnere3267522010-09-21 15:58:55 +000010771 // Check that the select condition doesn't reach either load. If so,
10772 // folding this will induce a cycle into the DAG. If not, this is safe to
10773 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010774 SDValue Addr;
10775 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010776 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10777 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10778 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10779 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010780 // The loads must not depend on one another.
10781 if (LLD->isPredecessorOf(RLD) ||
10782 RLD->isPredecessorOf(LLD))
10783 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010784 Addr = DAG.getSelect(SDLoc(TheSelect),
10785 LLD->getBasePtr().getValueType(),
10786 TheSelect->getOperand(0), LLD->getBasePtr(),
10787 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010788 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010789 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10790 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10791
10792 if ((LLD->hasAnyUseOfValue(1) &&
10793 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010794 (RLD->hasAnyUseOfValue(1) &&
10795 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010796 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010797
Andrew Trickef9de2a2013-05-25 02:42:55 +000010798 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010799 LLD->getBasePtr().getValueType(),
10800 TheSelect->getOperand(0),
10801 TheSelect->getOperand(1),
10802 LLD->getBasePtr(), RLD->getBasePtr(),
10803 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010804 }
10805
Chris Lattnere3267522010-09-21 15:58:55 +000010806 SDValue Load;
10807 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10808 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010809 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010810 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010811 LLD->getChain(), Addr, MachinePointerInfo(),
10812 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010813 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010814 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010815 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10816 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010817 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010818 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010819 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010820 LLD->getChain(), Addr, MachinePointerInfo(),
10821 LLD->getMemoryVT(), LLD->isVolatile(),
10822 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010823 }
Chris Lattnere3267522010-09-21 15:58:55 +000010824
10825 // Users of the select now use the result of the load.
10826 CombineTo(TheSelect, Load);
10827
10828 // Users of the old loads now use the new load's chain. We know the
10829 // old-load value is dead now.
10830 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10831 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10832 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010833 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010834
Chris Lattner6c14c352005-10-18 06:04:22 +000010835 return false;
10836}
10837
Chris Lattner43d63772009-03-11 05:08:08 +000010838/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10839/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010840SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010841 SDValue N2, SDValue N3,
10842 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010843 // (x ? y : y) -> y.
10844 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010845
Owen Anderson53aa7a92009-08-10 22:56:29 +000010846 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010847 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10848 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10849 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010850
10851 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010852 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010853 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010854 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10855 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010856
10857 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010858 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010859 return N2;
10860 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010861 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010862 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010863
Nate Begeman2042aa52005-10-08 00:29:44 +000010864 // Check to see if we can simplify the select into an fabs node
10865 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10866 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010867 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010868 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10869 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10870 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10871 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010872 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010873
Nate Begeman2042aa52005-10-08 00:29:44 +000010874 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10875 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10876 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10877 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010878 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010879 }
10880 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010881
Chris Lattner43d63772009-03-11 05:08:08 +000010882 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10883 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10884 // in it. This is a win when the constant is not otherwise available because
10885 // it replaces two constant pool loads with one. We only do this if the FP
10886 // type is known to be legal, because if it isn't, then we are before legalize
10887 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010888 // messing with soft float) and if the ConstantFP is not legal, because if
10889 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010890 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10891 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10892 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010893 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10894 TargetLowering::Legal) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010895 // If both constants have multiple uses, then we won't need to do an
10896 // extra load, they are likely around in registers for other users.
10897 (TV->hasOneUse() || FV->hasOneUse())) {
10898 Constant *Elts[] = {
10899 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10900 const_cast<ConstantFP*>(TV->getConstantFPValue())
10901 };
Chris Lattner229907c2011-07-18 04:54:35 +000010902 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010903 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010904
Chris Lattner43d63772009-03-11 05:08:08 +000010905 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010906 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010907 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10908 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000010909 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000010910
10911 // Get the offsets to the 0 and 1 element of the array so that we can
10912 // select between them.
10913 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010914 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000010915 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000010916
Chris Lattner43d63772009-03-11 05:08:08 +000010917 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000010918 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000010919 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010920 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010921 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10922 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010923 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000010924 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000010925 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010926 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000010927 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000010928 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000010929 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000010930
10931 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010932 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010933
Nate Begeman2042aa52005-10-08 00:29:44 +000010934 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000010935 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000010936 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000010937 (N1C->isNullValue() || // (a < 0) ? b : 0
10938 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000010939 EVT XType = N0.getValueType();
10940 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000010941 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000010942 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000010943 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010944 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10945 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000010946 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000010947 SDValue ShCt = DAG.getConstant(ShCtV,
10948 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010949 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010950 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010951 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000010952
Duncan Sands11dd4242008-06-08 20:54:56 +000010953 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000010954 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010955 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010956 }
Bill Wendling31b50992009-01-30 23:59:18 +000010957
10958 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000010959 }
Bill Wendling31b50992009-01-30 23:59:18 +000010960
Andrew Trickef9de2a2013-05-25 02:42:55 +000010961 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010962 XType, N0,
10963 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010964 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010965 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000010966
Duncan Sands11dd4242008-06-08 20:54:56 +000010967 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000010968 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010969 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010970 }
Bill Wendling31b50992009-01-30 23:59:18 +000010971
10972 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000010973 }
10974 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010975
Owen Anderson3231d132010-09-22 22:58:22 +000010976 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10977 // where y is has a single bit set.
10978 // A plaintext description would be, we can turn the SELECT_CC into an AND
10979 // when the condition can be materialized as an all-ones register. Any
10980 // single bit-test can be materialized as an all-ones register with
10981 // shift-left and shift-right-arith.
10982 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10983 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000010984 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000010985 N2C && N2C->isNullValue()) {
10986 SDValue AndLHS = N0->getOperand(0);
10987 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10988 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10989 // Shift the tested bit over the sign bit.
10990 APInt AndMask = ConstAndRHS->getAPIntValue();
10991 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000010992 DAG.getConstant(AndMask.countLeadingZeros(),
10993 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010994 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000010995
Owen Anderson3231d132010-09-22 22:58:22 +000010996 // Now arithmetic right shift it all the way over, so the result is either
10997 // all-ones, or zero.
10998 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000010999 DAG.getConstant(AndMask.getBitWidth()-1,
11000 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011001 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011002
Owen Anderson3231d132010-09-22 22:58:22 +000011003 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11004 }
11005 }
11006
Nate Begeman6828ed92005-10-10 21:26:48 +000011007 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011008 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000011009 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11010 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011011
Chris Lattnera083ffc2007-04-11 06:50:51 +000011012 // If the caller doesn't want us to simplify this into a zext of a compare,
11013 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011014 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011015 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011016
Nate Begeman6828ed92005-10-10 21:26:48 +000011017 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011018 // NOTE: Don't create a SETCC if it's not legal on this target.
11019 if (!LegalOperations ||
11020 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011021 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011022 SDValue Temp, SCC;
11023 // cast from setcc result type to select result type
11024 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011025 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011026 N0, N1, CC);
11027 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011028 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011029 N2.getValueType());
11030 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011031 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011032 N2.getValueType(), SCC);
11033 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011034 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11035 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011036 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011037 }
11038
11039 AddToWorkList(SCC.getNode());
11040 AddToWorkList(Temp.getNode());
11041
11042 if (N2C->getAPIntValue() == 1)
11043 return Temp;
11044
11045 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011046 return DAG.getNode(
11047 ISD::SHL, DL, N2.getValueType(), Temp,
11048 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11049 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011050 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011051 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011052
Nate Begeman2042aa52005-10-08 00:29:44 +000011053 // Check to see if this is the equivalent of setcc
11054 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11055 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011056 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011057 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011058 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011059 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11060 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011061 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011062 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011063 return Res;
11064 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011065
Bill Wendling31b50992009-01-30 23:59:18 +000011066 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011067 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011068 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011069 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011070 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011071 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011072 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011073 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011074 }
Bill Wendling31b50992009-01-30 23:59:18 +000011075 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011076 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011077 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011078 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011079 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011080 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011081 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011082 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011083 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011084 }
Bill Wendling31b50992009-01-30 23:59:18 +000011085 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011086 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011087 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011088 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011089 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011090 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011091 }
11092 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011093
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011094 // Check to see if this is an integer abs.
11095 // select_cc setg[te] X, 0, X, -X ->
11096 // select_cc setgt X, -1, X, -X ->
11097 // select_cc setl[te] X, 0, -X, X ->
11098 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011099 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011100 if (N1C) {
11101 ConstantSDNode *SubC = NULL;
11102 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11103 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11104 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11105 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11106 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11107 (N1C->isOne() && CC == ISD::SETLT)) &&
11108 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11109 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11110
Owen Anderson53aa7a92009-08-10 22:56:29 +000011111 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011112 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011113 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011114 N0,
11115 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011116 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011117 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011118 XType, N0, Shift);
11119 AddToWorkList(Shift.getNode());
11120 AddToWorkList(Add.getNode());
11121 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011122 }
11123 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011124
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011125 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011126}
11127
Evan Cheng92658d52007-02-08 22:13:59 +000011128/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011129SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011130 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011131 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011132 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011133 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011134 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011135}
11136
Nate Begemanc6f067a2005-10-20 02:15:44 +000011137/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11138/// return a DAG expression to select that will generate the same value by
11139/// multiplying by a magic number. See:
11140/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011141SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011142 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011143 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011144
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011145 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011146 ii != ee; ++ii)
11147 AddToWorkList(*ii);
11148 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011149}
11150
11151/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11152/// return a DAG expression to select that will generate the same value by
11153/// multiplying by a magic number. See:
11154/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011155SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011156 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011157 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011158
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011159 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011160 ii != ee; ++ii)
11161 AddToWorkList(*ii);
11162 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011163}
11164
Nate Begeman18150d52009-09-25 06:05:26 +000011165/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011166// to alias with anything but itself. Provides base object and offset as
11167// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011168static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011169 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011170 // Assume it is a primitive operation.
Nate Begeman18150d52009-09-25 06:05:26 +000011171 Base = Ptr; Offset = 0; GV = 0; CV = 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011172
Jim Laskey0463e082006-10-07 23:37:56 +000011173 // If it's an adding a simple constant then integrate the offset.
11174 if (Base.getOpcode() == ISD::ADD) {
11175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11176 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011177 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011178 }
11179 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011180
Nate Begeman18150d52009-09-25 06:05:26 +000011181 // Return the underlying GlobalValue, and update the Offset. Return false
11182 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11183 // by multiple nodes with different offsets.
11184 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11185 GV = G->getGlobal();
11186 Offset += G->getOffset();
11187 return false;
11188 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011189
Nate Begeman18150d52009-09-25 06:05:26 +000011190 // Return the underlying Constant value, and update the Offset. Return false
11191 // for ConstantSDNodes since the same constant pool entry may be represented
11192 // by multiple nodes with different offsets.
11193 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011194 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11195 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011196 Offset += C->getOffset();
11197 return false;
11198 }
Jim Laskey0463e082006-10-07 23:37:56 +000011199 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011200 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011201}
11202
11203/// isAlias - Return true if there is any possibility that the two addresses
11204/// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011205bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011206 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +000011207 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011208 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011209 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +000011210 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011211 unsigned SrcValueAlign2,
11212 const MDNode *TBAAInfo2) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011213 // If they are the same then they must be aliases.
11214 if (Ptr1 == Ptr2) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011215
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011216 // If they are both volatile then they cannot be reordered.
11217 if (IsVolatile1 && IsVolatile2) return true;
11218
Jim Laskey0463e082006-10-07 23:37:56 +000011219 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011220 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011221 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011222 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011223 const void *CV1, *CV2;
Nate Begeman18150d52009-09-25 06:05:26 +000011224 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11225 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011226
Nate Begeman18150d52009-09-25 06:05:26 +000011227 // If they have a same base address then check to see if they overlap.
11228 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Bill Wendling31b50992009-01-30 23:59:18 +000011229 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011230
Owen Anderson272ff942010-09-20 20:39:59 +000011231 // It is possible for different frame indices to alias each other, mostly
11232 // when tail call optimization reuses return address slots for arguments.
11233 // To catch this case, look up the actual index of frame indices to compute
11234 // the real alias relationship.
11235 if (isFrameIndex1 && isFrameIndex2) {
11236 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11237 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11238 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11239 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11240 }
11241
Wesley Peck527da1b2010-11-23 03:31:01 +000011242 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011243 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011244 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11245 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011246
Nate Begeman879d8f12009-09-15 00:18:30 +000011247 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11248 // compared to the size and offset of the access, we may be able to prove they
11249 // do not alias. This check is conservative for now to catch cases created by
11250 // splitting vector types.
11251 if ((SrcValueAlign1 == SrcValueAlign2) &&
11252 (SrcValueOffset1 != SrcValueOffset2) &&
11253 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11254 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11255 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
Wesley Peck527da1b2010-11-23 03:31:01 +000011256
Nate Begeman879d8f12009-09-15 00:18:30 +000011257 // There is no overlap between these relatively aligned accesses of similar
11258 // size, return no alias.
11259 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11260 return false;
11261 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011262
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011263 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11264 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011265#ifndef NDEBUG
11266 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11267 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11268 UseAA = false;
11269#endif
Hal Finkel31658832013-09-15 02:19:49 +000011270 if (UseAA && SrcValue1 && SrcValue2) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011271 // Use alias analysis information.
Dan Gohman9625d812007-08-27 16:32:11 +000011272 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11273 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11274 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011275 AliasAnalysis::AliasResult AAResult =
Hal Finkeldbebb522014-01-25 19:24:54 +000011276 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11277 UseTBAA ? TBAAInfo1 : 0),
11278 AliasAnalysis::Location(SrcValue2, Overlap2,
11279 UseTBAA ? TBAAInfo2 : 0));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011280 if (AAResult == AliasAnalysis::NoAlias)
11281 return false;
11282 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011283
11284 // Otherwise we have to assume they alias.
11285 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011286}
11287
Nadav Rotem307d7672012-11-29 00:00:08 +000011288bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11289 SDValue Ptr0, Ptr1;
11290 int64_t Size0, Size1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011291 bool IsVolatile0, IsVolatile1;
Nadav Rotem307d7672012-11-29 00:00:08 +000011292 const Value *SrcValue0, *SrcValue1;
11293 int SrcValueOffset0, SrcValueOffset1;
11294 unsigned SrcValueAlign0, SrcValueAlign1;
11295 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011296 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotem307d7672012-11-29 00:00:08 +000011297 SrcValueAlign0, SrcTBAAInfo0);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011298 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotem307d7672012-11-29 00:00:08 +000011299 SrcValueAlign1, SrcTBAAInfo1);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011300 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011301 SrcValueAlign0, SrcTBAAInfo0,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011302 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011303 SrcValueAlign1, SrcTBAAInfo1);
Nadav Rotem307d7672012-11-29 00:00:08 +000011304}
11305
Jim Laskey0463e082006-10-07 23:37:56 +000011306/// FindAliasInfo - Extracts the relevant alias information from the memory
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011307/// node. Returns true if the operand was a nonvolatile load.
Jim Laskey08edf332006-10-11 13:47:09 +000011308bool DAGCombiner::FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011309 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011310 const Value *&SrcValue,
11311 int &SrcValueOffset,
11312 unsigned &SrcValueAlign,
11313 const MDNode *&TBAAInfo) const {
11314 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11315
11316 Ptr = LS->getBasePtr();
11317 Size = LS->getMemoryVT().getSizeInBits() >> 3;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011318 IsVolatile = LS->isVolatile();
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011319 SrcValue = LS->getSrcValue();
11320 SrcValueOffset = LS->getSrcValueOffset();
11321 SrcValueAlign = LS->getOriginalAlignment();
11322 TBAAInfo = LS->getTBAAInfo();
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011323 return isa<LoadSDNode>(LS) && !IsVolatile;
Jim Laskey0463e082006-10-07 23:37:56 +000011324}
11325
Jim Laskey708d0db2006-10-04 16:53:27 +000011326/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11327/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011328void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011329 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011330 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011331 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011332
Jim Laskeyd07be232006-09-25 16:29:54 +000011333 // Get alias information for node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011334 SDValue Ptr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011335 int64_t Size;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011336 bool IsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011337 const Value *SrcValue;
11338 int SrcValueOffset;
11339 unsigned SrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011340 const MDNode *SrcTBAAInfo;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011341 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11342 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
Jim Laskeyd07be232006-09-25 16:29:54 +000011343
Jim Laskey708d0db2006-10-04 16:53:27 +000011344 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011345 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011346 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011347
Jim Laskey6549d222006-10-05 15:07:25 +000011348 // Look at each chain and determine if it is an alias. If so, add it to the
11349 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011350 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011351 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011352 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011353 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011354
11355 // For TokenFactor nodes, look at each operand and only continue up the
11356 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011357 // find more and revert to original chain since the xform is unlikely to be
11358 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011359 //
11360 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011361 // chain we found before we hit a tokenfactor rather than the original
11362 // chain.
11363 if (Depth > 6 || Aliases.size() == 2) {
11364 Aliases.clear();
11365 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011366 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011367 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011368
Nate Begeman879d8f12009-09-15 00:18:30 +000011369 // Don't bother if we've been before.
11370 if (!Visited.insert(Chain.getNode()))
11371 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011372
Jim Laskey6549d222006-10-05 15:07:25 +000011373 switch (Chain.getOpcode()) {
11374 case ISD::EntryToken:
11375 // Entry token is ideal chain operand, but handled in FindBetterChain.
11376 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011377
Jim Laskey6549d222006-10-05 15:07:25 +000011378 case ISD::LOAD:
11379 case ISD::STORE: {
11380 // Get alias information for Chain.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011381 SDValue OpPtr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011382 int64_t OpSize;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011383 bool OpIsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011384 const Value *OpSrcValue;
11385 int OpSrcValueOffset;
11386 unsigned OpSrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011387 const MDNode *OpSrcTBAAInfo;
Gabor Greiff304a7a2008-08-28 21:40:38 +000011388 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011389 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011390 OpSrcValueAlign,
11391 OpSrcTBAAInfo);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011392
Jim Laskey6549d222006-10-05 15:07:25 +000011393 // If chain is alias then stop here.
11394 if (!(IsLoad && IsOpLoad) &&
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011395 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11396 SrcValueAlign, SrcTBAAInfo,
11397 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011398 OpSrcValueAlign, OpSrcTBAAInfo)) {
Jim Laskey6549d222006-10-05 15:07:25 +000011399 Aliases.push_back(Chain);
11400 } else {
11401 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011402 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011403 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011404 }
Jim Laskey6549d222006-10-05 15:07:25 +000011405 break;
11406 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011407
Jim Laskey6549d222006-10-05 15:07:25 +000011408 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011409 // We have to check each of the operands of the token factor for "small"
11410 // token factors, so we queue them up. Adding the operands to the queue
11411 // (stack) in reverse order maintains the original order and increases the
11412 // likelihood that getNode will find a matching token factor (CSE.)
11413 if (Chain.getNumOperands() > 16) {
11414 Aliases.push_back(Chain);
11415 break;
11416 }
Jim Laskey6549d222006-10-05 15:07:25 +000011417 for (unsigned n = Chain.getNumOperands(); n;)
11418 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011419 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011420 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011421
Jim Laskey6549d222006-10-05 15:07:25 +000011422 default:
11423 // For all other instructions we will just have to take what we can get.
11424 Aliases.push_back(Chain);
11425 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011426 }
11427 }
Hal Finkel51a98382014-01-24 20:12:02 +000011428
11429 // We need to be careful here to also search for aliases through the
11430 // value operand of a store, etc. Consider the following situation:
11431 // Token1 = ...
11432 // L1 = load Token1, %52
11433 // S1 = store Token1, L1, %51
11434 // L2 = load Token1, %52+8
11435 // S2 = store Token1, L2, %51+8
11436 // Token2 = Token(S1, S2)
11437 // L3 = load Token2, %53
11438 // S3 = store Token2, L3, %52
11439 // L4 = load Token2, %53+8
11440 // S4 = store Token2, L4, %52+8
11441 // If we search for aliases of S3 (which loads address %52), and we look
11442 // only through the chain, then we'll miss the trivial dependence on L1
11443 // (which also loads from %52). We then might change all loads and
11444 // stores to use Token1 as their chain operand, which could result in
11445 // copying %53 into %52 before copying %52 into %51 (which should
11446 // happen first).
11447 //
11448 // The problem is, however, that searching for such data dependencies
11449 // can become expensive, and the cost is not directly related to the
11450 // chain depth. Instead, we'll rule out such configurations here by
11451 // insisting that we've visited all chain users (except for users
11452 // of the original chain, which is not necessary). When doing this,
11453 // we need to look through nodes we don't care about (otherwise, things
11454 // like register copies will interfere with trivial cases).
11455
11456 SmallVector<const SDNode *, 16> Worklist;
11457 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11458 IE = Visited.end(); I != IE; ++I)
11459 if (*I != OriginalChain.getNode())
11460 Worklist.push_back(*I);
11461
11462 while (!Worklist.empty()) {
11463 const SDNode *M = Worklist.pop_back_val();
11464
11465 // We have already visited M, and want to make sure we've visited any uses
11466 // of M that we care about. For uses that we've not visisted, and don't
11467 // care about, queue them to the worklist.
11468
11469 for (SDNode::use_iterator UI = M->use_begin(),
11470 UIE = M->use_end(); UI != UIE; ++UI)
11471 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11472 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11473 // We've not visited this use, and we care about it (it could have an
11474 // ordering dependency with the original node).
11475 Aliases.clear();
11476 Aliases.push_back(OriginalChain);
11477 return;
11478 }
11479
11480 // We've not visited this use, but we don't care about it. Mark it as
11481 // visited and enqueue it to the worklist.
11482 Worklist.push_back(*UI);
11483 }
11484 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011485}
11486
11487/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11488/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011489SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11490 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011491
Jim Laskey708d0db2006-10-04 16:53:27 +000011492 // Accumulate all the aliases to this node.
11493 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011494
Dan Gohman4298df62011-05-17 22:20:36 +000011495 // If no operands then chain to entry token.
11496 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011497 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011498
11499 // If a single operand then chain to it. We don't need to revisit it.
11500 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011501 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011502
Jim Laskey708d0db2006-10-04 16:53:27 +000011503 // Construct a custom tailored token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011504 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begeman879d8f12009-09-15 00:18:30 +000011505 &Aliases[0], Aliases.size());
Jim Laskeyd07be232006-09-25 16:29:54 +000011506}
11507
Nate Begeman21158fc2005-09-01 00:19:25 +000011508// SelectionDAG::Combine - This is the entry point for the file.
11509//
Bill Wendling084669a2009-04-29 00:15:41 +000011510void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011511 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011512 /// run - This is the main entry point to this class.
11513 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011514 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011515}